hledger-lib 0.16.1 → 2.0
raw patch · 97 files changed
Files
- CHANGES.md +2295/−0
- Hledger.hs +395/−8
- Hledger/Data.hs +56/−25
- Hledger/Data/Account.hs +377/−16
- Hledger/Data/AccountName.hs +444/−146
- Hledger/Data/AccountType.hs +124/−0
- Hledger/Data/Amount.hs +1705/−465
- Hledger/Data/BalanceData.hs +59/−0
- Hledger/Data/Balancing.hs +1556/−0
- Hledger/Data/Commodity.hs +0/−67
- Hledger/Data/Currency.hs +196/−0
- Hledger/Data/Dates.hs +1308/−685
- Hledger/Data/DayPartition.hs +343/−0
- Hledger/Data/Errors.hs +285/−0
- Hledger/Data/Journal.hs +1971/−436
- Hledger/Data/JournalChecks.hs +405/−0
- Hledger/Data/JournalChecks/Assert.hs +410/−0
- Hledger/Data/JournalChecks/Ordereddates.hs +65/−0
- Hledger/Data/JournalChecks/Uniqueleafnames.hs +72/−0
- Hledger/Data/Json.hs +346/−0
- Hledger/Data/Ledger.hs +74/−109
- Hledger/Data/Lots.hs +3086/−0
- Hledger/Data/Matching.hs +0/−324
- Hledger/Data/Period.hs +360/−0
- Hledger/Data/PeriodData.hs +138/−0
- Hledger/Data/PeriodicTransaction.hs +263/−0
- Hledger/Data/Posting.hs +995/−163
- Hledger/Data/RawOptions.hs +166/−0
- Hledger/Data/StringFormat.hs +192/−0
- Hledger/Data/TimeLog.hs +0/−129
- Hledger/Data/Timeclock.hs +310/−0
- Hledger/Data/Transaction.hs +779/−415
- Hledger/Data/TransactionModifier.hs +158/−0
- Hledger/Data/Types.hs +971/−205
- Hledger/Data/Valuation.hs +691/−0
- Hledger/Query.hs +1598/−0
- Hledger/Read.hs +473/−126
- Hledger/Read/Common.hs +2557/−0
- Hledger/Read/CsvReader.hs +89/−0
- Hledger/Read/InputOptions.hs +159/−0
- Hledger/Read/JournalReader.hs +2330/−851
- Hledger/Read/LatestDates.hs +111/−0
- Hledger/Read/RulesReader.hs +2717/−0
- Hledger/Read/TimeclockReader.hs +253/−0
- Hledger/Read/TimedotReader.hs +289/−0
- Hledger/Read/TimelogReader.hs +0/−104
- Hledger/Read/Utils.hs +0/−86
- Hledger/Reports.hs +30/−598
- Hledger/Reports/AccountTransactionsReport.hs +348/−0
- Hledger/Reports/BalanceReport.hs +330/−0
- Hledger/Reports/BudgetReport.hs +268/−0
- Hledger/Reports/EntriesReport.hs +59/−0
- Hledger/Reports/MultiBalanceReport.hs +639/−0
- Hledger/Reports/PostingsReport.hs +483/−0
- Hledger/Reports/ReportOptions.hs +1159/−0
- Hledger/Reports/ReportTypes.hs +249/−0
- Hledger/Utils.hs +282/−374
- Hledger/Utils/Debug.hs +718/−0
- Hledger/Utils/I18n.hs +1020/−0
- Hledger/Utils/IO.hs +1152/−0
- Hledger/Utils/Parse.hs +670/−0
- Hledger/Utils/Regex.hs +315/−0
- Hledger/Utils/String.hs +301/−0
- Hledger/Utils/Test.hs +150/−0
- Hledger/Utils/Text.hs +308/−0
- Hledger/Utils/UTF8.hs +0/−87
- Hledger/Write/Beancount.hs +574/−0
- Hledger/Write/Chart.hs +502/−0
- Hledger/Write/Chart/Palette.hs +96/−0
- Hledger/Write/Chart/Svg.hs +1051/−0
- Hledger/Write/Chart/Text.hs +414/−0
- Hledger/Write/Csv.hs +56/−0
- Hledger/Write/Html.hs +219/−0
- Hledger/Write/Html/Attribute.hs +69/−0
- Hledger/Write/Journal.hs +108/−0
- Hledger/Write/Ledger.hs +74/−0
- Hledger/Write/Ods.hs +401/−0
- Hledger/Write/Spreadsheet.hs +300/−0
- LICENSE +4/−4
- README.md +9/−0
- Text/Tabular/AsciiWide.hs +323/−0
- Text/WideString.hs +39/−0
- hledger-lib.cabal +318/−72
- locale/de.po +3053/−0
- locale/es.po +3133/−0
- locale/fr.po +2833/−0
- locale/ga.po +2837/−0
- locale/haw.po +2833/−0
- locale/hledger.pot +2644/−0
- locale/it.po +3264/−0
- locale/ja.po +2829/−0
- locale/pt-BR.po +2833/−0
- locale/ru.po +3148/−0
- locale/uk.po +3321/−0
- locale/zh-Hans.po +3156/−0
- test/doctests.hs +68/−0
- test/unittest.hs +13/−0
+ CHANGES.md view
@@ -0,0 +1,2295 @@+<!--+ _ _ _+| (_) |__+| | | '_ \+| | | |_) |+|_|_|_.__/++Item order: security fixes first, then breaking changes, then the rest.+Section headings: "Security" first if any, then "Breaking changes"+if any; then topic headings,+or a suitable generic heading (eg Fixes, Improvements), as needed.++-->++API/developer-ish changes in hledger-lib.+For user-visible changes, see the hledger package changelog.+++# 2.0 2026-12-01++All API changes since hledger-lib 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>.+For user-visible changes, see the hledger, hledger-ui and hledger-web changelogs.++## Breaking changes++- `PostingType`/`RegularPosting`/`ptype` are renamed to `PostingRealness`/`RealPosting`/`preal`,+ to avoid confusion with the new `ptype` tag. This changes postings' JSON.++- Journal's jfiles is now a list of JournalFile records (jfpath, jftext, and jfdepth, the include depth), instead of (path, text) pairs.+ jauxfiles records the non-journal files the data came from (CSV rules files, the files they include, and files read by `source` rules),+ paired with the data file they were used to read, so callers watching for changes can watch those too.+ A new jitems field records every top-level item of the journal file(s) (directives, transactions, comments, blank lines),+ for print --export; jfinalcommentlines is removed. jasserts holds the assert rules.+ Journal's JSON no longer includes its transient jparse* parser-state fields.++- Query: Amt has a new `Maybe CommoditySymbol` field; there are new Find, Change and Balance constructors;+ the unused empty: query prefix is dropped. `matchesPayeeWIP` is renamed `matchesPayee`, now matching declared payees strictly,+ and `matchesDescription` is dropped.++- AccountType has new Gain (G), UnrealisedGain (U) and Imbalance (M) constructors.+ `isAccountSubtypeOf` has moved from Hledger.Data.Types to Hledger.Data.AccountType.++- Commodity gains csourcepos and caliases fields. Commodity aliases are applied by a new finalisation step, journalApplyCommodityAliases.+ A repeated commodity declaration is combined with the earlier one (commodityCombine, combineCommodityDeclarations), rather than replacing it.++- `--alias` options are kept apart from the journal's own aliases, in a new jparseoptaliases parse state field, and are applied after them;+ alias directives and alias: tags now apply before the apply account prefix. Hledger.Read.Common.accountNameApplyModifiers explains the order.+ The popParentAccount helper is removed.+ ([#2733])++- Lot disposals balance at cost basis (see the hledger changelog); lot postings are marked by a hidden `_ptype` tag.+ Equity inference now runs after lot processing.++- Hledger.Write.Html replaces Write.Html.Lucid, Write.Html.Blaze and Write.Html.HtmlCommon; lucid is no longer a dependency.+ (Arthur Cinader, [#2737])++- Renames: TBPOld and TBPExact are now TBPDisplay and TBPEntry; `defaultMaxPrecision` is `defaultMaxDisplayPrecision`;+ `sumSimilarAmountsUsingFirstCost` is `sumSimilarAmounts`; Hledger.Utils.Text's quote helpers are `textStripQuotes`, `textIsSingleQuoted`+ and `textIsDoubleQuoted` (the String versions are exported from Hledger.Utils.String).+ transactionRoundCalculatedAmounts and postingRoundCalculatedAmounts are in Hledger.Data.Balancing.++- readJournalFromCsv now also returns an error-context-adding function.+ sourcePosPairPretty renders a single-line range as "FILE:5", not "FILE:5-5".+ `postingsAsLines`/`postingAsLines` take an `AmountFormat`, which gains a `displayLedgerLotSyntax` field.+ `escapeName` now also escapes `]`, `{`, `}`, and `.`.++## Fixes++- `divideAmount`/`divideMixedAmount` no longer raise an error when dividing by zero; they return the amount unchanged.++- `amountIntegerWidth` was one too wide with a negative amount that truncates to 0 with `Precision 0` (eg -0.3).++## Improvements++- Lots: the new Hledger.Data.Lots module is the lot-tracking pipeline: posting classification,+ lot calculation (FIFO/LIFO/HIFO/AVERAGE and *ALL variants, long and short), gain posting inference, and lot subaccount name parsing;+ with journalAveragePoolTotals and journalAveragePoolCosts, the AVERAGE pool calculations shared by holdings and close.+ `lotcostp` parses both `{DATE, "LABEL", COST}` and Ledger-style `{COST} [DATE] (NOTE)` annotations.+ Hledger.Write.Ledger provides `showTransactionLedger`, for Ledger-style lot syntax output.++- Charts: Hledger.Write.Chart is a renderer-independent chart model (a title, an x axis of categories, periods or dates, and panels of series);+ Hledger.Write.Chart.Text and Hledger.Write.Chart.Svg render it as styled text lines or SVG, with the colours in Hledger.Write.Chart.Palette.+ chartAsCsv gives a chart's data. chartSvgMarkupWith takes SvgOptions, for charts embedded in a page.+ blaze-svg >=0.3.7 is a new dependency.+ (Simon Michael, Arthur Cinader, [#2800])++- Translations: the new Hledger.Utils.I18n module provides translations from gettext PO catalogs.+ A Translations value maps English text to a translation; tr, trc, trf and trn look text up, with contexts, {name} placeholders and plural forms.+ ReportOpts gains translations_; showPeriodAbbrevWith and showDateSpanAbbrevWith take a TimeLocale.+ (Arthur Cinader)++- Assert rules: Journal's jasserts holds AssertDirective values; Hledger.Data.JournalChecks.Assert's journalCheckAsserts checks them,+ as does Hledger.Read.Common's journalCheckAssertsWith. Hledger.Query.postingQueryForAccount partially evaluates a query for one account.++- change: and balance: queries are not tested against postings: querySplitRowTerms moves them into ReportSpec's new+ _rsRowQuery field, which the reports apply after aggregating (with matchesRowAmounts).+ Also new: parseAmountQueryArg, queryIsChange, queryIsBalance, queryIsRowTerm, queryHasBalance, queryHasChange, queryIsFlatDepth.++- The journal parser (Hledger.Read.JournalReader) has fast-path parsers, used when possible;+ they can be disabled with HLEDGER_FASTPATH=off, or checked against the general parser with HLEDGER_FASTPATH=check.+ Hledger.Utils.Parse gains peekChar, peekChars2, peekAfterSpaces and manyWhile, cheap lookahead helpers.+ The parse state has a new jparseapplyyears field, for scoped apply year.++- InputOpts has new internal fields: _fileoverrides (replacement text for some files, so a change can be checked before it is written),+ _scanfiles (find the files read, without processing data), and _forecastOnlyForDisplay (so assert rules ignore display-only forecast transactions).++- Reports: ReportOpts gains fold_depth_. Hledger.Reports.PostingsReport gains postingsReportStartBalances;+ accountTransactionsReportWithStart also returns the starting balance. showDateSpanForQuery renders a date span as a period expression+ that parses back to the same span. Spreadsheet cells gain cellTitle (a link title) and cellParts (a multi-commodity amount's individual amounts);+ `showMixedAmountOneLinePartsB` returns those. The barewide balance layout is supported.+ (Arthur Cinader, Henning Thielemann)++- Periods: the lazy splitSpanToDateSpans (and splitSpanBoundaries) let register and periodic rules run in constant memory.+ Hledger.Data.Dates exports reportingintervalp.++- Utilities: `dbgTime`, `dbgTimeIO` and `dbgTimeResetIO` (time and memory reporting); `warnIO` emits through a handler settable with+ `setWarningHandler`, so a TUI can collect warnings; `wordsmay` and `wordsEither` (total variants of `words'`, which now tokenises quotes more like the shell);+ `regexEscape`; `quoteForQuery` (Arthur Cinader); `shellQuoteIfNeeded`; `withFileOrStdout`; `multiplyQuantities`; `amountSetQuantity`;+ `commentPrependTag`; `postingRemoveHiddenAndVisibleTag`; `decorateExcerpt` and `makePostingErrorExcerptByIndex`;+ `journalBaseCurrency` and `journalBaseCurrencyCode`. `showPriceDirective` is consolidated in Hledger.Data.Amount.+ CSV rules' ConditionalBlock has a new cbPos field.++- Hledger.Write.Ods enables digit grouping if the AmountStyle declares any digit groups, and its CommodityStyle is a custom data type.+ (Henning Thielemann)++- Hledger.Data.Currency knows some cryptocurrency symbols (roughly the top 100 by market cap).++- Text.Tabular.AsciiWide's renderColumns is faster with many-line cells.+ (Dmitry Astapov)++- aeson 2.2.5.1 or newer is required (avoiding HSEC-2026-0007); megaparsec 9.8.0 is excluded+ ([megaparsec#572](https://github.com/mrkkrp/megaparsec/issues/572)); doclayout 0.6 is allowed.++[#2733]: https://github.com/hledgerorg/hledger/issues/2733+[#2737]: https://github.com/hledgerorg/hledger/issues/2737+[#2800]: https://github.com/hledgerorg/hledger/issues/2800+++# 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)).+++# 1.52.3 2026-08-27++++# 1.52.2 2026-08-24++++# 1.52.1 2026-04-28+++# 1.52 2026-03-20++Breaking changes++- A cost basis field (`acostbasis`) has been added to Amount (to store Ledger/Beancount-style cost basis annotations).++Fixes++- invertAmount: with zero amounts, do nothing instead of failing.+ Previously `invertAmount` would raise a "Ratio has zero denominator"+ exception if the amount's quantity was zero. Now it's a no-op in that case.+ [#2476]++[#2476]: https://github.com/hledgerorg/hledger/issues/2476+++# 1.51.2 2026-01-08++- Allow base 4.22 / ghc 9.14.++# 1.51.1 2025-12-08++# 1.50.5 2025-12-08++# 1.51 2025-12-05++Breaking changes++- Hledger.Data.Balancing: balanceTransaction -> balanceSingleTransaction+- Hledger.Utils.IO:+ - inputToHandle -> textToHandle; set utf8 not utf8_bom+ - readHandlePortably, readHandlePortably' -> hGetContentsPortably++Improvements++- Hledger.Utils.String:+ quoteForCommandLine now quotes some additional problem characters, and no longer quotes "7".+ [#2468]+++# 1.50.4 2025-12-04++# 1.50.3 2025-11-18++# 1.50.2 2025-09-26++# 1.50.1 2025-09-16++# 1.50 2025-09-03++Breaking changes++- hledger now requires at least GHC 9.6 (and base 4.18), to ease maintenance.++Fixes++- Fix liftA2 build error with ghc <9.6 (broken since 1.43.1).++Improvements++- Account now stores balances, one per date period. This enables it do+ the hard work in MultiBalanceReport.+ Some new types are created to enable convenient operation of accounts:+ - `BalanceData` is a type which stores an exclusive balance, inclusive+ balance, and number of postings. This was previously directly stored+ in Account, but is now factored into a separate data type.+ - `PeriodData` is a container which stores date-indexed data, as well as+ pre-period data. In post cases, this represents the report spans,+ along with the historical data.+ - Account becomes polymorphic, allowing customisation of the type of+ data it stores. This will usually be `BalanceData`, but in+ `BudgetReport` it can use `These BalanceData BalanceData` to store+ both actuals and budgets in the same structure. The data structure+ changes to contain a `PeriodData`, allowing multiperiod accounts.+ (Stephen Morgan)+- Hledger.Read: make LatestDatesForFile showable+- Hledger.Read.Common: accountnamep and modifiedaccountnamep now take a flag to allow semicolons or not+- Hledger.Utils.IO: getFlag, warnIO, rename exitOnError -> handleExit, improve doc+- Hledger.Query: matchesCommodity handles all query types, not just cur:, and doesn't match by default+- Hledger.Data.Amount: move commodityStylesFromAmounts here, drop canonicalStyleFrom++# 1.43.2 2025-06-13++- Hledger.Utils.IO: rename exitOnError -> handleExit, improve doc+++# 1.43.1 2025-06-04++- Hledger.Query: queryIsAmtOrSym+++# 1.43 2025-06-01++- Support GHC 9.12.++- Fix doctest suite with ghc-8.10.7 (Thomas Miedema)++- Drop base-compat dependency (Thomas Miedema)++- Added NFData instances for Journal and subcomponents. (Stephen Morgan)++- Hledger.Data.Dates:+ - renamed parsedateM -> parsedate.+ M makes me think of monad and is awkward to type for this common helper.+ Maybe is expected for a parser.+ - parsedate now also accepts YYYYMMDD format, for convenience in ghci and for parseHledgerVersion.+ This is more permissive, now parsing many integers successfully; hopefully that won't be a problem.+ I noted but did not document two user-facing uses, which now also accept YYYYMMDD dates:+ --value's argument, and import's .latest files.++- Hledger.Data.Journal: journalCommoditiesUsed++- Hledger.Read: more ways to read the default journal:+ defaultJournalWith, defaultJournalSafely, defaultJournalSafelyWith++- Hledger.Utils.Debug:+ - Provide simpler, more consistent dbg* names.+ - A few cases of hledger/hledger-ui debug output which were always+ traced to stderr or always logged to a file, now consistently follow+ the policy on whether to trace or log.++- Hledger.Utils.IO:+ - exitOnError, a helper to clean up unicode errors and GHC error output generally.+ - make parseYN(A) total+ - export findPager, getHomeSafe+++# 1.42.2 2025-05-16++- Require extra >= 1.7.11, fixing the stack8.10.yaml build. (Thomas Miedema)+++# 1.42.1 2025-03-12+++# 1.42 2025-03-07++Improvements++- readJournal, when not given a file name, now always assumes it is "-" rather than "(string)".+ [#2328]+- Reader's rReadFn has changed type (for the new CSV text encoding feature);+ it now takes a `Handle` rather than a `Text`, allowing more flexibility.+- Make test/unittest.hs more buildable; remove PackageImports that was causing+ trouble for ghci.+ (Thomas Miedema, [#2337])+- Added: postingNegate+- Renamed: negatePostingAmount -> postingNegateMainAmount+- Refactor Hledger.Write.Html etc, reducing Lucid references.+ Clarify the HTML lib situation a bit, and clean up some imports.+ [#2244]+- Added: dropRawOpt, cliOptsDropArgs+- Hledger.Data.Amount: showAmountCost(B) now drops leading whitespace.+++# 1.41 2024-12-09++Breaking changes++- New/refactored modules (Hledger.Write.*) and types (Spreadsheet) to help+ abstract rendering in various output formats, eg HTML, FODS and beancount.+ Spreadsheet is an abstraction for tabular reports, in addition to the+ tabular package we already use; there may be some overlap.+ (Henning Thielemann)++- Rename displayDepth/prrDepth to displayIndent/prrIndent, and make them+ correspond to the number of indentation steps.+ (These are about indentation for rendering, not account depth.) [#2246]++Improvements++- Add Hledger.Data.Currency, currencySymbolToCode, currencyCodeToSymbol+- AmountFormat: add displayQuotes flag to control enclosing quotes+- InputOpts: add `posting_account_tags_` flag to control account tags on postings+- Support ghc 9.10 and base 4.20.+ Note, when built with ghc 9.10.1, hledger error messages are displayed with two extra trailing newlines.++Other API/doc changes++- Hledger.Utils.IO: cleanup; rgb' now takes Float arguments instead of Word8+- rename jinferredcommodities to jinferredcommoditystyles+- rename jcommodities to jdeclaredcommodities+- move/rename nullsourcepos+- document isBlockActive, matcherMatches+- posting*AsLines: fix some docs++++# 1.40 2024-09-09++Breaking changes++- Some constructors of the Interval type have been renamed for clarity.+- Hledger.Read.CsvUtils has moved to Hledger.Write.Csv. (Henning Thielemann)+- Tabular report rendering code has been added/reworked to allow new output formats and more reuse. (Henning Thielemann)++Improvements++- Added `journalDbg` debug output helper.++- Allow doclayout 0.5.++# 1.34 2024-06-01++Improvements++- InputOpts has a new `_defer` flag for internal use instead of overusing `strict_`+- journalCheckBalanceAssertions has moved to JournalChecks+++# 1.33.1 2024-05-02++- Updates for hledger 1.33.1+++# 1.33 2024-04-18++Breaking changes++Fixes++- Require process 1.6.19.0+ to avoid any vulnerabilities on Windows from+ [HSEC-2024-0003](https://haskell.github.io/security-advisories/advisory/HSEC-2024-0003.html).+ This has also required disabling this package's doctest test suite for the moment.++- A potential Glob/filemanip package conflict in Hledger.Utils.IO now prevented,+ avoiding build failures.+++Improvements++- hledger can now be built with GHC 9.8.+- hledger now requires safe >=0.3.20.+- fix spanUnion with open-ended dates; add spanExtend [#2177]+- move readFileStrictly from hledger to Hledger.Utils.IO+- rename/improve amountSetFullPrecisionUpTo; add mixedAmountSetFullPrecisionUpTo+- rename Amount's aprice -> acost+- rename AmountPrice, UnitPrice, TotalPrice -> AmountCost, UnitCost, TotalCost+- showAmountWithoutPrice -> showAmountWithoutCost+- mixedAmountStripPrices -> mixedAmountStripCosts+- showMixedAmountWithoutPrice -> showMixedAmountWithoutCost+- showMixedAmountOneLineWithoutPrice -> showMixedAmountOneLineWithoutCost+- rename amountStripPrices -> amountStripCost, etc+- rename AmountDisplayOpts -> AmountFormat; add a new flag for symbol display+- rename noColour -> defaultFmt+- rename noCost -> noCostFmt+- rename oneLine -> oneLineFmt+- rename csvDisplay -> machineFmt+- distinguish oneLineFmt and oneLineNoCostFmt; add fullZeroFmt+- matchedPostingsBeforeAndDuring: improve debug output++[#2177]: https://github.com/hledgerorg/hledger/issues/2177+++# 1.32.3 2024-01-28++- Some API renames ended up in this release, including++ - amountStripPrices -> amountStripCost+ - showAmountPrice -> showAmountCostB+ - showAmountPriceDebug -> showAmountCostDebug++# 1.32.2 2023-12-31++Breaking changes++- In Hledger.Data.Amount, noPrice is renamed to noCost.++- AmountDisplayOpts has a new displayCommodity flag, controlling commodity symbol display.++Fixes++- Hledger.Utils.Debug.traceOrLog was logging when it should trace and vice versa.++Improvements++- Allow megaparsec 9.6++# 1.32.1 2023-12-07++- readFileStrictly is now provided by Hledger.Utils.IO++# 1.32 2023-12-01++Misc. changes++- styleAmounts is used in more places++- journalApplyCommodityStyles renamed to journalStyleAmounts++- "hard" and "all" rounding strategies have been added++- debug output improvements, eg for precision handling++- Table is now Showable, for debugging+++# 1.31 2023-09-03++Breaking changes++- There is a new consolidated API for styling amounts, and a+ convenient HasAmounts typeclass. AmountStyle's fields have been+ renamed/reordered more mnemonically, and setting the precision is+ now optional. (This simplifies the amount-stylingn code, but+ complicates the semantics a little. When reading, an unset precision+ generally behaves like NaturalPrecision.)++- (Possible breaking change):+ showMixedAmountLinesB, showAmountB, showAmountPrice now preserve+ commodityful zeroes when rendering. This is intended to affect print output,+ but it seems possible it might also affect balance and register reports,+ though our tests show no change in those.++- Renamed: journalAddInferredEquityPostings -> journalInferEquityFromCosts++Misc. changes++- Reports now do a final amount styling pass before rendering.++- groupByDateSpan code cleanup (Jay Neubrand)++- Allow aeson 2.2, megaparsec 9.5++# 1.30 2023-06-01++Breaking changes++- dropped: Hledger.Data.RawOptions.inRawOpts++Misc. changes++- added more terminal size, ANSI style/color helpers in Hledger.Utils.IO+ (and therefore Hledger and Hledger.Cli.Script):++ getTerminalHeightWidth+ getTerminalHeight+ getTerminalWidth+ bold'+ faint'+ black'+ red'+ green'+ yellow'+ blue'+ magenta'+ cyan'+ white'+ brightBlack'+ brightRed'+ brightGreen'+ brightYellow'+ brightBlue'+ brightMagenta'+ brightCyan'+ brightWhite'+ rgb'+ multicol+ expandGlob+ sortByModTime++# 1.29.2 2023-04-07++# 1.29.1 2023-03-16++- Hledger.Utils.String:++ added:+ strip1Char+ stripBy+ strip1By++- Allow building with GHC 9.6.1; add base-compat (#2011)++# 1.29 2023-03-11+- added terminal colour detection helpers:+ terminalIsLight+ terminalLightness+ terminalFgColor+ terminalBgColor++- Hledger.Data.RawOptions: add unsetboolopt++- add journalMarkRedundantCosts to help with balancing++- journalInferCosts -> journalInferCostsFromEquity++- `BalancingOpts{infer_transaction_prices_ -> infer_balancing_costs_}`++- Hledger.Data.Balancing: inferBalancingPrices -> transactionInferBalancingCosts++- Hledger.Data.Balancing: inferBalancingAmount -> transactionInferBalancingAmount++- Hledger.Data.Journal: transactionAddPricesFromEquity -> transactionInferCostsFromEquity++- Hledger.Data.Journal: journalAddPricesFromEquity -> journalInferCosts++- Hledger.Data.Dates: intervalStartBefore -> intervalBoundaryBefore++- Hledger.Read.Common: cleaned up some amount parsers; describe Ledger lot notation+ ```+ amountpwithmultiplier -> amountp'+ amountpnolotpricesp -> amountnobasisp+ amountwithoutpricep -> simpleamountp+ priceamountp -> costp+ ```++- depend on text-ansi+++# 1.28 2022-12-01++- Hledger.Utils.Debug's debug logging helpers have been unified.+ The "trace or log" functions log to stderr by default, or to a file+ if ",logging" is appended to the program name (using withProgName). + The debug log file is PROGNAME.log (changed from debug.log).++- Moved from Hledger.Utils.Debug to Hledger.Utils.Parse:+ traceParse+ traceParseAt+ dbgparse++- Moved from Hledger.Utils.Debug to Hledger.Utils.Print:+ pshow+ pshow'+ pprint+ pprint'+ colorOption+ useColorOnStdout+ useColorOnStderr+ outputFileOption+ hasOutputFile++- Rename Hledger.Utils.Print -> Hledger.Utils.IO, consolidate utils there.++- Hledger.Utils cleaned up.++- Hledger.Data.Amount: showMixedAmountOneLine now also shows costs.+ Note that different costs are kept separate in amount arithmetic.++- Hledger.Read.Common: rename/add amount parsing helpers.++ added:+ parseamount+ parseamount'+ parsemixedamount+ parsemixedamount'++ removed:+ amountp'+ mamountp'++- Hledger.Utils.Parse:+ export customErrorBundlePretty, + for pretty-printing hledger parse errors.++- Support megaparsec 9.3. (Felix Yan)++- Support GHC 9.4.++- Update cabal files to match hpack 0.35/stack 2.9+++# 1.27 2022-09-01++Breaking changes++- Support for GHC 8.6 and 8.8 has been dropped.+ hledger now requires GHC 8.10 or newer.++- Hledger.Data.Amount: `amount` has been dropped; use `nullamt` instead.++- journal*AccountQuery functions have been dropped; use a type: query instead.+ cbcsubreportquery no longer takes Journal as an argument.+ (#1921)++Misc. changes++- Hledger.Utils.Debug now re-exports Debug.Breakpoint from the+ breakpoint library, so that breakpoint's helpers can be used easily+ during development.++- Hledger.Utils.Debug:+ dlog has been replaced by more reliable functions for debug-logging+ to a file (useful for debugging TUI apps like hledger-ui):++ dlogTrace+ dlogTraceAt+ dlogAt+ dlog0+ dlog1+ dlog2+ dlog3+ dlog4+ dlog5+ dlog6+ dlog7+ dlog8+ dlog9++- Hledger.Utils.Debug: pprint' and pshow' have been added,+ forcing monochrome output.++- Hledger.Utils.String: add quoteForCommandLine++- Hledger.Data.Errors: export makeBalanceAssertionErrorExcerpt++- Hledger.Utils.Parse: export HledgerParseErrors++- Debug logging from journalFilePath and the include directive will+ now show "(unknown)" instead of an empty string.++# 1.26.1 2022-07-11++- require safe 0.3.19+ to avoid deprecation warning++# 1.26 2022-06-04++Breaking changes++- readJournal, readJournalFile, readJournalFiles now return+ `ExceptT String IO a` instead of `IO (Either String a)`.+ Internally, this increases composability and avoids some ugly case handling.+ It means that these must now be evaluated with `runExceptT`.+ That can be imported from `Control.Monad.Except` in the `mtl` package,+ but `Hledger.Read` also re-exports it for convenience.++ New variants readJournal', readJournalFiles', readJournalFile' are+ also provided; these are like the old functions but more convenient,+ assuming default input options and needing one less argument.+ (Stephen Morgan)++- parseAndFinaliseJournal' (a variant of parseAndFinaliseJournal) has been removed. + In the unlikely event you needed it in your code, you can replace:+ ```haskell+ parseAndFinaliseJournal' parser iopts fp t+ ```+ with:+ ```haskell+ initialiseAndParseJournal parser iopts fp t+ >>= liftEither . journalApplyAliases (aliasesFromOpts iopts)+ >>= journalFinalise iopts fp t+ ```++- Some parsers have been generalised from JournalParser to TextParser.+ (Stephen Morgan)++Misc. changes++- Allow doclayout 0.4.++- Our doctests now run with GHC 9.2+ only, to avoid doctest issues.++- Hledger.Data.JournalChecks: some Journal checks have been moved and renamed:+ journalCheckAccounts,+ journalCheckCommodities,+ journalCheckPayees+ +- Hledger.Data.Errors: new error formatting helpers+ makeTransactionErrorExcerpt,+ makePostingErrorExcerpt,+ transactionFindPostingIndex++- HledgerParseErrors is a new type alias for our parse errors.+ CustomErr has been renamed to HledgerParseErrorData.++- Hledger.Query: added+ matchesQuery,+ queryIsCode,+ queryIsTransactionRelated++- Improve ergonomics of SmartDate constructors. + (Stephen Morgan)++- Hledger.Utils: Add a helper function numDigitsInt to get the number+ of digits in an integer, which has a surprising number of ways to+ get it wrong.+ ([#1813](https://github.com/hledgerorg/hledger/issues/1813) (Stephen Morgan)++# 1.25 2022-03-04++- hledger-lib now builds with GHC 9.2 and latest deps. + ([#1774](https://github.com/hledgerorg/hledger/issues/1774)++- Journal has a new jaccounttypes map.+ The journalAccountType lookup function makes it easy to check an account's type.+ The journalTags and journalInheritedTags functions look up an account's tags.+ Functions like journalFilterPostings and journalFilterTransactions,+ and new matching functions matchesAccountExtra, matchesPostingExtra+ and matchesTransactionExtra, use these to allow more powerful matching+ that is aware of account types and tags.++- Journal has a new jdeclaredaccounttags field+ for easy lookup of account tags.+ Query.matchesTaggedAccount is a tag-aware version of matchesAccount.++- Some account name functions have moved from Hledger.Data.Posting+ to Hledger.Data.AccountName:+ accountNamePostingType, accountNameWithPostingType, accountNameWithoutPostingType,+ joinAccountNames, concatAccountNames, accountNameApplyAliases, accountNameApplyAliasesMemo.++- Renamed: CommodityLayout to Layout.++# 1.24.1 2021-12-10++Improvements++- Added: filterQueryOrNotQuery.++# 1.24 2021-12-01++Improvements++- The Semigroup instance of PeriodicReportRow and PeriodicReport now+ preserves the first prrName, rather than the second.+ (Stephen Morgan)++- PeriodicReport and PeriodicReportRow now have Bifunctor instances.+ (Stephen Morgan)++- Move posting rendering functions into Hledger.Data.Posting.+ This produces slightly different output for showPosting, in particular+ it no longer displays the transaction date. However, this has been+ marked as ‘for debugging only’ for a while.+ (Stephen Morgan)++- Drop postingDateOrDate2, transactionDateOrDate2; rename+ whichDateFromOpts to whichDate. (#1731)++- Added new helper functions journalValueAndFilterPostings(With) to make+ valuation and filtration less error prone.+ (Stephen Morgan)++- Avoid deprecation warnings with safe 0.3.18+. + (Stephen Morgan)++- Drop base-compat-batteries dependency. + (Stephen Morgan)++- Allow megaparsec 9.2.++# 1.23 2021-09-21++- Require base >=4.11, prevent red squares on Hackage's build matrix.++Much code cleanup and reorganisation, such as:++- Introduce lenses for many types. (Stephen Morgan)++- The now-obsolete normaliseMixedAmount and+ normaliseMixedAmountSquashPricesForDisplay functions have been+ dropped. (Stephen Morgan)++- GenericSourcePos has been dropped, replaced by either SourcePos or+ (SourcePos, SourcePos), simplifying module structure. (Stephen Morgan)++- Functions related to balancing (both transaction balancing and journal balancing)+ have been moved to Hledger.Data.Balancing, reducing module size and reducing the risk+ of import cycles.+ (Stephen Morgan)++- `ReportOptions{infer_value_}` has been renamed to `infer_prices_`,+ for more consistency with the corresponding CLI flag.+ And `BalancingOpts{infer_prices_}` is now `infer_transaction_prices_`.++- JournalParser and ErroringJournalParser have moved to+ Hledger.Data.Journal. (Stephen Morgan)++- MixedAmounts now have a more predictable Ord instance / sort order.+ They are compared in each commodity in turn, with+ alphabetically-first commodity symbols being most significant.+ Missing commodities are assumed to be zero. + As a consequence, all the ways of representing zero with a MixedAmount ([],+ [A 0], [A 0, B 0, ...]) are now Eq-ual (==), whereas before they were+ not. We have not been able to find anything broken by this change.+ ([#1563](https://github.com/hledgerorg/hledger/issues/1563), + [#1564](https://github.com/hledgerorg/hledger/issues/1564), + Stephen Morgan)++- HUnit's testCase and testGroup are now used directly instead of+ having test and tests aliases. (Stephen Morgan)++- The codebase now passes many hlint checks++- Dropped modules:+ Hledger.Utils.Color,+ Hledger.Data.Commodity,+ Hledger.Utils.UTF8IOCompat,+ Hledger.Utils.Tree module.+ (Stephen Morgan)++- Drop the deprecated old-time lib.+ A small number type signatures have changed:+ journalSetLastReadTime, maybeFileModificationTime and Journal+ now use POSIXTime instead of ClockTime.+ Hledger.Cli.Utils.utcTimeToClockTime has been removed, + as it is now equivalent to utcTimeToPOSIXSeconds from Data.Time.Clock.POSIX.+ To get the current system time, you should now use getPOSIXTime + from Data.Time.Clock.POSIX instead of getClockTime.+ ([#1650](https://github.com/hledgerorg/hledger/issues/1650), Stephen Morgan)++- modifyTransactions now takes a Map of commodity styles, and will style amounts according to that argument. journalAddForecast and journalTransform now return an Either String Journal. (Stephen Morgan)+ This improves efficiency, as we no longer have to restyle all amounts in+ the journal after generating auto postings or periodic transactions.+ Changing the return type of journalAddForecast and journalTransform+ reduces partiality.+ To get the previous behaviour for modifyTransaction, use modifyTransaction mempty.++- Refactor journalFinalise to clarify flow. (Stephen Morgan)+ The only semantic difference is that we now apply+ journalApplyCommodityStyles before running journalCheckAccountsDeclared+ and journalCheckCommoditiesDeclared.++- Introduce lenses for ReportOpts and ReportSpec. (Stephen Morgan)++- Rename the fields of ReportSpec. (Stephen Morgan)++ This is done to be more consistent with future field naming conventions,+ and to make automatic generation of lenses simpler. See discussion in+ [#1545](https://github.com/hledgerorg/hledger/issues/1545).++ rsOpts -> _rsReportOpts+ rsToday -> _rsDay+ rsQuery -> _rsQuery+ rsQueryOpts -> _rsQueryOpts++- Remove aismultiplier from Amount. (Stephen Morgan)++ In Amount, aismultiplier is a boolean flag that will always be False,+ except for in TMPostingRules, where it indicates whether the posting+ rule is a multiplier. It is therefore unnecessary in the vast majority+ of cases. This posting pulls this flag out of Amount and puts it into+ TMPostingRule, so it is only kept around when necessary.++ This changes the parsing of journals somewhat. Previously you could+ include an * before an amount anywhere in a Journal, and it would+ happily parse and set the aismultiplier flag true. This will now fail+ with a parse error: * is now only acceptable before an amount within an+ auto posting rule.++ Any usage of the library in which the aismultiplier field is read or set+ should be removed. If you truly need its functionality, you should+ switch to using TMPostingRule.++ This changes the JSON output of Amount, as it will no longer include+ aismultiplier.++- For accountTransactionsReport, generate the overall reportq from the ReportSpec, rather than being supplied as a separate option. (Stephen Morgan)++ This is the same approach used by the other reports, e.g. EntryReport,+ PostingReport, MultiBalanceReport. This reduces code duplication, as+ previously the reportq had to be separately tweaked in each of 5+ different places.++ If you call accountTransactionreport, there is no need to separately+ derive the report query.++- Remove unused TransactionReport. Move the useful utility functions to AccountTransactionsReport. (Stephen Morgan)++ If you use transactionsReport, you should either use entryReport if you+ don't require a running total, or using accountTransactionsReport with+ thisacctq as Any or None (depending on what you want included in the+ running total).++- Some balance report types have been renamed for clarity and to sync with docs:++ ReportType -> BalanceCalculation+ ChangeReport -> CalcChange+ BudgetReport -> CalcBudget+ ValueChangeReport -> CalcValueChange++ BalanceType -> BalanceAccumulation+ PeriodChange -> PerPeriod+ CumulativeChange -> Cumulative+ HistoricalBalance -> Historical++ ReportOpts:+ reporttype_ -> balancecalc_+ balancetype_ -> balanceaccum_++ CompoundBalanceCommandSpec:+ cbctype -> cbcaccum++ Hledger.Reports.ReportOptions:+ balanceTypeOverride -> balanceAccumulationOverride++# 1.22.2 2021-08-07++- forecast_ has moved from ReportOpts to InputOpts. (Stephen Morgan)++- Generate forecast transactions at journal finalisation, rather than as a postprocessing step.+ This allows us to have a uniform procedure for balancing transactions,+ whether they are normal transactions or forecast transactions, including+ dealing with balance assignments, balance assertions, and auto postings.+ ([#1638](https://github.com/hledgerorg/hledger/issues/1638), Stephen Morgan)++# 1.22.1 2021-08-02++- Allow megaparsec 9.1++- journalEndDate's behaviour has been clarified, journalLastDay has+ been added.++- transactionCheckBalanced is now exported. (#1596)++# 1.22 2021-07-03++- 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 now-required lower bound on containers. (#1514)++- Added useColor, colorOption helpers usable in pure code, eg for debug output.++- Added a Show instance for AmountDisplayOpts and WideBuilder, for debug logging.++Many internal refactorings/improvements/optimisations by Stephen Morgan,+including:++- Don't infer a txn price with same-sign amounts. (#1551)++- Clean up valuation functions, and make clear which to use where. (#1560)++- Replace journalSelectingAmountFromOpts with journalApplyValuationFromOpts.+ This also has the effect of allowing valuation in more reports, for+ example the transactionReport.++- Refactor to eliminate use of printf.++- Remove unused String, Text utility functions.++- Replace concat(Top|Bottom)Padded with textConcat(Top|Bottom)Padded.++- Export Text.Tabular from Text.Tabular.AsciiWide, clean up import lists.++- When matching an account query against a posting, don't try to match+ against the same posting twice, in cases when poriginal is Nothing.++- Create mixedAmountApplyValuationAfterSumFromOptsWith for doing any+ valuation needed after summing amounts.++- Create journalApplyValuationFromOpts. This does costing and+ valuation on a journal, and is meant to replace most direct calls of+ costing and valuation. The exception is for reports which require+ amounts to be summed before valuation is applied, for example a+ historical balance report with --value=end.++- Remove unused (amount|mixedAmount|posting|transaction)ApplyCostValuation functions.++- Remove unnecessary normalisedMixedAmount.++- Remove `showAmounts*B` functions, replacing them entirely with+ `showMixedAmount*B` functions.++- Pull "show-costs" option used by the Close command up into ReporOpts.++- Add more efficient toEncoding for custom ToJSON declarations.++- Fix ledgerDateSpan, so that it considers both transaction and+ posting dates. (#772)++- Move reportPeriodName to Hledger.Reports.ReportOptions, use it for+ HTML and CSV output for compound balance reports.++- Simplify the JSON representation of AmountPrecision. It now uses the+ same JSON representation as Maybe Word8. This means that the JSON+ serialisation is now broadly compatible with that used before the+ commit f6fa76bba7530af3be825445a1097ae42498b1cd, differing only in+ how it handles numbers outside Word8 and that it can now produce+ null for NaturalPrecision.++- A number of AccountName and Journal functions which are supposed to+ produce unique sorted results now use Sets internally to be slightly+ more efficient. There is also a new function journalCommodities.++- More efficiently check whether Amounts are or appear to be zero.+ Comparing two Quantity (either with == or compare) does a lot of+ normalisation (calling roundMax) which is unnecessary if we're+ comparing to zero. Do things more directly to save work.+ For `reg -f examples/10000x10000x10.journal`, this results in++ - A 12% reduction in heap allocations, from 70GB to 62GB+ - A 14% reduction in (profiled) time, from 79s to 70s++ Results for bal -f examples/10000x10000x10.journal are of the same+ order of magnitude.++- In sorting account names, perform lookups on HashSets and HashMaps,+ rather than lists. This is probably not an enormous performance sink+ in real situations, but it takes a huge amount of time and memory in+ our benchmarks (specifically 10000x10000x10.journal). For + `bal -f examples/10000x10000x10.journal`, this results in++ - A 23% reduction in heap allocation, from 27GiB to 21GiB+ - A 33% reduction in (profiled) time running, from 26.5s to 17.9s++- Minor refactor, using foldMap instead of asum . map . toList.++- Do not call showAmount twice for every posting. For print -f+ examples/10000x10000x10.journal, this results in a 7.7% reduction in+ heap allocations, from 7.6GB to 7.1GB.++- Some efficiency improvements in register reports.+ Use renderRow interface for Register report.++ For `reg -f examples/10000x10000x10.journal`, this results in:++ - Heap allocations decreasing by 55%, from 68.6GB to 31.2GB+ - Resident memory decreasing by 75%, from 254GB to 65GB+ - Total (profiled) time decreasing by 55%, from 37s to 20s++- Split showMixedAmountB into showMixedAmountB and showAmountsB, the+ former being a simple wrapper around the latter. This removes the+ need for the showNormalised option, as showMixedAmountB will always+ showNormalised and showAmountsB will never do so.++- Change internal representation of MixedAmount to use a strict Map+ instead of a list of Amounts. No longer export Mixed constructor, to+ keep API clean. (If you really need it, you can import it directly+ from Hledger.Data.Types). We also ensure the JSON representation of+ MixedAmount doesn't change: it is stored as a normalised list of+ Amounts.+ + This commit improves performance. Here are some indicative results:++ hledger reg -f examples/10000x1000x10.journal+ - Maximum residency decreases from 65MB to 60MB (8% decrease)+ - Total memory in use decreases from 178MiB to 157MiB (12% decrease)++ hledger reg -f examples/10000x10000x10.journal+ - Maximum residency decreases from 69MB to 60MB (13% decrease)+ - Total memory in use decreases from 198MiB to 153MiB (23% decrease)++ hledger bal -f examples/10000x1000x10.journal+ - Total heap usage decreases from 6.4GB to 6.0GB (6% decrease)+ - Total memory in use decreases from 178MiB to 153MiB (14% decrease)++ hledger bal -f examples/10000x10000x10.journal+ - Total heap usage decreases from 7.3GB to 6.9GB (5% decrease)+ - Total memory in use decreases from 196MiB to 185MiB (5% decrease)++ hledger bal -M -f examples/10000x1000x10.journal+ - Total heap usage decreases from 16.8GB to 10.6GB (47% decrease)+ - Total time decreases from 14.3s to 12.0s (16% decrease)++ hledger bal -M -f examples/10000x10000x10.journal+ - Total heap usage decreases from 108GB to 48GB (56% decrease)+ - Total time decreases from 62s to 41s (33% decrease)++ If you never directly use the constructor Mixed or pattern match against+ it then you don't need to make any changes. If you do, then do the+ following:++ - If you really care about the individual Amounts and never normalise+ your MixedAmount (for example, just storing `Mixed amts` and then+ extracting `amts` as a pattern match, then use should switch to using+ [Amount]. This should just involve removing the `Mixed` constructor.+ - If you ever call `mixed`, `normaliseMixedAmount`, or do any sort of+ amount arithmetic (+), (-), then you should replace the constructor+ `Mixed` with the function `mixed`. To extract the list of Amounts, use+ the function `amounts`.+ - Any remaining calls to `normaliseMixedAmount` can be removed, as that+ is now the identity function.++- Create a new API for MixedAmount arithmetic. This should supplant+ the old interface, which relied on the Num typeclass. MixedAmount+ did not have a very good Num instance. The only functions which were+ defined were fromInteger, (+), and negate. Furthermore, it was not+ law-abiding, as 0 + a /= a in general. Replacements for used+ functions are:++ 0 -> nullmixedamt / mempty+ (+) -> maPlus / (<>)+ (-) -> maMinus+ negate -> maNegate+ sum -> maSum+ sumStrict -> maSum++ Also creates some new constructors for MixedAmount:++ mixedAmount :: Amount -> MixedAmount+ maAddAmount :: MixedAmount -> Amount -> MixedAmount+ maAddAmounts :: MixedAmount -> [Amount] -> MixedAmount++ Add Semigroup and Monoid instances for MixedAmount.+ Ideally we would remove the Num instance entirely.++ The only change needed have nullmixedamt/mempty substitute for 0+ without problems was to not squash prices in+ mixedAmount(Looks|Is)Zero. This is correct behaviour in any case.+++# 1.21 2021-03-10++- Building Hledger.Data.Journal no longer fails if the monad-extras+ package is installed.++- Many parts of the hledger-lib and hledger APIs have become more+ Text-ified, expecting or returning Text instead of String, reducing+ hledger's time and resident memory requirements by roughly 10%.+ Some functions now use WideBuilder (a text "builder" which keeps track+ of width), to concatenate text more efficiently. There are some+ helpers for converting to and from WideBuilder (wbUnpack, wbToText..)+ showAmountB/showMixedAmountB are new amount-displaying functions+ taking an AmountDisplayOpts. These will probably replace the old+ show(Mixed)Amount* functions. (#1427, Stephen Morgan)++- AtThen valuation is now implemented for all report types.+ amountApplyValuation now takes the posting date as an argument.+ (transaction/posting)ApplyValuation's valuation type and+ transaction/posting arguments have been reordered like+ amountApplyValuation's. (Stephen Morgan)++- Amount, AmountPrice, AmountStyle, DigitGroupStyle fields are now+ strict. (Stephen Morgan)++- Amount prices are now stored with their sign, so negative prices can+ be represented. (They seem to have always worked, but now the+ internal representation is more accurate.) (Stephen Morgan)+ +- normaliseMixedAmount now combines Amounts with TotalPrices in the+ same commodity. (Stephen Morgan)++- normaliseMixedAmount now uses a strict Map for combining amounts+ internally, closing a big space leak. (Stephen Morgan)++- (multiply|divide)(Mixed)?Amount now also multiply or divide the+ TotalPrice if it is present, and the old+ (multiply|divide)(Mixed)?AmountAndPrice functions are removed. (Stephen Morgan)++- (amount|mixedAmount)(Looks|Is)Zero functions now check whether both+ the quantity and the cost are zero. This is usually what you want,+ but if you do only want to check whether the quantity is zero, you+ can run mixedAmountStripPrices (or similar) before this. (Stephen Morgan)++- commodityStylesFromAmounts now consumes the list immediately,+ reducing the maximum heap size per thread from ~850K to ~430K in a+ real-world register report. (Stephen Morgan)++- *ApplyValuation functions take two less arguments, and+ *ApplyCostValuation functions have been added, performing both+ costing and valuation. (Stephen Morgan)++- traceAtWith now has a level argument and works properly.++- API changes include:+ ```+ Hledger.Data.Amount:+ setAmountPrecision -> amountSetPrecision+ setFullPrecision -> amountSetFullPrecision+ setMixedAmountPrecision -> mixedAmountSetPrecision+ showMixed -> showMixedAmountB+ showMixedLines -> showMixedAmountLinesB+ -mixedAmountSetFullPrecision++ Hledger.Data.Journal:+ mapJournalTransactions -> journalMapTransactions+ mapJournalPostings -> journalMapPostings+ -mapTransactionPostings+ +journalPayeesUsed+ +journalPayeesDeclaredOrUsed++ Hledger.Data.Transaction:+ +transactionFile+ +transactionMapPostings++ Hledger.Data.Valuation:+ -valuationTypeIsCost+ -valuationTypeIsDefaultValue+ -ValuationType's AtDefault constructor++ Hledger.Query:+ +matchesDescription+ +matchesPayeeWIP++ Hledger.Utils.Text:+ +textConcatBottomPadded+ +wbToText+ +wbUnpack++ Text.Tabular.AsciiWide:+ alignCell -> textCell+ ```+# 1.20.4 2021-01-29++- See hledger.++# 1.20.3 2021-01-14++- See hledger.++# 1.20.2 2020-12-28++- Fix the info manuals' node structure.++- Drop unused parsec dependency.++# 1.20.1 2020-12-15++- renamed: updateReportSpecFromOpts -> updateReportSpec[With]++# 1.20 2020-12-05++- added: journalApplyAliases, transactionApplyAliases, postingApplyAliases++- a new more robust price lookup implementation, fgl library dropped (#1402)++- 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)++- global commodity display styles can now be set in InputOpts or Journal,+ overriding all others (declared or inferred). This is used by the import+ command and probably command-line options in future.++- Journal keeps a new piece of parsing state, a decimal mark character,+ which can optionally be set to force the number format expected by all+ amount parsers.++- Remove Empty Query constructor, which does nothing and has done so for a very long time. (Stephen Morgan)++- In ReportOpts, store query terms term-by-term in a list in querystring_. (Stephen Morgan)+ This helps deal with tricky quoting issues, as we no longer have to make+ sure everything is quoted properly before merging it into a string.++- Implement concat(Top|Bottom)Padded in terms of renderRow, allowing them to be width aware. (Stephen Morgan)++- Expand Tabular.AsciiWide to allow multiline, custom-width,+ vertically/horizontally-aligned cells, and optional table borders.+ (Stephen Morgan)++- Introduce showMixed*Unnormalised, eliminate most direct calls of strWidth. (Stephen Morgan)++- showMixedAmountElided now makes better use of space, showing as many+ Amounts possible as long as they and the elision string fit within+ 32 characters. (Stephen Morgan)++- Add Functor instance for CompoundPeriodicReport. (Stephen Morgan)++- Generalise CBCSubreportSpec to allow more subreport control. (Stephen Morgan)++- Export some MultiBalanceReport helper functions. (Stephen Morgan)++- Make Default instances clearer, remove Default instance for Bool. (Stephen Morgan)++- Many ReportOpts-related changes, such as the addition of ReportSpec, aimed+ at preventing runtime errors (from parsing: regexps, dates, format strings;+ from not having today's date set; etc.)+ ReportSpec holds a ReportOpts, the day of the report, and the Query generated from these.++- StringFormat now takes an optional overline width, which is+ currently only used by defaultBalanceLineFormat. (Stephen Morgan)++- quoteIfNeeded should not escape the backslashes in unicode code points. (Stephen Morgan)++- Export OrdPlus and constructors. (Stephen Morgan)++- Debug output now uses pretty-simple instead pretty-show.+ This hopefully gives overall nicer debug output (eg in colour), + including for values which don't have Read-able Show output.+ This means that we can start removing custom Show instances + that were a workaround for pretty-show. Eg account names+ in debug output no longer show their colons as underscores.++ Here's some old pretty-show output:++ CsvRules+ { rdirectives = [ ( "skip" , "1" ) ]+ , rcsvfieldindexes = [ ( "date" , 1 ) , ( "amount" , 2 ) ]+ , rassignments = [ ( "amount" , "%2" ) , ( "date" , "%1" ) ]+ , rconditionalblocks = []+ }++ And the new pretty-simple output:++ CsvRules+ { rdirectives=+ [ ( "skip", "1" ) ]+ , rcsvfieldindexes=+ [ ( "date", 1 ), ( "amount", 2 ) ]+ , rassignments=+ [ ( "amount", "%2" ), ( "date", "%1" ) ]+ , rconditionalblocks= []+ }++ We require pretty-simple 4.0.0.0 to get this compact output.+ It's a little less compact than pretty-show, but not too bad.+ Non-compact pretty-simple output would be:++ CsvRules+ { rdirectives=+ [+ ( "skip"+ , "1B"+ )+ ]+ , rcsvfieldindexes=+ [+ ( "date"+ , 1+ )+ ,+ ( "amount"+ , 2+ )+ ]+ , rassignments=+ [+ ( "amount"+ , "%2"+ )+ ,+ ( "date"+ , "%1"+ )+ ]+ , rconditionalblocks=[]+ }+++# 1.19.1 2020-09-07++- Allow megaparsec 9++- stripAnsi: correctly strip ansi sequences with no+ numbers/semicolons. (Stephen Morgan)++- Added case-insensitive accountNameToAccountRegexCI,+ accountNameToAccountOnlyRegexCI, made the default account type+ queries case insensitive again. (#1341)++# 1.19 2020-09-01++- Added a missing lower bound for aeson, making cabal installs more+ reliable. (#1268)++- The Regex type alias has been replaced by the Regexp ADT, which+ contains both the compiled regular expression (so is guaranteed to+ be usable at runtime) and the original string (so can be serialised,+ printed, compared, etc.) A Regexp also knows whether is it case+ sensitive or case insensitive. The Hledger.Utils.Regex API has+ changed. (#1312, #1330).++- Typeable and Data instances are no longer derived for hledger's+ data types; they were redundant/no longer needed.++- NFData instances are no longer derived for hledger's data types.+ This speeds up a full build by roughly 7%. But it means we can't+ deep-evaluate hledger values, or time hledger code with Criterion.+ https://github.com/hledgerorg/hledger/pull/1330#issuecomment-684075129+ has some ideas on this.++- Query no longer has a custom Show instance++- Hledger.Utils.String: quoteIfNeeded now actually escapes quotes in+ strings. escapeQuotes was dropped. (Stephen Morgan)++- Hledger.Utils.Tree: dropped some old utilities++- Some fromIntegral calls have been replaced with safer code, removing+ some potential for integer wrapping bugs (#1325, #1326)++- Parsing numbers with more than 255 decimal places now gives an error+ instead of silently misparsing (#1326)++- Digit groups are now limited to at most 255 digits each. (#1326)++- Exponents are parsed as Integer rather than Int.+ This means exponents greater than 9223372036854775807 or less than+ -9223372036854775808 are now parsed correctly, in theory. (In+ practice, very large exponents will cause hledger to eat all your+ memory, so avoid them for now.) (#1326)++- AmountStyle's asprecision is now a sum type with Word8, instead of+ an Int with magic values.++- DigitGroupStyle uses Word8 instead of Int.++- Partial helper function parsedate has been dropped, use fromGregorian instead.++- Partial helper function mkdatespan has been dropped.++- Helper function transaction now takes a Day instead of a date string. (Stephen Morgan)++- Old CPP directives made redundant by version bounds have been+ removed. (Stephen Morgan)++- Smart dates are now represented by the SmartDate type, and are+ always well formed. (Stephen Morgan)++- accountTransactionsReport (used for hledger aregister and+ hledger-ui/hledger-web registers) now filters transactions more+ thoroughly, so eg transactions dated outside the report period will+ not be shown. Previously the transaction would be shown if it had+ any posting dated inside the report period. Possibly some other+ filter criteria now get applied that didn't before. I think on+ balance this will give slightly preferable results.++- The old BalanceReport code has been dropped at last, replaced by+ MultiBalanceReport so that all balance reports now use the same+ code. (Stephen Morgan, #1256).++ - The large multiBalanceReport function has been split up and refactored+ extensively.+ - Tabular data formerly represented as [[MixedAmount]] is now HashMap+ AccountName (Map DateSpan Account). Reports with many columns are now faster.+ - Calculating starting balances no longer calls the whole balanceReport,+ just the first few functions.+ - displayedAccounts is completely rewritten. Perhaps one subtle thing to+ note is that in tree mode it no longer excludes nodes with zero inclusive+ balance unless they also have zero exclusive balance.+ - Simon's note: "I'll mark the passing of the old multiBalanceReport, into+ which I poured many an hour :). It is in a way the heart (brain ?) of+ hledger - the key feature of ledgerlikes (balance report) and a key+ improvement introduced by hledger (tabular multiperiod balance reports)+ ...+ Thanks @Xitian9, great work."++# 1.18.1 2020-06-21++- fix some doc typos (Martin Michlmayr)++# 1.18 2020-06-07++- added: getHledgerCliOpts', takes an explicit argument list++- added: toJsonText++- changed: isNegativeMixedAmount now gives an answer for+ multi-commodity amounts which are all negative++- changed: multiBalanceReport now gets the query from ReportOpts (Dmitry Astapov)++- renamed:+ isZeroAmount -> amountLooksZero+ isReallyZeroAmount -> amountIsZero+ isZeroMixedAmount -> mixedAmountLooksZero+ isReallyZeroMixedAmount -> mixedAmountIsZero+ isReallyZeroMixedAmountCost dropped++- renamed: finaliseJournal -> journalFinalise++- renamed: fixedlotpricep -> lotpricep, now also parses non-fixed lot prices++- dropped: transactionPostingBalances++- dropped: outputflags no longer exported by Hledger.Cli.CliOptions++- fixed: documentation for journalExpenseAccountQuery (Pavan Rikhi)++# 1.17.1 2020-03-19++- 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").++- added: debug helpers traceAt, traceAtWith++- Journal is now a Semigroup, not a Monoid (since <> is right-biased). (Stephen Morgan)++# 1.17.0.1 2020-03-01++- fix org heading comments and doctest setup comment that were+ breaking haddock (and in some cases, installation)++# 1.17 2020-03-01++- Reader-finding utilities have moved from Hledger.Read to+ Hledger.Read.JournalReader so the include directive can use them.++- Reader changes:+ - rExperimental flag removed+ - old rParser renamed to rReadFn+ - new rParser field provides the actual parser.+ This seems to require making Reader a higher-kinded type, unfortunately.++- Hledger.Tabular.AsciiWide now renders smoother outer borders in+ pretty (unicode) mode.+ Also, a fix for table edges always using single-width intersections+ and support for double horizontal lines with single vertical lines. (Eric Mertens)++- Hledger.Utils.Parse: restofline can go to eof also++- Hledger.Read cleanup++- Hledger.Read.CsvReader cleanup+ Exports added: CsvRecord, CsvValue, csvFileFor.+ Exports removed: expandIncludes, parseAndValidateCsvRules, transactionFromCsvRecord++- more cleanup of amount canonicalisation helpers (#1187)+ Stop exporting journalAmounts, overJournalAmounts, traverseJournalAmounts.+ Rename journalAmounts helper to journalStyleInfluencingAmounts.++- export mapMixedAmount++- Don't store leaf name in PeriodReport. (Stephen Morgan)+ Calculate at the point of consumption instead.++- Generalise PeriodicReport to be polymorphic in the account labels. (Stephen Morgan)++- Use records instead of tuples in PeriodicReport. (Stephen Morgan)++- Use PeriodicReport in place of MultiBalanceReport. (Stephen Morgan)++- Calculate MultiReportBalance columns more efficiently. (Stephen Morgan)+ Only calculate posting date once for each posting, and calculate their+ columns instead of checking each DateSpan separately.++- Moved JSON instances from hledger-web to hledger-lib (Hledger.Data.Json),+ and added ToJSON instances for all (?) remaining data types, up to Ledger.++- Dropped nullassertion's "assertion" alias, fixing a warning.+ Perhaps we'll stick with the null* naming convention. +++# 1.16.2 2020-01-14++- add support for megaparsec 8 (#1175)++# 1.16.1 2019-12-03++- Drop unnecessary mtl-compat dependency++- Fix building with GHC 8.0, 8.2++# 1.16 2019-12-01++- drop support for GHC 7.10, due to MonadFail hassles in JournalReader.hs++- add support for GHC 8.8, base-compat 0.11 (#1090)++ We are now using the new fail from the MonadFail class, which we+ always import as qualified Fail.fail, from base-compat-batteries+ Control.Monad.Fail.Compat to work with old GHC versions. If old fail+ is needed (shouldn't be) it should be imported qualified as+ Prelude.Fail, using imports such as:++ import Prelude hiding (fail)+ import Prelude qualified (fail)+ import Control.Monad.State.Strict hiding (fail)+ import "base-compat-batteries" Prelude.Compat hiding (fail)+ import "base-compat-batteries" qualified Control.Monad.Fail.Compat as Fail++- hledger and hledger-lib unit tests have been ported to tasty.++- The doctest suite has been disabled for now since it doesn't run+ well with cabal (#1139)+ +# 1.15.2 2019-09-05++Changes:++- postingApplyValuation, mixedAmountApplyValuation, amountApplyValuation+ take an argument, the report end date if one was specified.++# 1.15.1 2019-09-02++- fix failing doctests++# 1.15 2019-09-01++Removals include:++- journalPrices+- BalanceHistoryReport+- postingValueAtDate++Additions include:++- MarketPrice (more pure form of PriceDirective without the amount style information)+- PriceOracle (efficient lookup of exchange rates)+- ValuationType (ways to convert amount value)+- aliasnamep (export)+- setNaturalPrecisionUpTo+- dbgNWith, ptraceAtWith+- postingTransformAmount, postingToCost, postingValue+- amountToCost, mixedAmountToCost+- valueTypeFromOpts+- mapJournalTransactions, mapJournalPostings, mapTransactionPostings+- journalStartDate, journalEndDate+- journalPriceOracle+- marketPriceReverse+- priceDirectiveToMarketPrice+- mixedAmountApplyValuation+- mixedAmountValueAtDate++Changes include:++- Price -> AmountPrice, AKA "transaction price"+- old MarketPrice -> PriceDirective+- TransactionsReport/AccountTransactionsReport split into separate files+- journalTransactionsReport -> transactionsReport+- accountTransactionsReportItems: rewrite using catMaybes and mapAccumL (Henning Thielemann)+- optionally save the current date in ReportOpts+- Hledger.Cli tests now have correct prefix; add Cli.Utils tests+- MultiBalanceReport now returns zero for row totals when in cumulative or historical mode (#329)+++# 1.14.1 2019-03-20++- require easytest <0.3 to fix build issue++# 1.14 2019-03-01++- added: + transaction, [v]post*, balassert* constructors, for tests etc. ++- renamed: + porigin -> poriginal ++- refactored: + transaction balancing & balance assertion checking (#438)++# 1.13.1 (2019/02/02)++- stop depending on here to avoid haskell-src-meta/stackage blockage.++# 1.13 (2019/02/01)++- in Journal's jtxns field, forecasted txns are appended rather than prepended++- API changes:++ added:+ +setFullPrecision+ +setMinimalPrecision+ +expectParseStateOn+ +embedFileRelative+ +hereFileRelative++ changed:+ - amultiplier -> aismultiplier+ - Amount fields reordered for clearer debug output+ - tpreceding_comment_lines -> tprecedingcomment, reordered+ - Hledger.Data.TransactionModifier.transactionModifierToFunction -> modifyTransactions+ - Hledger.Read.Common.applyTransactionModifiers -> Hledger.Data.Journal.journalModifyTransactions++ - HelpTemplate -> CommandDoc+++# 1.12 (2018/12/02)++- switch to megaparsec 7 (Alex Chen)+ We now track the stack of include files in Journal ourselves, since+ megaparsec dropped this feature.++- add 'ExceptT' layer to our parser monad again (Alex Chen)+ We previously had a parser type, 'type ErroringJournalParser = ExceptT+ String ...' for throwing parse errors without allowing further+ backtracking. This parser type was removed under the assumption that it+ would be possible to write our parser without this capability. However,+ after a hairy backtracking bug, we would now prefer to have the option to+ prevent backtracking.++ - Define a 'FinalParseError' type specifically for the 'ExceptT' layer+ - Any parse error can be raised as a "final" parse error+ - Tracks the stack of include files for parser errors, anticipating the+ removal of the tracking of stacks of include files in megaparsec 7+ - Although a stack of include files is also tracked in the 'StateT+ Journal' layer of the parser, it seems easier to guarantee correct+ error messages in the 'ExceptT FinalParserError' layer+ - This does not make the 'StateT Journal' stack redundant because the+ 'ExceptT FinalParseError' stack cannot be used to detect cycles of+ include files++- more support for location-aware parse errors when re-parsing (Alex Chen)++- make 'includedirectivep' an 'ErroringJournalParser' (Alex Chen)++- drop Ord instance breaking GHC 8.6 build (Peter Simons)++- flip the arguments of (divide\|multiply)\[Mixed\]Amount++- showTransaction: fix a case showing multiple missing amounts+ showTransaction could sometimes hide the last posting's amount even if+ one of the other posting amounts was already implicit, producing invalid+ transaction output.++- plog, plogAt: add missing newline++- split up journalFinalise, reorder journal finalisation steps (#893) (Jesse Rosenthal)+ The `journalFinalise` function has been split up, allowing more granular+ control.++- journalSetTime --> journalSetLastReadTime++- journalSetFilePath has been removed, use journalAddFile instead++# 1.11.1 (2018/10/06)++- add, lib: fix wrong transaction rendering in balance assertion errors+ and when using the add command++# 1.11 (2018/9/30)++- compilation now works when locale is unset (#849)++- all unit tests have been converted from HUnit+test-framework to easytest++- doctests now run quicker by default, by skipping reloading between tests.+ This can be disabled by passing --slow to the doctests test suite+ executable.++- doctests test suite executable now supports --verbose, which shows+ progress output as tests are run if doctest 0.16.0+ is installed+ (and hopefully is harmless otherwise).++- doctests now support file pattern arguments, provide more informative output.+ Limiting to just the file(s) you're interested can make doctest start+ much quicker. With one big caveat: you can limit the starting files,+ but it always imports and tests all other local files those import.++- a bunch of custom Show instances have been replaced with defaults,+ for easier troubleshooting. These were sometimes obscuring+ important details, eg in test failure output. Our new policy is:+ stick with default derived Show instances as far as possible, but+ when necessary adjust them to valid haskell syntax so pretty-show+ can pretty-print them (eg when they contain Day values, cf+ https://github.com/haskell/time/issues/101). By convention, when+ fields are shown in less than full detail, and/or in double-quoted+ pseudo syntax, we show a double period (..) in the output.++- Amount has a new Show instance. Amount's show instance hid+ important details by default, and showing more details required+ increasing the debug level, which was inconvenient. Now it has a+ single show instance which shows more information, is fairly+ compact, and is pretty-printable.++ ghci> usd 1+ OLD:+ Amount {acommodity="$", aquantity=1.00, ..}+ NEW:+ Amount {acommodity = "$", aquantity = 1.00, aprice = NoPrice, astyle = AmountStyle "L False 2 Just '.' Nothing..", amultiplier = False}++ MixedAmount's show instance is unchanged, but showMixedAmountDebug+ is affected by this change:++ ghci> putStrLn $ showMixedAmountDebug $ Mixed [usd 1]+ OLD:+ Mixed [Amount {acommodity="$", aquantity=1.00, aprice=, astyle=AmountStyle {ascommodityside = L, ascommodityspaced = False, asprecision = 2, asdecimalpoint = Just '.', asdigitgroups = Nothing}}]+ NEW:+ Mixed [Amount {acommodity="$", aquantity=1.00, aprice=, astyle=AmountStyle "L False 2 Just '.' Nothing.."}]++- Same-line & next-line comments of transactions, postings, etc.+ are now parsed a bit more precisely (followingcommentp).+ Previously, parsing no comment gave the same result as an empty+ comment (a single newline); now it gives an empty string.\+ Also, and perhaps as a consequence of the above, when there's no+ same-line comment but there is a next-line comment, we'll insert an+ empty first line, since otherwise next-line comments would get moved+ up to the same line when rendered.++- Hledger.Utils.Test exports HasCallStack++- queryDateSpan, queryDateSpan' now intersect date AND'ed date spans+ instead of unioning them, and docs are clearer.++- pushAccount -> pushDeclaredAccount++- jaccounts -> jdeclaredaccounts++- AutoTransaction.hs -> PeriodicTransaction.hs & TransactionModifier.hs++- Hledger.Utils.Debug helpers have been renamed/cleaned up++# 1.10 (2018/6/30)++- build cleanly with all supported GHC versions again (7.10 to 8.4)++- support/use latest base-compat (#794)++- support/require megaparsec 6.4+++- extensive refactoring and cleanup of parsers and related types and utilities++- readJournalFile(s) cleanup, these now use InputOpts++- doctests now run a bit faster (#802)++# 1.9.1 (2018/4/30)++- new generic PeriodicReport, and some report-related type aliases++- new BudgetReport++- make (readJournal\|tryReader)s?WithOpts the default api, dropping "WithOpts"++- automated postings and command line account aliases happen earlier+ in journal processing (see hledger changelog)++# 1.9 (2018/3/31)++- support ghc 8.4, latest deps++- when the system text encoding is UTF-8, ignore any UTF-8 BOM prefix+ found when reading files.++- CompoundBalanceReport amounts are now normally positive.+ The bs/bse/cf/is commands now show normal income, liability and equity+ balances as positive. Negative numbers now indicate a contra-balance+ (eg an overdrawn checking account), a net loss, a negative net worth,+ etc. This makes these reports more like conventional financial+ statements, and easier to read and share with others. (experimental)++- splitSpan now returns no spans for an empty datespan++- don't count periodic/modifier txns in Journal debug output++- lib/ui/web/api: move embedded manual files to extra-source-files++- Use skipMany/skipSome for parsing spacenonewline (Moritz Kiefer)+ This avoids allocating the list of space characters only to then+ discard it.++- rename, clarify purpose of balanceReportFromMultiBalanceReport++- fix some hlint warnings++- add some easytest tests++# 1.5 (2017/12/31)++- -V/--value uses today's market prices by default, not those of last transaction date. #683, #648)++- csv: allow balance assignment (balance assertion only, no amount) in csv records (Nadrieril)++- journal: allow space as digit group separator character, #330 (Mykola Orliuk)++- journal: balance assertion errors now show line of failed assertion posting, #481 (Sam Jeeves)++- journal: better errors for directives, #402 (Mykola Orliuk)++- journal: better errors for included files, #660 (Mykola Orliuk)++- journal: commodity directives in parent files are inherited by included files, #487 (Mykola Orliuk)++- journal: commodity directives limits precision even after -B, #509 (Mykola Orliuk)++- journal: decimal point/digit group separator chars are now inferred from an applicable commodity directive or default commodity directive. #399, #487 (Mykola Orliuk)++- journal: numbers are parsed more strictly (Mykola Orliuk)++- journal: support Ledger-style automated postings, enabled with --auto flag (Dmitry Astapov)++- journal: support Ledger-style periodic transactions, enabled with --forecast flag (Dmitry Astapov)++- period expressions: fix "nth day of {week,month}", which could generate wrong intervals (Dmitry Astapov)++- period expressions: month names are now case-insensitive (Dmitry Astapov)++- period expressions: stricter checking for invalid expressions (Mykola Orliuk)++- period expressions: support "every 11th Nov" (Dmitry Astapov)++- period expressions: support "every 2nd Thursday of month" (Dmitry Astapov)++- period expressions: support "every Tuesday", short for "every <n>th day of week" (Dmitry Astapov)++- remove upper bounds on all but hledger* and base (experimental)+ It's rare that my deps break their api or that newer versions must+ be avoided, and very common that they release new versions which I+ must tediously and promptly test and release hackage revisions for+ or risk falling out of stackage. Trying it this way for a bit.++# 1.4 (2017/9/30)++- add readJournalFile\[s\]WithOpts, with simpler arguments and support+ for detecting new transactions since the last read.++- query: add payee: and note: query terms, improve description/payee/note docs (Jakub Zárybnický, Simon Michael, #598, #608)++- journal, cli: make trailing whitespace significant in regex account aliases+ Trailing whitespace in the replacement part of a regular expression+ account alias is now significant. Eg, converting a parent account to+ just an account name prefix: --alias '/:acct:/=:acct'++- timedot: allow a quantity of seconds, minutes, days, weeks, months+ or years to be logged as Ns, Nm, Nd, Nw, Nmo, Ny++- csv: switch the order of generated postings, so account1 is first.+ This simplifies things and facilitates future improvements.++- csv: show the "creating/using rules file" message only with --debug++- csv: fix multiple includes in one rules file++- csv: add "newest-first" rule for more robust same-day ordering++- deps: allow ansi-terminal 0.7++- deps: add missing parsec lower bound, possibly related to #596, fpco/stackage#2835++- deps: drop oldtime flag, require time 1.5+++- deps: remove ghc < 7.6 support, remove obsolete CPP conditionals++- deps: fix test suite with ghc 8.2++# 1.3.1 (2017/8/25)++- Fix a bug with -H showing nothing for empty periods (#583, Nicholas Niro)+ This patch fixes a bug that happened when using the -H option on+ a period without any transaction. Previously, the behavior was no+ output at all even though it should have shown the previous ending balances+ of past transactions. (This is similar to previously using -H with -E,+ but with the extra advantage of not showing empty accounts)++- allow megaparsec 6 (#594)++- allow megaparsec-6.1 (Hans-Peter Deifel)++- fix test suite with Cabal 2 (#596)++# 1.3 (2017/6/30)++journal: 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)++csv: assigning to the "balance" field name creates balance+assertions (#537, Dmitry Astapov).++csv: Doubled minus signs are handled more robustly (fixes #524, Nicolas Wavrant, Simon Michael)++Multiple "status:" query terms are now OR'd together. (#564)++deps: allow megaparsec 5.3.++# 1.2 (2017/3/31)++## journal format++A pipe character can optionally be used to delimit payee names in+transaction descriptions, for more accurate querying and pivoting by+payee. Eg, for a description like `payee name | additional notes`,+the two parts will be accessible as pseudo-fields/tags named `payee`+and `note`.++Some journal parse errors now show the range of lines involved, not just the first.++## ledger format++The experimental `ledger:` reader based on the WIP ledger4 project has+been disabled, reducing build dependencies.++## Misc++Fix a bug when tying the knot between postings and their parent transaction, reducing memory usage by about 10% (#483) (Mykola Orliuk)++Fix a few spaceleaks (#413) (Moritz Kiefer)++Add Ledger.Parse.Text to package.yaml, fixing a potential build failure.++Allow megaparsec 5.2 (#503)++Rename optserror -> usageError, consolidate with other error functions++# 1.1 (2016/12/31)++## journal format++- balance assignments are now supported (#438, #129, #157, #288)++ This feature also brings a slight performance drop (\~5%);+ optimisations welcome.++- also recognise `*.hledger` files as hledger journal format++## ledger format++- use ledger-parse from the ledger4 project as an alternate reader for C++ Ledger journals++ The idea is that some day we might get better compatibility with Ledger files this way.+ Right now this reader is not very useful and will be used only if you explicitly select it with a `ledger:` prefix.+ It parses transaction dates, descriptions, accounts and amounts, and ignores everything else.+ Amount parsing is delegated to hledger's journal parser, and malformed amounts might be silently ignored.++ This adds at least some of the following as new dependencies for hledger-lib:+ parsers, parsec, attoparsec, trifecta.++## misc++- update base lower bound to enforce GHC 7.10+++ hledger-lib had a valid install plan with GHC 7.8, but currently requires GHC 7.10 to compile.+ Now we require base 4.8+ everywhere to ensure the right GHC version at the start.++- Hledger.Read api cleanups++- rename dbgIO to dbg0IO, consistent with dbg0, and document a bug in dbg*IO++- make readJournalFiles \[f\] equivalent to readJournalFile f (#437)++- more general parser types enabling reuse outside of IO (#439)++# 1.0.1 (2016/10/27)++- allow megaparsec 5.0 or 5.1++# 1.0 (2016/10/26)++## timedot format++- new "timedot" format for retroactive/approximate time logging.++ Timedot is a plain text format for logging dated, categorised+ quantities (eg time), supported by hledger. It is convenient+ for approximate and retroactive time logging, eg when the+ real-time clock-in/out required with a timeclock file is too+ precise or too interruptive. It can be formatted like a bar+ chart, making clear at a glance where time was spent.++## timeclock format++- renamed "timelog" format to "timeclock", matching the emacs package++- sessions can no longer span file boundaries (unclocked-out++ sessions will be auto-closed at the end of the file).++- transaction ids now count up rather than down (#394)++- timeclock files no longer support default year directives++- removed old code for appending timeclock transactions to journal transactions.++ A holdover from the days when both were allowed in one file.++## csv format++- fix empty field assignment parsing, rule parse errors after megaparsec port (#407) (Hans-Peter Deifel)++## journal format++- journal files can now include timeclock or timedot files (#320)++ (but not yet CSV files).++- fixed an issue with ordering of same-date transactions included from other files++- the "commodity" directive and "format" subdirective are now supported, allowing++ full control of commodity style (#295) The commodity directive's+ format subdirective can now be used to override the inferred+ style for a commodity, eg to increase or decrease the+ precision. This is at least a good workaround for #295.++- Ledger-style "apply account"/"end apply account" directives are now used to set a default parent account.++- the Ledger-style "account" directive is now accepted (and ignored).++- bracketed posting dates are more robust (#304)++ Bracketed posting dates were fragile; they worked only if you+ wrote full 10-character dates. Also some semantics were a bit+ unclear. Now they should be robust, and have been documented+ more clearly. This is a legacy undocumented Ledger syntax, but+ it improves compatibility and might be preferable to the more+ verbose "date:" tags if you write posting dates often (as I do).+ Internally, bracketed posting dates are no longer considered to+ be tags. Journal comment, tag, and posting date parsers have+ been reworked, all with doctests.++- balance assertion failure messages are clearer++- with --debug=2, more detail about balance assertions is shown.++## misc++- file parsers have been ported from Parsec to Megaparsec \o/ (#289, #366) (Alexey Shmalko, Moritz Kiefer)++- most hledger types have been converted from String to Text, reducing memory usage by 30%+ on large files++- file parsers have been simplified for easier troubleshooting (#275).++ The journal/timeclock/timedot parsers, instead of constructing+ opaque journal update functions which are later applied to build+ the journal, now construct the journal directly by modifying the+ parser state. This is easier to understand and debug. It also+ rules out the possibility of journal updates being a space+ leak. (They weren't, in fact this change increased memory usage+ slightly, but that has been addressed in other ways). The+ ParsedJournal type alias has been added to distinguish+ "being-parsed" journals and "finalised" journals.++- file format detection is more robust.++ The Journal, Timelog and Timedot readers' detectors now check+ each line in the sample data, not just the first one. I think the+ sample data is only about 30 chars right now, but even so this+ fixed a format detection issue I was seeing.+ Also, we now always try parsing stdin as journal format (not just sometimes).++- all file formats now produce transaction ids, not just journal (#394)++- git clone of the hledger repo on windows now works (#345)++- added missing benchmark file (#342)++- our stack.yaml files are more compatible across stack versions (#300)++- use newer file-embed to fix ghci working directory dependence (<https://github.com/snoyberg/file-embed/issues/18>)++- report more accurate dates in account transaction report when postings have their own dates++ (affects hledger-ui and hledger-web registers).+ The newly-named "transaction register date" is the date to be+ displayed for that transaction in a transaction register, for+ some current account and filter query. It is either the+ transaction date from the journal ("transaction general date"),+ or if postings to the current account and matched by the+ register's filter query have their own dates, the earliest of+ those posting dates.++- simplify account transactions report's running total.++ The account transactions report used for hledger-ui and -web+ registers now gives either the "period total" or "historical+ total", depending strictly on the --historical flag. It doesn't+ try to indicate whether the historical total is the accurate+ historical balance (which depends on the user's report query).++- reloading a file now preserves the effect of options, query arguments etc.++- reloading a journal should now reload all included files as well.++- the Hledger.Read.* modules have been reorganised for better reuse.++ Hledger.Read.Utils has been renamed Hledger.Read.Common+ and holds low-level parsers & utilities; high-level read+ utilities are now in Hledger.Read.++- clarify amount display style canonicalisation code and terminology a bit.++ Individual amounts still have styles; from these we derive+ the standard "commodity styles". In user docs, we might call+ these "commodity formats" since they can be controlled by the+ "format" subdirective in journal files.++- Journal is now a monoid++- expandPath now throws a proper IO error++- more unit tests, start using doctest++0.27 (2015/10/30)++- The main hledger types now derive NFData, which makes it easier to+ time things with criterion.++- Utils has been split up more.++- Utils.Regex: regular expression compilation has been memoized, and+ memoizing versions of regexReplace\[CI\] have been added, since+ compiling regular expressions every time seems to be quite+ expensive (#244).++- Utils.String: strWidth is now aware of multi-line strings (#242).++- Read: parsers now use a consistent p suffix.++- New dependencies: deepseq, uglymemo.++- All the hledger packages' cabal files are now generated from+ simpler, less redundant yaml files by hpack, in principle. In+ practice, manual fixups are still needed until hpack gets better,+ but it's still a win.++0.26 (2015/7/12)++- allow year parser to handle arbitrarily large years+- Journal's Show instance reported one too many accounts+- some cleanup of debug trace helpers+- tighten up some date and account name parsers (don't accept leading spaces; hadddocks)+- drop regexpr dependency++0.25.1 (2015/4/29)++- support/require base-compat >0.8 (#245)++0.25 (2015/4/7)++- GHC 7.10 compatibility (#239)++0.24.1 (2015/3/15)++- fix JournalReader "ctx" compilation warning+- add some type signatures in Utils to help make ghci-web++0.24 (2014/12/25)++- fix combineJournalUpdates folding order+- fix a regexReplaceCI bug+- fix a splitAtElement bug with adjacent separators+- mostly replace slow regexpr with regex-tdfa (fixes #189)+- use the modern Text.Parsec API+- allow transformers 0.4*+- regexReplace now supports backreferences+- Transactions now remember their parse location in the journal file+- export Regexp types, disambiguate CsvReader's similarly-named type+- export failIfInvalidMonth/Day (fixes #216)+- track the commodity of zero amounts when possible+ (useful eg for hledger-web's multi-commodity charts)+- show posting dates in debug output+- more debug helpers++0.23.3 (2014/9/12)++- allow transformers 0.4*++0.23.2 (2014/5/8)++- postingsReport: also fix date sorting of displayed postings (#184)++0.23.1 (2014/5/7)++- postingsReport: with disordered journal entries, postings before the+ report start date could get wrongly included. (#184)++0.23 (2014/5/1)++- orDatesFrom -> spanDefaultsFrom++0.22.2 (2014/4/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/1/6) and older: see http://hledger.org/release-notes or doc/CHANGES.md.
Hledger.hs view
@@ -1,11 +1,398 @@+{-|+This is the root of the @hledger-lib@ package and the @Hledger.*@ module hierarchy.+hledger-lib is the core engine used by various hledger UIs and tools,+providing the main data types, file format parsers, reporting logic, and utilities.++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/>.++-}+ module Hledger (- module Hledger.Data- ,module Hledger.Read- ,module Hledger.Reports- ,module Hledger.Utils+ -- $DOCS+ module X+ ,tests_Hledger ) where-import Hledger.Data-import Hledger.Read-import Hledger.Reports-import Hledger.Utils++import Hledger.Data as X+import Hledger.Read as X+import Hledger.Reports as X+import Hledger.Query as X+import Hledger.Utils as X+import Hledger.Write.Chart (tests_Hledger_Write_Chart)+import Hledger.Write.Chart.Palette (tests_Hledger_Write_Chart_Palette)+import Hledger.Write.Chart.Svg (tests_Hledger_Write_Chart_Svg)+import Hledger.Write.Chart.Text (tests_Hledger_Write_Chart_Text)+import Hledger.Write.Html (tests_Hledger_Write_Html)++tests_Hledger = testGroup "Hledger" [+ tests_Data+ ,tests_Query+ ,tests_Read+ ,tests_Reports+ ,tests_Utils+ ,tests_Hledger_Write_Chart+ ,tests_Hledger_Write_Chart_Palette+ ,tests_Hledger_Write_Chart_Svg+ ,tests_Hledger_Write_Chart_Text+ ,tests_Hledger_Write_Html+ ]+++{- $DOCS++This is also the starting point for hledger's code docs,+aimed at hledger developers and PTA implementors (and curious users).+These are embedded in hledger's source code as Haddock comments and can be viewed+in your code editor,+or in a web browser (eg with @make haddock@),+or (for released versions) on Hackage, eg [hledger-lib:Hledger](https://hackage.haskell.org/package/hledger-lib/docs/Hledger.html).+See also:++- hledger:Hledger.Cli+- hledger-ui:Hledger.UI+- hledger-web:Hledger.Web+- [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)++The rest of this page discusses some general topics.+Together with the hledger manual it describes and provides a functional specification+for hledger and hledger-like apps.+The current code and tests generally conform to this, hopefully.++== Jargon++In addition to the terminology defined in the hledger manual,+eg at [Journal](https://hledger.org/dev/hledger.html#journal):++Here are some words with particular meanings in the context of hledger:++- __/Decimal/__ is a decimal number representation provided by+ the Decimal package, used by hledger for storing numeric quantities.++- __/Normalised decimal/__ A Decimal which has no trailing decimal zeros.+ This can be ensured by the @normaliseDecimal@ function.++- __/Amount/__ ('Amount') is hledger's representation of numeric amounts+ which have a decimal quantity,+ a commodity symbol ('CommoditySymbol'),+ and a display style ('AmountStyle') and display precision ('Precision').+ and optionally a cost in another commodity.++- __/Style/__, __/Amount style/__ An amount's display style, such its decimal mark and symbol placement.+ Represented by "CommodityStyle". (That also stores display precision,+ though it is sometimes convenient to speak of style and precision separately.)++- __/Commodity style/__ The standard display style inferred or specified for a particular commodity.+ Normally all amounts in that commodity are displayed with that style.++- __/Precision/__ In hledger docs, "precision" means the number of decimal digits,+ ie digits to the right of the decimal mark.++- __/Journal precision/__ The number of decimal digits written for an amount+ in the journal file (or in other input data).++- __/Decimal precision/__ The number of decimal digits stored in an Amount's internal Decimal number.+ After parsing, this will be the same as the journal precision; it can increase during amount calculations.++- __/Display precision/__ The preferred number of decimal digits to show in output+ (except by @print@-like reports, which show journal precision by default).++- __/MixedAmount/__ ('MixedAmount') is hledger's representation of a+ multi-commodity amount; it is a set of zero or more Amounts in+ different commodities and costs (stored as a map for efficiency).++- __/amount/__ means either a single-commodity Amount or a multi-commodity MixedAmount,+ depending on context. There are various sources and kinds of amount:++- __/Posting amount/__ An amount being posted (moved from or to) an account.++- __/Cost amount/__ The (cost in a different commodity) associated with a posting amount.+ Eg the purchase cost when buying, or the sale price when selling.+ Cost is recorded in the journal immediately following the posting amount, expressed as a unit or total cost.++- __/Unit cost/__ The cost per unit of the posting amount. Written as @\@ UNITCOST@.++- __/Total cost/__ The total cost the posting amount. Written as @\@\@ TOTALCOST@.++- __/Amount cost/__ A posting amount converted to its cost's commodity. Shown by @hledger print -B@.++ > 2023-01-01+ > (a) 2 A @ 2 B ; <- the amount cost is 4 B++ > 2023-01-01+ > (a) 2 A @@ 2 B ; <- the amount cost is 2 B++- __/Cost/__ can mean any of the four above depending on context.++- __/Balance assertion \/ assignment amount/__+ An amount written after the posting amount and cost,+ following @=@ or @==@ or @=*@ or @==*@,+ representing a balance assertion+ (or when the posting amount is omitted, a balance assignment).++- __/Balance assertion \/ assignment cost/__+ The unit or total cost of the balance assertion\/assignment amount, if any.+ Written after it in the usual way.++- __/Price/__, __/Market price/__+ A conversion rate\/exchange rate from a particular commodity to another as of a particular date.+ These usually fluctuate over time, and are recorded by @P@ price directives.+ Shown by @hledger prices@.++- __/Price amount/__ The amount written in a @P@ price directive,+ which specifies the destination commodity and the per-unit conversion rate.++- __/Cost vs price/__+ Both of these words are quite slippery in english.+ To simplify, we always say+ "cost" for a conversion rate used in a particular transaction (posting), and+ "price" for conversion rates prevailing in the environment.++- __/Value/__+ Any amount converted to some other commodity using a market price on a certain date.+ Shown by any hledger report when the @-V@, @-X@ or @--value@ option is used.++- __/Real postings/__ Normal account postings, required to balance to zero.++- __/Virtual postings/__ Account postings which are exempt from the normal balance-to-zero requirement.+ Written with parentheses around the account name.+ Can be excluded from reports with the @--real@ flag.++- __/Balanced virtual postings/__ Account postings which are required to balance to zero,+ but separately from the real postings.+ Written with square brackets around the account name.+ Can be excluded from reports with the @--real@ flag.++- __/Transaction balancing/__ The process of inferring amounts and/or costs to balance a transaction,+ both in its real and its balanced virtual postings.++- __/Balancing amount/__ An amount that is inferred to balance a transaction with a missing amount. Shown by @hledger print -x@.++ > 2023-01-01+ > a 1+ > b ; <- a balancing amount of -1 is inferred++- __/Balancing cost/__ A cost that is inferred to balance a transaction involving two commodities. Shown by @hledger print -x@.++ > 2023-01-01+ > a 1 A ; <- a balancing cost of @@ 2 B is inferred+ > b -2 B++== Precision++As mentioned in Jargon:+"precision" in hledger means the number of digits to the right of the decimal mark.+And, amounts have several precisions we can talk about:++__/Journal precision/__ is the number of decimal digits recorded in the+journal file \/ input data. We accept up to 255 decimal digits there.++__/Decimal precision/__ is the number of decimal digits stored internally in each Decimal value. Decimal supports up to 255 decimal digits.+In amounts just parsed from the journal, this will be the same as their journal precision.+During calculations, amounts' decimal precision may increase, and will not decrease.++__/Display precision/__ is the preferred number of decimal digits to show in report output.+It is represented by 'AmountPrecision', which is currently part of the 'AmountStyle' stored within each Amount.+In amounts just parsed from the journal, this will be the same as the journal and decimal precisions;+later it gets standardised for each commodity's amounts.+When display precision is less than the decimal precision, fewer, rounded decimal digits are displayed ("rounding").+When display precision is greater than the decimal precision, additional decimal zeros are displayed ("padding").++Basically, hledger amounts have two main precisions we care about at runtime:+their internal decimal precision, used for calculation, and their display precision, used for rendering.++== Rounding++__/Internal rounding/__ means rounding (or padding) internal Decimal numbers,+using @amountSetInternalPrecision@ (which uses @Data.Decimal.roundTo@).+Internal rounding loses information so we don't do this much.++__/Display rounding/__ means applying a target display precision to an existing amount.+This can be done more or less forcefully, determined by a "display rounding strategy" ('Rounding').+Currently this too is stored within each Amount's AmountStyle, for convenience,+(though semantically speaking it is not part of the amount).++The rounding strategies are:++- none - leave the amount's display precision unchanged+- soft - add or remove trailing decimal zeros to approximate the target precision, but don't remove significant digits+- hard - use the exact target precision, possibly rounding and hiding significant digits+- all - do hard rounding of both the main amount and its cost amount (costs are normally not display-rounded).++Broadly, here is when display rounding happens:++1. After reading a journal, when standard commodity styles are applied,+ display precisions are kept unchanged; no rounding is done at this stage (since 1.31).++2. While balancing each transaction,+ its amounts are temporarily hard-rounded to the standard commodity display precisions,+ to provide some configurable tolerance in the balancing calculations.+ (We plan to change this to use transaction-local standard precisions,+ inferred from the transaction's journal precisions only, like Ledger.)++3. Just before output, reports do display rounding according to their needs (since 1.31).+ Most reports do hard display rounding.+ @print@ and other print-like commands do no rounding by default,+ or optionally one of the other rounding strategies.++=== Precision and style handling++hledger supports user-specified precisions from 0 to 255 for each+commodity, and tries to propagate these consistently and intuitively+through all the various processing steps.++This gets rather complicated, so we keep a summary of the current+precision and style behaviours here.+This doc should always be kept synced with code.++In Decimal number calculations:++- the result is normalised, meaning any trailing decimal zeros are trimmed.+ So the result 's precision can be larger+ (1 / 2, both with precision 0, is 0.5, with precision 1)+ or smaller+ (2.0 / 1.0, both with precision 1, is normalised to 2, with precision 0).++In amount calculations:++- When amounts are summed (or subtracted), the result has the maximum+ of their decimal precisions, the maximum of their display precisions,+ and the display style of the second amount.++- When an amount is multiplied (or divided) by a pure number,+ the result's decimal precision is that of the decimal result, normalised.+ The display precision and style is kept unchanged.++- When an amount is converted to cost, the new amount's decimal precision+ is that of the cost amount (if it's a total cost),+ or of the cost amount multiplied by the quantity and normalised (if it's a unit cost).+ Its display precision is kept unchanged.+ Its display style is that of the cost amount.++- When an amount is converted to value, the new amount's decimal precision+ is that of the price amount multiplied by the quantity and normalised.+ Its display precision is set to match the decimal precision,+ or to a fallback precision (8) if the decimal appears to be infinite.+ Its display style is its commodity's standard display style.+ If no standard style is known for the commodity (eg because it does not appear in the journal),+ it is given the fallback display style (symbol on the left unspaced, period as decimal mark,+ precision limited to a maximum of 8 digits).++In a run of hledger:++__1. Input__++__1.1. Parsing__++- Each parsed amount initially has decimal precision, display precision,+ and display style set according to how it was written in the journal.++__1.2. Standard styling__++- After all amounts are parsed,+ standard display styles and display precisions are inferred for each commodity+ from its amounts, directives like @commodity@ and @D@, and -c\/--commodity options+ (in 'journalInferCommodityStyles'),+ and these are applied to all amounts and their costs for consistent display+ (in 'journalStyleAmounts').+ No amount display precisions are changed at this stage.++__1.3. Transaction balancing__++- When amounts are summed, the result has the maximum of their+ decimal precisions and the maximum of their display precisions.++- A balancing amount without a cost will have the same precisions as+ the amount (or sum) it is balancing.++- A balancing amount which has a cost will be converted to cost; see+ "When an amount is converted to cost" above.++- When inferring a balancing cost:++ - The "from amount" is the sum of postings in the first-appearing commodity.++ - The "to amount" is the sum of postings in the second-appearing commodity. See "When amounts are summed" above.++ - If the from amount comes from a single posting, it is given a total cost.+ The cost's decimal precision will be that of the to amount divided by the from quantity, normalised. + Its display precision and style will be that of the to amount.++ - If the from amount comes from multiple postings, they all are given a unit cost.+ The cost's decimal precision will be that of the to amount divided by the from quantity, normalised. + Its display precision will be the sum of the from and to amounts' display precisions, or 2, whichever is greater.+ Its display style will be that of the to amount.++- An amount inferred from a balance assignment will have the same precisions as the balance assignment amount.++__1.4. Determining market prices__++If needed, for a value report:++- Any @P@ price directives form the __/declared prices/__.+ Like posting amounts, their price amounts have been standard-styled+ but their precisions have not yet been changed.++- If the @--infer-market-prices@ flag is used, additional price+ directives are generated from any journal postings with costs+ (in 'amountPriceDirectiveFromCost').+ When the cost was a unit cost, the price amount will have the same precisions.+ When the cost was a total cost,++ - The total cost is divided by the amount quantity to get a unit cost.+ - Its decimal precision becomes that of the decimal result, normalised.+ - Its display precision is set to match the new decimal precision;+ unless the decimal appears to be infinite (because it uses all the 255 digits allowed),+ in which case it is given a smaller fallback display precision (8 decimal digits).++ These plus the declared prices are the __/forward prices/__.++- Additional market prices are generated (as 'MarketPrice' this time, not 'PriceDirective')+ by reversing the forward prices (in 'marketPriceReverse').+ Any new prices generated in this way are the __/reverse prices/__.+ Their decimal precision will be that of (1 \/ the decimal quantity), normalised.+ (They don't have a display precision.)+ These plus the forward prices are the __/direct prices/__+ (giving direct conversion rates from one commodity to another).++And later, if needed:++- For each requested value conversion from commodity A to commodity B,+ if an appropriate price is not found in the direct prices, we try to calculate a __/chained price/__,+ combining two or more direct prices that form a path from A to B.+ The resulting price's decimal precision will be the product of the chained prices, normalised,+ then padded back up to the maximum of their decimal precisions+ (undoing the normalising, because later we will choose the value amount's display precision+ based on the value's decimal precision).++__2. Calculating reports__++- Amounts may be converted to cost (-B), summed, averaged, converted+ to velue (-V\/-X\/--value), etc. Precisions and styles are affected+ as described in "In amount calculations" above.++__3. Output__++- print-like reports: amounts are displayed with their current display precisions.+ Or with --round, they can be soft- or hard-rounded/padded to the standard commodity precisions.+ +- All other reports: amounts are displayed hard rounded/padded to the standard commodity precisions.++- In the roi report: if there is no standard display precision for the valuation commodity,+ it is limited to a maximum of 8 digits.++== Exports of this module:+-}
Hledger/Data.hs view
@@ -1,4 +1,5 @@-{-| +{-# LANGUAGE OverloadedStrings #-}+{-| The Hledger.Data library allows parsing and querying of C++ ledger-style journal files. It generally provides a compatible subset of C++ ledger's@@ -10,46 +11,76 @@ module Hledger.Data ( module Hledger.Data.Account, module Hledger.Data.AccountName,+ module Hledger.Data.AccountType, module Hledger.Data.Amount,- module Hledger.Data.Commodity,+ module Hledger.Data.BalanceData,+ module Hledger.Data.Balancing,+ module Hledger.Data.Currency, module Hledger.Data.Dates,+ module Hledger.Data.DayPartition,+ module Hledger.Data.Errors, module Hledger.Data.Journal,+ module Hledger.Data.JournalChecks,+ module Hledger.Data.Json, module Hledger.Data.Ledger,- module Hledger.Data.Matching,+ module Hledger.Data.Lots,+ module Hledger.Data.Period,+ module Hledger.Data.PeriodData,+ module Hledger.Data.PeriodicTransaction, module Hledger.Data.Posting,- module Hledger.Data.TimeLog,+ module Hledger.Data.RawOptions,+ module Hledger.Data.StringFormat,+ module Hledger.Data.Timeclock, module Hledger.Data.Transaction,+ module Hledger.Data.TransactionModifier, module Hledger.Data.Types,- tests_Hledger_Data+ module Hledger.Data.Valuation,+ tests_Data ) where-import Test.HUnit +import Test.Tasty (testGroup) import Hledger.Data.Account+import Hledger.Data.BalanceData import Hledger.Data.AccountName+import Hledger.Data.AccountType import Hledger.Data.Amount-import Hledger.Data.Commodity+import Hledger.Data.Balancing+import Hledger.Data.Currency import Hledger.Data.Dates+import Hledger.Data.DayPartition+import Hledger.Data.Errors import Hledger.Data.Journal+import Hledger.Data.JournalChecks+import Hledger.Data.Json import Hledger.Data.Ledger-import Hledger.Data.Matching+import Hledger.Data.Lots+import Hledger.Data.Period+import Hledger.Data.PeriodData+import Hledger.Data.PeriodicTransaction import Hledger.Data.Posting-import Hledger.Data.TimeLog+import Hledger.Data.RawOptions+import Hledger.Data.StringFormat+import Hledger.Data.Timeclock import Hledger.Data.Transaction-import Hledger.Data.Types+import Hledger.Data.TransactionModifier+import Hledger.Data.Types hiding (MixedAmountKey, Mixed)+import Hledger.Data.Valuation -tests_Hledger_Data = TestList- [- tests_Hledger_Data_Account- ,tests_Hledger_Data_AccountName- ,tests_Hledger_Data_Amount- ,tests_Hledger_Data_Commodity- ,tests_Hledger_Data_Dates- ,tests_Hledger_Data_Journal- ,tests_Hledger_Data_Ledger- ,tests_Hledger_Data_Matching- ,tests_Hledger_Data_Posting- ,tests_Hledger_Data_TimeLog- ,tests_Hledger_Data_Transaction- -- ,tests_Hledger_Data_Types- ]+tests_Data = testGroup "Data" [+ tests_Account+ ,tests_AccountName+ ,tests_Amount+ ,tests_BalanceData+ ,tests_Balancing+ ,tests_DayPartition+ -- ,tests_Currency+ ,tests_Journal+ ,tests_Ledger+ ,tests_PeriodData+ ,tests_Posting+ ,tests_Valuation+ ,tests_StringFormat+ ,tests_Timeclock+ ,tests_Transaction+ ]
Hledger/Data/Account.hs view
@@ -1,32 +1,393 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-} {-| -An 'Account' stores -- an 'AccountName',--- all 'Posting's in the account, excluding subaccounts--- a 'MixedAmount' representing the account balance, including subaccounts.+An 'Account' has a name, a list of subaccounts, an optional parent+account, and subaccounting-excluding and -including balances. -} module Hledger.Data.Account-where-import Test.HUnit-import Text.Printf+( nullacct+, accountFromBalances+, accountFromPostings+, accountsFromPostings+, accountTree+, accountTreeFromBalanceAndNames+, showAccounts+, showAccountsBoringFlag+, printAccounts+, lookupAccount+, parentAccounts+, accountsLevels+, mapAccounts+, mapPeriodData+, anyAccounts+, filterAccounts+, sumAccounts+, clipAccounts+, clipAccountsAndAggregate+, pruneAccounts+, flattenAccounts+, mergeAccounts+, accountSetDeclarationInfo+, sortAccountNamesByDeclaration+, sortAccountTreeByDeclaration+, sortAccountTreeOn+-- -- * Tests+, tests_Account+) where +import Control.Applicative ((<|>))+import Data.HashSet qualified as HS+import Data.HashMap.Strict qualified as HM+import Data.List (find, sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List.NonEmpty (NonEmpty(..), groupWith)+import Data.Map qualified as M+import Data.Maybe (fromMaybe)+import Data.Text qualified as T+import Data.These (These(..))+import Data.Time (Day(..), fromGregorian)+import Safe (headMay)+import Text.Printf (printf)++import Hledger.Data.BalanceData ()+import Hledger.Data.PeriodData+import Hledger.Data.AccountName import Hledger.Data.Amount import Hledger.Data.Types+import Hledger.Utils -instance Show Account where- show (Account a ts b) = printf "Account %s with %d txns and %s balance" a (length ts) (showMixedAmount b)+-- deriving instance Show Account+instance Show a => Show (Account a) where+ showsPrec d acct =+ showParen (d > 10) $+ showString "Account "+ . showString (T.unpack $ aname acct)+ . showString " (boring:"+ . showString (if aboring acct then "y" else "n")+ . showString ", adata:"+ . shows (adata acct)+ . showChar ')' -instance Eq Account where- (==) (Account n1 t1 b1) (Account n2 t2 b2) = n1 == n2 && t1 == t2 && b1 == b2+instance Eq (Account a) where+ (==) a b = aname a == aname b -- quick equality test for speed+ -- and+ -- [ aname a == aname b+ -- -- , aparent a == aparent b -- avoid infinite recursion+ -- , asubs a == asubs b+ -- , aebalance a == aebalance b+ -- , aibalance a == aibalance b+ -- ] -nullacct = Account "" [] nullmixedamt+nullacct :: Account BalanceData+nullacct = accountFromBalances "" mempty -tests_Hledger_Data_Account = TestList [- ]+-- | Construct an 'Account" from an account name and balances. Other fields are+-- left blank.+accountFromBalances :: AccountName -> PeriodData a -> Account a+accountFromBalances name bal = Account+ { aname = name+ , adeclarationinfo = Nothing+ , asubs = []+ , aparent = Nothing+ , aboring = False+ , adata = bal+ } +-- | Derive 1. an account tree and 2. each account's total exclusive and+-- inclusive changes associated with dates from a list of postings and a+-- function for associating a date to each posting (usually representing the+-- start dates of report subperiods).+-- This is the core of the balance command (and of *ledger).+-- The accounts are returned as a list in flattened tree order,+-- and also reference each other as a tree.+-- (The first account is the root of the tree.)+accountsFromPostings :: (Posting -> Maybe Day) -> [Posting] -> [Account BalanceData]+accountsFromPostings getPostingDate = flattenAccounts . accountFromPostings getPostingDate++-- | Derive 1. an account tree and 2. each account's total exclusive+-- and inclusive changes associated with dates from a list of postings and a+-- function for associating a date to each posting (usually representing the+-- start dates of report subperiods).+-- This is the core of the balance command (and of *ledger).+-- The accounts are returned as a tree.+accountFromPostings :: (Posting -> Maybe Day) -> [Posting] -> Account BalanceData+accountFromPostings getPostingDate ps =+ tieAccountParents . sumAccounts $ mapAccounts setBalance acctTree+ where+ -- The special name "..." is stored in the root of the tree+ acctTree = accountTree "root" . HM.keys $ HM.delete "..." accountMap+ setBalance a = a{adata = HM.lookupDefault mempty name accountMap}+ where name = if aname a == "root" then "..." else aname a+ accountMap = processPostings ps++ processPostings :: [Posting] -> HM.HashMap AccountName (PeriodData BalanceData)+ processPostings = foldl' (flip processAccountName) mempty+ where+ processAccountName p = HM.alter (updateBalanceData p) (paccount p)+ updateBalanceData p = Just+ . insertPeriodData (getPostingDate p) (BalanceData (pamount p) nullmixedamt 1)+ . fromMaybe mempty++-- | Convert a list of account names to a tree of Account objects,+-- with just the account names filled in and an empty balance.+-- A single root account with the given name is added.+accountTree :: Monoid a => AccountName -> [AccountName] -> Account a+accountTree rootname = accountTreeFromBalanceAndNames rootname mempty++-- | Convert a list of account names to a tree of Account objects,+-- with just the account names filled in. Each account is given the same+-- supplied balance.+-- A single root account with the given name is added.+accountTreeFromBalanceAndNames :: AccountName -> PeriodData a -> [AccountName] -> Account a+accountTreeFromBalanceAndNames rootname bals as =+ (accountFromBalances rootname bals){ asubs=map (uncurry accountTree') $ M.assocs m }+ where+ T m = treeFromPaths $ map expandAccountName as :: FastTree AccountName+ accountTree' a (T m') =+ (accountFromBalances a bals){ asubs=map (uncurry accountTree') $ M.assocs m' }++-- | An efficient-to-build tree suggested by Cale Gibbard, probably+-- better than accountNameTreeFrom.+newtype FastTree a = T (M.Map a (FastTree a))+ deriving (Show, Eq, Ord)++mergeTrees :: (Ord a) => FastTree a -> FastTree a -> FastTree a+mergeTrees (T m) (T m') = T (M.unionWith mergeTrees m m')++treeFromPath :: [a] -> FastTree a+treeFromPath [] = T M.empty+treeFromPath (x:xs) = T (M.singleton x (treeFromPath xs))++treeFromPaths :: (Ord a) => [[a]] -> FastTree a+treeFromPaths = foldl' mergeTrees (T M.empty) . map treeFromPath+++-- | Tie the knot so all subaccounts' parents are set correctly.+tieAccountParents :: Account a -> Account a+tieAccountParents = tie Nothing+ where+ tie parent a@Account{..} = a'+ where+ a' = a{aparent=parent, asubs=map (tie (Just a')) asubs}++-- | Get this account's parent accounts, from the nearest up to the root.+parentAccounts :: Account a -> [Account a]+parentAccounts Account{aparent=Nothing} = []+parentAccounts Account{aparent=Just a} = a:parentAccounts a++-- | List the accounts at each level of the account tree.+accountsLevels :: Account a -> [[Account a]]+accountsLevels = takeWhile (not . null) . iterate (concatMap asubs) . (:[])++-- | Map a (non-tree-structure-modifying) function over this and sub accounts.+mapAccounts :: (Account a -> Account a) -> Account a -> Account a+mapAccounts f a = f a{asubs = map (mapAccounts f) $ asubs a}++-- | Apply a function to all 'PeriodData' within this and sub accounts.+mapPeriodData :: (PeriodData a -> PeriodData a) -> Account a -> Account a+mapPeriodData f = mapAccounts (\a -> a{adata = f $ adata a})++-- | Is the predicate true on any of this account or its subaccounts ?+anyAccounts :: (Account a -> Bool) -> Account a -> Bool+anyAccounts p a+ | p a = True+ | otherwise = any (anyAccounts p) $ asubs a++-- | Is the predicate true on all of this account and its subaccounts ?+allAccounts :: (Account a -> Bool) -> Account a -> Bool+allAccounts p a+ | not (p a) = False+ | otherwise = all (allAccounts p) $ asubs a++-- | Recalculate all the subaccount-inclusive balances in this tree.+sumAccounts :: Account BalanceData -> Account BalanceData+sumAccounts a = a{asubs = subs, adata = setInclusiveBalances $ adata a}+ where+ subs = map sumAccounts $ asubs a+ subtotals = foldMap adata subs++ setInclusiveBalances :: PeriodData BalanceData -> PeriodData BalanceData+ setInclusiveBalances = mergePeriodData onlyChildren noChildren combineChildren subtotals++ combineChildren children this = this {bdincludingsubs = bdexcludingsubs this <> bdincludingsubs children}+ onlyChildren children = mempty{bdincludingsubs = bdincludingsubs children}+ noChildren this = this {bdincludingsubs = bdexcludingsubs this}++-- | Remove all subaccounts below a certain depth.+clipAccounts :: Int -> Account a -> Account a+clipAccounts 0 a = a{asubs=[]}+clipAccounts d a = a{asubs=subs}+ where+ subs = map (clipAccounts (d-1)) $ asubs a++-- | Remove subaccounts below the specified depth, aggregating their balance at the depth limit+-- (accounts at the depth limit will have any sub-balances merged into their exclusive balance).+-- If the depth is Nothing, return the original accounts+clipAccountsAndAggregate :: Monoid a => DepthSpec -> [Account a] -> [Account a]+clipAccountsAndAggregate (DepthSpec Nothing []) as = as+clipAccountsAndAggregate depthSpec as = combined+ where+ clipped = [a{aname=clipOrEllipsifyAccountName depthSpec $ aname a} | a <- as]+ combined = [a{adata=foldMap adata same}+ | same@(a:|_) <- groupWith aname clipped]++{-+test cases, assuming d=1:++assets:cash 1 1+assets:checking 1 1+->+as: [assets:cash 1 1, assets:checking 1 1]+clipped: [assets 1 1, assets 1 1]+combined: [assets 2 2]++assets 0 2+ assets:cash 1 1+ assets:checking 1 1+->+as: [assets 0 2, assets:cash 1 1, assets:checking 1 1]+clipped: [assets 0 2, assets 1 1, assets 1 1]+combined: [assets 2 2]++assets 0 2+ assets:bank 1 2+ assets:bank:checking 1 1+->+as: [assets 0 2, assets:bank 1 2, assets:bank:checking 1 1]+clipped: [assets 0 2, assets 1 2, assets 1 1]+combined: [assets 2 2]++-}++-- | Remove all leaf accounts and subtrees matching a predicate.+pruneAccounts :: (Account a -> Bool) -> Account a -> Maybe (Account a)+pruneAccounts p = headMay . prune+ where+ prune a+ | null prunedsubs = if p a then [] else [a']+ | otherwise = [a']+ where+ prunedsubs = concatMap prune $ asubs a+ a' = a{asubs=prunedsubs}++-- | Flatten an account tree into a list, which is sometimes+-- convenient. Note since accounts link to their parents/subs, the+-- tree's structure remains intact and can still be used. It's a tree/list!+flattenAccounts :: Account a -> [Account a]+flattenAccounts a = squish a []+ where squish a' as = a' : Prelude.foldr squish as (asubs a')++-- | Filter an account tree (to a list).+filterAccounts :: (Account a -> Bool) -> Account a -> [Account a]+filterAccounts p a+ | p a = a : concatMap (filterAccounts p) (asubs a)+ | otherwise = concatMap (filterAccounts p) (asubs a)++-- | Merge two account trees and their subaccounts.+--+-- This assumes that the top-level 'Account's have the same name.+mergeAccounts :: Account a -> Account b -> Account (These a b)+mergeAccounts a = tieAccountParents . merge a+ where+ merge acct1 acct2 = acct1+ { adeclarationinfo = adeclarationinfo acct1 <|> adeclarationinfo acct2+ , aparent = Nothing+ , aboring = aboring acct1 && aboring acct2+ , adata = mergeBalances (adata acct1) (adata acct2)+ , asubs = mergeSubs (sortOn aname $ asubs acct1) (sortOn aname $ asubs acct2)+ }++ mergeSubs (x:xs) (y:ys) = case compare (aname x) (aname y) of+ EQ -> merge x y : mergeSubs xs ys+ LT -> fmap This x : mergeSubs xs (y:ys)+ GT -> fmap That y : mergeSubs (x:xs) ys+ mergeSubs xs [] = map (fmap This) xs+ mergeSubs [] ys = map (fmap That) ys++ mergeBalances = mergePeriodData This That These++-- | Sort each group of siblings in an account tree by projecting through+-- a provided function.+sortAccountTreeOn :: Ord b => (Account a -> b) -> Account a -> Account a+sortAccountTreeOn f = mapAccounts $ \a -> a{asubs=sortOn f $ asubs a}++-- | Add extra info for this account derived from the Journal's+-- account directives, if any (comment, tags, declaration order..).+accountSetDeclarationInfo :: Journal -> Account a -> Account a+accountSetDeclarationInfo j a@Account{..} =+ a{ adeclarationinfo=lookup aname $ jdeclaredaccounts j }++-- | Sort account names by the order in which they were declared in+-- the journal, at each level of the account tree (ie within each+-- group of siblings). Undeclared accounts are sorted last and+-- alphabetically.+-- This is hledger's default sort for reports organised by account.+-- The account list is converted to a tree temporarily, adding any+-- missing parents; these can be kept (suitable for a tree-mode report)+-- or removed (suitable for a flat-mode report).+--+sortAccountNamesByDeclaration :: Journal -> Bool -> [AccountName] -> [AccountName]+sortAccountNamesByDeclaration j keepparents as =+ (if keepparents then id else filter (`HS.member` HS.fromList as)) $ -- maybe discard missing parents that were added+ map aname $ -- keep just the names+ drop 1 $ -- drop the root node that was added+ flattenAccounts $ -- convert to an account list+ sortAccountTreeByDeclaration $ -- sort by declaration order (and name)+ mapAccounts (accountSetDeclarationInfo j) $ -- add declaration order info+ (accountTree "root" as :: Account ()) -- convert to an account tree++-- | Sort each group of siblings in an account tree by declaration order, then account name.+-- So each group will contain first the declared accounts,+-- in the same order as their account directives were parsed,+-- and then the undeclared accounts, sorted by account name.+sortAccountTreeByDeclaration :: Account a -> Account a+sortAccountTreeByDeclaration a+ | null $ asubs a = a+ | otherwise = a{asubs=+ sortOn accountDeclarationOrderAndName $+ map sortAccountTreeByDeclaration $ asubs a+ }++accountDeclarationOrderAndName :: Account a -> (Int, AccountName)+accountDeclarationOrderAndName a = (adeclarationorder', aname a)+ where+ adeclarationorder' = maybe maxBound adideclarationorder $ adeclarationinfo a++-- | Search an account list by name.+lookupAccount :: AccountName -> [Account a] -> Maybe (Account a)+lookupAccount a = find ((==a).aname)++-- debug helpers++printAccounts :: Show a => Account a -> IO ()+printAccounts = putStrLn . showAccounts++showAccounts :: Show a => Account a -> String+showAccounts = unlines . map showAccountDebug . flattenAccounts++showAccountsBoringFlag = unlines . map (show . aboring) . flattenAccounts++showAccountDebug a = printf "%-25s %s %4s"+ (aname a)+ (if aboring a then "b" else " " :: String)+ (show $ adata a)+++tests_Account = testGroup "Account" [+ testGroup "accountFromPostings" [+ testCase "no postings, no days" $+ accountFromPostings undefined [] @?= accountTree "root" []+ ,testCase "no postings, only 2000-01-01" $+ allAccounts (all (== fromGregorian 2000 01 01) . M.keys . pdperiods . adata)+ (accountFromPostings undefined []) @? "Not all adata have exactly 2000-01-01"+ ]+ ]
Hledger/Data/AccountName.hs view
@@ -1,4 +1,5 @@-{-# LANGUAGE NoMonomorphismRestriction#-}+{-# LANGUAGE NoMonomorphismRestriction #-}+{-# LANGUAGE OverloadedStrings #-} {-| 'AccountName's are strings like @assets:cash:petty@, with multiple@@ -7,152 +8,338 @@ -} -module Hledger.Data.AccountName+module Hledger.Data.AccountName (+ accountLeafName+ ,accountNameComponents+ ,accountNameHasEmptyPart+ ,accountNameDrop+ ,accountNameFromComponents+ ,accountNameLevel+ ,accountNameToAccountOnlyRegex+ ,accountNameToAccountOnlyRegexCI+ ,accountNameToAccountRegex+ ,accountNameToAccountRegexCI+ ,accountNameTreeFrom+ ,accountSummarisedName+ ,accountNameInferType+ ,accountNameInferTypeExcept+ ,accountNameType+ ,defaultBaseConversionAccount+ ,defaultGainAccount+ ,defaultImbalanceAccount+ ,assetAccountRegex+ ,cashAccountRegex+ ,liabilityAccountRegex+ ,equityAccountRegex+ ,conversionAccountRegex+ ,revenueAccountRegex+ ,gainAccountRegex+ ,unrealisedGainAccountRegex+ ,imbalanceAccountRegex+ ,expenseAccountRegex+ ,acctsep+ ,acctsepchar+ ,clipAccountName+ ,clipOrEllipsifyAccountName+ ,getAccountNameClippedDepth+ ,elideAccountName+ ,escapeName+ ,expandAccountName+ ,expandAccountNames+ ,isAccountNamePrefixOf+-- ,isAccountRegex+ ,isSubAccountNameOf+ ,parentAccountName+ ,parentAccountNames+ ,subAccountNamesFrom+ ,topAccountNames+ ,topAccountName+ ,unbudgetedAccountName+ ,accountNamePostingType+ ,accountNameWithoutPostingType+ ,accountNameWithPostingType+ ,joinAccountNames+ ,concatAccountNames+ ,accountNameApplyAliases+ ,accountNameApplyAliasesMemo+ ,tests_AccountName+) where-import Data.List-import Data.Map (Map)-import Data.Tree-import Test.HUnit-import Text.Printf-import qualified Data.Map as M -import Hledger.Data.Types-import Hledger.Utils+import Control.Applicative ((<|>))+import Control.Monad (foldM)+import Data.Foldable (asum, find, toList)+import Data.List.NonEmpty qualified as NE+import Data.Map qualified as M+import Data.Maybe (mapMaybe)+import Data.MemoUgly (memo)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Tree (Tree(..), unfoldTree)+import Safe+import Text.DocLayout (realLength) +import Hledger.Data.Types hiding (asubs)+import Hledger.Utils +-- $setup+-- >>> :set -XOverloadedStrings --- change to use a different separator for nested accounts+acctsepchar :: Char acctsepchar = ':' -accountNameComponents :: AccountName -> [String]-accountNameComponents = splitAtElement acctsepchar+acctsep :: Text+acctsep = T.pack [acctsepchar] -accountNameFromComponents :: [String] -> AccountName-accountNameFromComponents = concat . intersperse [acctsepchar]+-- The base conversion account name used by --infer-equity,+-- when no other account of type V/Conversion has been declared.+defaultBaseConversionAccount = "equity:conversion" -accountLeafName :: AccountName -> String-accountLeafName = last . accountNameComponents+-- The default account name for inferred gain postings,+-- when no other account of type G/Gain has been declared.+defaultGainAccount = "revenues:gain" -accountNameLevel :: AccountName -> Int-accountNameLevel "" = 0-accountNameLevel a = length (filter (==acctsepchar) a) + 1+-- The default account name for imbalance postings generated by --infer-imbalance,+-- when no other account of type M/Imbalance has been declared.+defaultImbalanceAccount = "equity:imbalance" -accountNameDrop :: Int -> AccountName -> AccountName-accountNameDrop n = accountNameFromComponents . drop n . accountNameComponents+-- | Regular expressions matching common English top-level account names,+-- used as a fallback when account types are not declared.+assetAccountRegex = toRegexCI' "^assets?(:|$)"+cashAccountRegex = toRegexCI' "^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|current)(:|$)"+liabilityAccountRegex = toRegexCI' "^(debts?|liabilit(y|ies))(:|$)"+equityAccountRegex = toRegexCI' "^equity(:|$)"+conversionAccountRegex = toRegexCI' "^equity:(trade|trades|trading|conversion)(:|$)"+revenueAccountRegex = toRegexCI' "^(income|revenue)s?(:|$)"+gainAccountRegex = toRegexCI' "^(income|revenue)s?:(capital[- ]?)?(gains?|loss(es)?)(:|$)"+unrealisedGainAccountRegex = toRegexCI' "^equity:unreali[sz]ed([- ](capital[- ])?gains?)?(:|$)"+imbalanceAccountRegex = toRegexCI' "^equity:imbalances?(:|$)"+expenseAccountRegex = toRegexCI' "^expenses?(:|$)" --- | ["a:b:c","d:e"] -> ["a","a:b","a:b:c","d","d:e"]-expandAccountNames :: [AccountName] -> [AccountName]-expandAccountNames as = nub $ concatMap expand as- where expand = map accountNameFromComponents . tail . inits . accountNameComponents+-- | Try to guess an account's type from its name,+-- matching common English top-level account names.+-- (The top-level account name is checked first, cheaply, and only the regular+-- expressions which could then match are tried. Previously all of them were tried+-- for every account, a noticeable cost with many accounts.)+accountNameInferType :: AccountName -> Maybe AccountType+accountNameInferType a+ | isOneOf ["asset", "assets"] =+ if regexMatchText cashAccountRegex a then Just Cash else Just Asset+ | isOneOf ["debt", "debts", "liability", "liabilities"] = Just Liability+ | isOneOf ["equity"] =+ if regexMatchText conversionAccountRegex a then Just Conversion+ else if regexMatchText unrealisedGainAccountRegex a then Just UnrealisedGain+ else if regexMatchText imbalanceAccountRegex a then Just Imbalance+ else Just Equity+ | isOneOf ["income", "incomes", "revenue", "revenues"] =+ if regexMatchText gainAccountRegex a then Just Gain else Just Revenue+ | isOneOf ["expense", "expenses"] = Just Expense+ | otherwise = Nothing+ where+ toplevel = T.toLower $ T.takeWhile (/= acctsepchar) a+ isOneOf = elem toplevel --- | ["a:b:c","d:e"] -> ["a","d"]-topAccountNames :: [AccountName] -> [AccountName]-topAccountNames as = [a | a <- expandAccountNames as, accountNameLevel a == 1]+-- | Like accountNameInferType, but exclude the provided types from the guesses.+-- Used eg to prevent "equity:conversion" being inferred as Conversion when a different+-- account has been declared with that type.+accountNameInferTypeExcept :: [AccountType] -> AccountName -> Maybe AccountType+accountNameInferTypeExcept excludedtypes a =+ case accountNameInferType a of+ Just t | not $ t `elem` excludedtypes -> Just t+ _ -> Nothing -parentAccountName :: AccountName -> AccountName-parentAccountName = accountNameFromComponents . init . accountNameComponents+-- Extract the 'AccountType' of an 'AccountName' by looking it up in the+-- provided Map, traversing the parent accounts if necessary. If none of those+-- work, try 'accountNameInferType'.+accountNameType :: M.Map AccountName AccountType -> AccountName -> Maybe AccountType+accountNameType atypes a = asum (map (`M.lookup` atypes) $ a : parentAccountNames a)+ <|> accountNameInferType a -parentAccountNames :: AccountName -> [AccountName]-parentAccountNames a = parentAccountNames' $ parentAccountName a- where- parentAccountNames' "" = []- parentAccountNames' a = a : parentAccountNames' (parentAccountName a)+-- accountNameComponents :: AccountName -> [String]+-- accountNameComponents = splitAtElement acctsepchar -isAccountNamePrefixOf :: AccountName -> AccountName -> Bool-isAccountNamePrefixOf = isPrefixOf . (++ [acctsepchar])+accountNameComponents :: AccountName -> [Text]+accountNameComponents = T.splitOn acctsep -isSubAccountNameOf :: AccountName -> AccountName -> Bool-s `isSubAccountNameOf` p = - (p `isAccountNamePrefixOf` s) && (accountNameLevel s == (accountNameLevel p + 1))+-- | Does this account name have an empty part, from a leading, trailing+-- or repeated account separator, ignoring any virtual posting brackets ?+-- Account names as written must not have these (see accountnamep).+accountNameHasEmptyPart :: AccountName -> Bool+accountNameHasEmptyPart a =+ T.null a' || acctsep `T.isPrefixOf` a' || acctsep `T.isSuffixOf` a' || (acctsep <> acctsep) `T.isInfixOf` a'+ where a' = accountNameWithoutPostingType a --- | From a list of account names, select those which are direct--- subaccounts of the given account name.-subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName]-subAccountNamesFrom accts a = filter (`isSubAccountNameOf` a) accts+accountNameFromComponents :: [Text] -> AccountName+accountNameFromComponents = T.intercalate acctsep --- | Convert a list of account names to a tree.-accountNameTreeFrom :: [AccountName] -> Tree AccountName-accountNameTreeFrom = accountNameTreeFrom1+accountLeafName :: AccountName -> Text+accountLeafName = T.takeWhileEnd (/= acctsepchar) -accountNameTreeFrom1 accts = - Node "top" (accounttreesfrom (topAccountNames accts))- where- accounttreesfrom :: [AccountName] -> [Tree AccountName]- accounttreesfrom [] = []- accounttreesfrom as = [Node a (accounttreesfrom $ subs a) | a <- as]- subs = subAccountNamesFrom (expandAccountNames accts)+-- | Truncate all account name components but the last to two characters.+accountSummarisedName :: AccountName -> Text+accountSummarisedName a+ -- length cs > 1 = take 2 (head cs) ++ ":" ++ a'+ | length cs > 1 = T.intercalate ":" (map (T.take 2) $ init cs) <> ":" <> a'+ | otherwise = a'+ where+ cs = accountNameComponents a+ a' = accountLeafName a -nullaccountnametree = Node "top" []+-- | The level (depth) of an account name.+--+-- >>> accountNameLevel "" -- special case+-- 0+-- >>> accountNameLevel "assets"+-- 1+-- >>> accountNameLevel "assets:cash"+-- 2+accountNameLevel :: AccountName -> Int+accountNameLevel "" = 0+accountNameLevel a = T.length (T.filter (==acctsepchar) a) + 1 -accountNameTreeFrom2 accts = - Node "top" $ unfoldForest (\a -> (a, subs a)) $ topAccountNames accts- where- subs = subAccountNamesFrom allaccts- allaccts = expandAccountNames accts- -- subs' a = subsmap ! a- -- subsmap :: Map AccountName [AccountName]- -- subsmap = Data.Map.fromList [(a, subAccountNamesFrom allaccts a) | a <- allaccts]+-- | A top-level account prefixed to some accounts in budget reports.+-- Defined here so it can be ignored by accountNameDrop.+unbudgetedAccountName :: T.Text+unbudgetedAccountName = "<unbudgeted>" -accountNameTreeFrom3 accts = - Node "top" $ forestfrom allaccts $ topAccountNames accts- where- -- drop accts from the list of potential subs as we add them to the tree- forestfrom :: [AccountName] -> [AccountName] -> Forest AccountName- forestfrom subaccts accts = - [let subaccts' = subaccts \\ accts in Node a $ forestfrom subaccts' (subAccountNamesFrom subaccts' a) | a <- accts]- allaccts = expandAccountNames accts- +accountNamePostingType :: AccountName -> PostingRealness+accountNamePostingType a+ | T.null a = RealPosting+ | T.head a == '[' && T.last a == ']' = BalancedVirtualPosting+ | T.head a == '(' && T.last a == ')' = VirtualPosting+ | otherwise = RealPosting --- a more efficient tree builder from Cale Gibbard-newtype Tree' a = T (Map a (Tree' a))- deriving (Show, Eq, Ord)+accountNameWithoutPostingType :: AccountName -> AccountName+accountNameWithoutPostingType a = case accountNamePostingType a of+ BalancedVirtualPosting -> textUnbracket a+ VirtualPosting -> textUnbracket a+ RealPosting -> a -mergeTrees :: (Ord a) => Tree' a -> Tree' a -> Tree' a-mergeTrees (T m) (T m') = T (M.unionWith mergeTrees m m')+accountNameWithPostingType :: PostingRealness -> AccountName -> AccountName+accountNameWithPostingType BalancedVirtualPosting = wrap "[" "]" . accountNameWithoutPostingType+accountNameWithPostingType VirtualPosting = wrap "(" ")" . accountNameWithoutPostingType+accountNameWithPostingType RealPosting = accountNameWithoutPostingType -emptyTree = T M.empty+-- | Prefix one account name to another, preserving posting type+-- indicators like concatAccountNames.+joinAccountNames :: AccountName -> AccountName -> AccountName+joinAccountNames a b = concatAccountNames $ filter (not . T.null) [a,b] -pathtree :: [a] -> Tree' a-pathtree [] = T M.empty-pathtree (x:xs) = T (M.singleton x (pathtree xs))+-- | Join account names into one. If any of them has () or [] posting type+-- indicators, these (the first type encountered) will also be applied to+-- the resulting account name.+concatAccountNames :: [AccountName] -> AccountName+concatAccountNames as = accountNameWithPostingType t $ T.intercalate ":" $ map accountNameWithoutPostingType as+ where t = headDef RealPosting $ filter (/= RealPosting) $ map accountNamePostingType as -fromPaths :: (Ord a) => [[a]] -> Tree' a-fromPaths = foldl' mergeTrees emptyTree . map pathtree+-- | Rewrite an account name using all matching aliases from the given list, in sequence.+-- Each alias sees the result of applying the previous aliases.+-- Or, return any error arising from a bad regular expression in the aliases.+accountNameApplyAliases :: [AccountAlias] -> AccountName -> Either RegexError AccountName+accountNameApplyAliases aliases a =+ let (name,typ) = (accountNameWithoutPostingType a, accountNamePostingType a)+ in foldM+ (\acct alias -> dbg6 "result" $ aliasReplace (dbg6 "alias" alias) (dbg6 "account" acct))+ name+ aliases+ >>= Right . accountNameWithPostingType typ --- the above, but trying to build Tree directly+-- | Memoising version of accountNameApplyAliases, maybe overkill.+accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> Either RegexError AccountName+accountNameApplyAliasesMemo aliases = memo (accountNameApplyAliases aliases)+ -- XXX re-test this memoisation --- mergeTrees' :: (Ord a) => Tree a -> Tree a -> Tree a--- mergeTrees' (Node m ms) (Node m' ms') = Node undefined (ms `union` ms')+-- aliasMatches :: AccountAlias -> AccountName -> Bool+-- aliasMatches (BasicAlias old _) a = old `isAccountNamePrefixOf` a+-- aliasMatches (RegexAlias re _) a = regexMatchesCI re a --- emptyTree' = Node "top" []+aliasReplace :: AccountAlias -> AccountName -> Either RegexError AccountName+aliasReplace (BasicAlias old new) a+ | old `isAccountNamePrefixOf` a || old == a =+ Right $ new <> T.drop (T.length old) a+ | otherwise = Right a+aliasReplace (RegexAlias re repl) a =+ fmap T.pack . regexReplace re repl $ T.unpack a -- XXX --- pathtree' :: [a] -> Tree a--- pathtree' [] = Node undefined []--- pathtree' (x:xs) = Node x [pathtree' xs]+-- | Remove some number of account name components from the front of the account name.+-- If the special "<unbudgeted>" top-level account is present, it is preserved and+-- dropping affects the rest of the account name.+accountNameDrop :: Int -> AccountName -> AccountName+accountNameDrop n a+ | a == unbudgetedAccountName = a+ | unbudgetedAccountAndSep `T.isPrefixOf` a =+ case accountNameDrop n $ T.drop (T.length unbudgetedAccountAndSep) a of+ "" -> unbudgetedAccountName+ a' -> unbudgetedAccountAndSep <> a'+ | otherwise = accountNameFromComponentsOrElide . drop n $ accountNameComponents a+ where+ unbudgetedAccountAndSep = unbudgetedAccountName <> acctsep+ accountNameFromComponentsOrElide [] = "..."+ accountNameFromComponentsOrElide xs = accountNameFromComponents xs --- fromPaths' :: (Ord a) => [[a]] -> Tree a--- fromPaths' = foldl' mergeTrees' emptyTree' . map pathtree'+-- | Sorted unique account names implied by these account names,+-- ie these plus all their parent accounts up to the root.+-- Eg: ["a:b:c","d:e"] -> ["a","a:b","a:b:c","d","d:e"]+expandAccountNames :: [AccountName] -> [AccountName]+expandAccountNames = toList . foldMap (S.fromList . expandAccountName) +-- | "a:b:c" -> ["a","a:b","a:b:c"]+expandAccountName :: AccountName -> [AccountName]+expandAccountName = map accountNameFromComponents . NE.tail . NE.inits . accountNameComponents --- converttree :: [AccountName] -> Tree' AccountName -> [Tree AccountName]--- converttree parents (T m) = [Node (accountNameFromComponents $ parents ++ [a]) (converttree (parents++[a]) b) | (a,b) <- M.toList m]+-- | ["a:b:c","d:e"] -> ["a","d"]+topAccountNames :: [AccountName] -> [AccountName]+topAccountNames = filter ((1==) . accountNameLevel) . expandAccountNames --- accountNameTreeFrom4 :: [AccountName] -> Tree AccountName--- accountNameTreeFrom4 accts = Node "top" (converttree [] $ fromPaths $ map accountNameComponents accts)+-- | "a:b:c" -> "a"+topAccountName :: AccountName -> AccountName+topAccountName = T.takeWhile (/= acctsepchar) -converttree :: Tree' AccountName -> [Tree AccountName]-converttree (T m) = [Node a (converttree b) | (a,b) <- M.toList m]+-- | The parent of an account name, or "" if it has none. ("a:b:c" -> "a:b").+-- Returns a slice of the name, without copying.+parentAccountName :: AccountName -> AccountName+parentAccountName = T.dropEnd 1 . T.dropWhileEnd (/= acctsepchar) -expandTreeNames :: Tree AccountName -> Tree AccountName-expandTreeNames (Node x ts) = Node x (map (treemap (\n -> accountNameFromComponents [x,n]) . expandTreeNames) ts)+parentAccountNames :: AccountName -> [AccountName]+parentAccountNames a = parentAccountNames' $ parentAccountName a+ where+ parentAccountNames' "" = []+ parentAccountNames' a2 = a2 : parentAccountNames' (parentAccountName a2) -accountNameTreeFrom4 :: [AccountName] -> Tree AccountName-accountNameTreeFrom4 = Node "top" . map expandTreeNames . converttree . fromPaths . map accountNameComponents+-- | Is the first account a parent or other ancestor of (and not the same as) the second ?+isAccountNamePrefixOf :: AccountName -> AccountName -> Bool+isAccountNamePrefixOf = T.isPrefixOf . (<> acctsep) +isSubAccountNameOf :: AccountName -> AccountName -> Bool+s `isSubAccountNameOf` p =+ (p `isAccountNamePrefixOf` s) && (accountNameLevel s == (accountNameLevel p + 1)) +-- | From a list of account names, select those which are direct+-- subaccounts of the given account name.+subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName]+subAccountNamesFrom accts a = filter (`isSubAccountNameOf` a) accts++-- | Convert a list of account names to a tree (with a "root" node at the top,+-- and each node's subaccounts in sorted order), efficiently: any missing parent+-- accounts are added, then each account's direct subaccounts are looked up in a+-- map, built in one pass. (Previously, the remaining accounts were filtered at+-- each node, which was quadratic, and a noticeable cost with many accounts.)+accountNameTreeFrom :: [AccountName] -> Tree AccountName+accountNameTreeFrom accts = unfoldTree grow Nothing+ where+ -- Nothing is the root node; its children are the top-level accounts.+ grow Nothing = ("root", map Just $ M.findWithDefault [] Nothing subsbyparent)+ grow (Just a) = (a, map Just $ M.findWithDefault [] (Just a) subsbyparent)+ -- each account's direct subaccounts, in the (sorted) order of the expanded account list+ subsbyparent :: M.Map (Maybe AccountName) [AccountName]+ subsbyparent = M.map reverse $ M.fromListWith (++) [(parent a, [a]) | a <- expandAccountNames accts]+ parent a | accountNameLevel a <= 1 = Nothing+ | otherwise = Just $ parentAccountName a+ -- | Elide an account name to fit in the specified width. -- From the ledger 2.6 news:--- +-- -- @ -- What Ledger now does is that if an account name is too long, it will -- start abbreviating the first parts of the account name down to two@@ -166,59 +353,170 @@ -- ..:Af:Lu:Sn:Ca:Ch:Cash ; Abbreviated and elided! -- @ elideAccountName :: Int -> AccountName -> AccountName-elideAccountName width s = - elideLeft width $ accountNameFromComponents $ elideparts width [] $ accountNameComponents s+elideAccountName width s+ -- XXX special case for transactions register's multi-account pseudo-names+ | " (split)" `T.isSuffixOf` s =+ let+ names = T.splitOn ", " $ T.take (T.length s - 8) s+ widthpername = max 0 (width - 8 - 2 * (max 1 (length names) - 1)) `div` length names+ in+ fitText Nothing (Just width) True False $+ (<>" (split)") $+ T.intercalate ", "+ [accountNameFromComponents $ elideparts widthpername [] $ accountNameComponents s' | s' <- names]+ | otherwise =+ fitText Nothing (Just width) True False $ accountNameFromComponents $ elideparts width [] $ accountNameComponents s where- elideparts :: Int -> [String] -> [String] -> [String]- elideparts width done ss- | length (accountNameFromComponents $ done++ss) <= width = done++ss- | length ss > 1 = elideparts width (done++[take 2 $ head ss]) (tail ss)+ elideparts :: Int -> [Text] -> [Text] -> [Text]+ elideparts w done ss+ | realLength (accountNameFromComponents $ done++ss) <= w = done++ss+ | length ss > 1 = elideparts w (done++[textTakeWidth 2 $ headErr ss]) (tailErr ss) -- PARTIAL headErr, tailErr will succeed because length > 1 | otherwise = done++ss -clipAccountName :: Int -> AccountName -> AccountName-clipAccountName n = accountNameFromComponents . take n . accountNameComponents+-- | Keep only the first n components of an account name, where n+-- is a positive integer.+clipAccountNameTo :: Int -> AccountName -> AccountName+clipAccountNameTo n = accountNameFromComponents . take n . accountNameComponents --- | Convert an account name to a regular expression matching it and its subaccounts.-accountNameToAccountRegex :: String -> String-accountNameToAccountRegex "" = ""-accountNameToAccountRegex a = printf "^%s(:|$)" a+-- | Calculate the depth to which an account name should be clipped for a given+-- 'DepthSpec'.+--+-- First checking whether the account name matches any of the regular+-- expressions controlling depth. If so, clip to the depth of the most specific+-- of those matches, i.e. the one which starts matching the latest as you+-- progress up the parents of the account. Otherwise clip to the flat depth+-- provided, or return the full name if Nothing.+getAccountNameClippedDepth :: DepthSpec -> AccountName -> Maybe Int+getAccountNameClippedDepth (DepthSpec flat regexps) acctName =+ mostSpecificRegexp regexps <|> flat+ where+ -- If any regular expressions match, choose the one with the greatest+ -- specificity and clip to that depth.+ mostSpecificRegexp = fmap snd . foldr takeMax Nothing . mapMaybe matchRegexp+ where+ -- If two regexps match, take the most specific one. If there is a tie,+ -- take the last one (this aligns with the behaviour for flat depths+ -- limiting).+ takeMax (s, d) (Just (s', d')) = Just $ if s'>= s then (s', d') else (s, d)+ takeMax (s, d) Nothing = Just (s, d) --- | Convert an account name to a regular expression matching it and its subaccounts.-accountNameToAccountOnlyRegex :: String -> String-accountNameToAccountOnlyRegex "" = ""-accountNameToAccountOnlyRegex a = printf "^%s$" a+ -- If the regular expression matches the account name, store the specificity and requested depth+ matchRegexp :: (Regexp, Int) -> Maybe (Int, Int)+ matchRegexp (r, d) = if regexMatchText r acctName then Just (getSpecificity r, d) else Nothing+ -- Specificity is the smallest parent of the account which matches the regular expression+ getSpecificity r = maybe maxBound fst $ find (regexMatchText r . snd) acctParents+ acctParents = zip [1..] . initDef [] $ expandAccountName acctName --- | Convert an exact account-matching regular expression to a plain account name.-accountRegexToAccountName :: String -> String-accountRegexToAccountName = regexReplace "^\\^(.*?)\\(:\\|\\$\\)$" "\\1"+-- | Clip an account name to a given 'DepthSpec', first checking whether it+-- matches any of the regular expressions controlling depth. If so, clip to the+-- depth of the most specific of those matches, i.e. the one which starts+-- matching the latest as you progress up the parents of the account. Otherwise+-- clip to the flat depth provided, or return the full name if Nothing.+clipAccountName :: DepthSpec -> AccountName -> AccountName+clipAccountName ds a = maybe id clipAccountNameTo (getAccountNameClippedDepth ds a) a --- | Does this string look like an exact account-matching regular expression ?-isAccountRegex :: String -> Bool-isAccountRegex s = take 1 s == "^" && (take 5 $ reverse s) == ")$|:("+-- | As 'clipAccountName', but return '...' if asked to clip to depth 0.+clipOrEllipsifyAccountName :: DepthSpec -> AccountName -> AccountName+clipOrEllipsifyAccountName ds a = go (getAccountNameClippedDepth ds a)+ where+ go Nothing = a+ go (Just 0) = "..."+ go (Just n) = clipAccountNameTo n a -tests_Hledger_Data_AccountName = TestList- [- "accountNameTreeFrom" ~: do- accountNameTreeFrom ["a"] `is` Node "top" [Node "a" []]- accountNameTreeFrom ["a","b"] `is` Node "top" [Node "a" [], Node "b" []]- accountNameTreeFrom ["a","a:b"] `is` Node "top" [Node "a" [Node "a:b" []]]- accountNameTreeFrom ["a:b:c"] `is` Node "top" [Node "a" [Node "a:b" [Node "a:b:c" []]]]+-- | Escape an AccountName for use within a regular expression.+-- >>> putStr . T.unpack $ escapeName "First?!#$*?$(*) !@^#*? %)*!@#"+-- First\?!#\$\*\?\$\(\*\) !@\^#\*\? %\)\*!@#+-- >>> putStr . T.unpack $ escapeName "assets:broker:{2026-01-01, $50}"+-- assets:broker:\{2026-01-01, \$50\}+escapeName :: AccountName -> Text+escapeName = T.concatMap escapeChar+ where+ escapeChar c = if c `elem` escapedChars then T.snoc "\\" c else T.singleton c+ escapedChars = ['[', ']', '?', '+', '|', '(', ')', '*', '$', '^', '\\', '{', '}', '.'] - ,"expandAccountNames" ~:- expandAccountNames ["assets:cash","assets:checking","expenses:vacation"] `is`- ["assets","assets:cash","assets:checking","expenses","expenses:vacation"]+-- | Convert an account name to a regular expression matching it and its subaccounts.+accountNameToAccountRegex :: AccountName -> Regexp+accountNameToAccountRegex a = toRegex' $ "^" <> escapeName a <> "(:|$)" -- PARTIAL: Is this safe after escapeName? - ,"isAccountNamePrefixOf" ~: do- "assets" `isAccountNamePrefixOf` "assets" `is` False- "assets" `isAccountNamePrefixOf` "assets:bank" `is` True- "assets" `isAccountNamePrefixOf` "assets:bank:checking" `is` True- "my assets" `isAccountNamePrefixOf` "assets:bank" `is` False+-- | Convert an account name to a regular expression matching it and its subaccounts,+-- case insensitively.+accountNameToAccountRegexCI :: AccountName -> Regexp+accountNameToAccountRegexCI a = toRegexCI' $ "^" <> escapeName a <> "(:|$)" -- PARTIAL: Is this safe after escapeName? - ,"isSubAccountNameOf" ~: do- "assets" `isSubAccountNameOf` "assets" `is` False- "assets:bank" `isSubAccountNameOf` "assets" `is` True- "assets:bank:checking" `isSubAccountNameOf` "assets" `is` False- "assets:bank" `isSubAccountNameOf` "my assets" `is` False+-- | Convert an account name to a regular expression matching it but not its subaccounts.+accountNameToAccountOnlyRegex :: AccountName -> Regexp+accountNameToAccountOnlyRegex a = toRegex' $ "^" <> escapeName a <> "$" -- PARTIAL: Is this safe after escapeName? +-- | Convert an account name to a regular expression matching it but not its subaccounts,+-- case insensitively.+accountNameToAccountOnlyRegexCI :: AccountName -> Regexp+accountNameToAccountOnlyRegexCI a = toRegexCI' $ "^" <> escapeName a <> "$" -- PARTIAL: Is this safe after escapeName?++-- -- | Does this string look like an exact account-matching regular expression ?+--isAccountRegex :: String -> Bool+--isAccountRegex s = take 1 s == "^" && take 5 (reverse s) == ")$|:("++tests_AccountName = testGroup "AccountName" [+ testCase "accountNameHasEmptyPart" $ do+ map accountNameHasEmptyPart ["a", "a:b", "(a:b)", "[a]:b", "a::b", ":a", "a:", "(a:)", "[:a]", ":"]+ @?= [False, False, False, False, True, True, True, True, True, True]+ ,testCase "accountNameTreeFrom" $ do+ accountNameTreeFrom ["a"] @?= Node "root" [Node "a" []]+ accountNameTreeFrom ["a","b"] @?= Node "root" [Node "a" [], Node "b" []]+ accountNameTreeFrom ["a","a:b"] @?= Node "root" [Node "a" [Node "a:b" []]]+ accountNameTreeFrom ["a:b:c"] @?= Node "root" [Node "a" [Node "a:b" [Node "a:b:c" []]]]+ ,testCase "expandAccountNames" $ do+ expandAccountNames ["assets:cash","assets:checking","expenses:vacation"] @?=+ ["assets","assets:cash","assets:checking","expenses","expenses:vacation"]+ ,testCase "isAccountNamePrefixOf" $ do+ "assets" `isAccountNamePrefixOf` "assets" @?= False+ "assets" `isAccountNamePrefixOf` "assets:bank" @?= True+ "assets" `isAccountNamePrefixOf` "assets:bank:checking" @?= True+ "my assets" `isAccountNamePrefixOf` "assets:bank" @?= False+ ,testCase "isSubAccountNameOf" $ do+ "assets" `isSubAccountNameOf` "assets" @?= False+ "assets:bank" `isSubAccountNameOf` "assets" @?= True+ "assets:bank:checking" `isSubAccountNameOf` "assets" @?= False+ "assets:bank" `isSubAccountNameOf` "my assets" @?= False+ ,testCase "accountNameInferType" $ do+ accountNameInferType "assets" @?= Just Asset+ accountNameInferType "assets:cash" @?= Just Cash+ accountNameInferType "assets:A/R" @?= Just Asset+ accountNameInferType "liabilities" @?= Just Liability+ accountNameInferType "equity" @?= Just Equity+ accountNameInferType "equity:conversion" @?= Just Conversion+ accountNameInferType "expenses" @?= Just Expense+ accountNameInferType "revenues" @?= Just Revenue+ accountNameInferType "revenue" @?= Just Revenue+ accountNameInferType "income" @?= Just Revenue+ accountNameInferType "income:gains" @?= Just Gain+ accountNameInferType "revenue:gain" @?= Just Gain+ accountNameInferType "revenues:capital-gains" @?= Just Gain+ accountNameInferType "income:capitalgain" @?= Just Gain+ accountNameInferType "income:losses" @?= Just Gain+ accountNameInferType "revenue:capital-loss" @?= Just Gain+ accountNameInferType "income:gains:realized" @?= Just Gain+ accountNameInferType "equity:unrealised-gain" @?= Just UnrealisedGain+ accountNameInferType "equity:unrealized gains" @?= Just UnrealisedGain+ accountNameInferType "equity:unrealisedfoo" @?= Just Equity+ accountNameInferType "equity:imbalance" @?= Just Imbalance+ accountNameInferType "equity:imbalances:x" @?= Just Imbalance+ accountNameInferType "equity:imbalanced" @?= Just Equity+ ,testCase "joinAccountNames" $ do+ joinAccountNames "assets" "cash" @?= "assets:cash"+ joinAccountNames "assets:cash" "a" @?= "assets:cash:a"+ joinAccountNames "assets" "(cash)" @?= "(assets:cash)"+ joinAccountNames "assets" "[cash]" @?= "[assets:cash]"+ joinAccountNames "(assets)" "cash" @?= "(assets:cash)"+ joinAccountNames "" "assets" @?= "assets"+ joinAccountNames "assets" "" @?= "assets"+ ,testCase "concatAccountNames" $ do+ concatAccountNames ["assets", "cash"] @?= "assets:cash"+ concatAccountNames ["assets:cash", "a"] @?= "assets:cash:a"+ concatAccountNames ["assets", "(cash)"] @?= "(assets:cash)"+ concatAccountNames ["assets", "[cash]"] @?= "[assets:cash]"+ concatAccountNames ["(assets)", "cash"] @?= "(assets:cash)"+ concatAccountNames ["", "assets"] @?= ":assets"+ concatAccountNames ["assets", ""] @?= "assets:" ]
+ Hledger/Data/AccountType.hs view
@@ -0,0 +1,124 @@+{-|++Helpers for working with 'AccountType's.+Subtypes (Cash, Conversion, Gain, UnrealisedGain, Imbalance) are recognised as their parent type+where appropriate.++-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.AccountType (+ isAccountSubtypeOf,+ isAssetType,+ isLiabilityType,+ isEquityType,+ isRevenueType,+ isExpenseType,+ accountTypeName,+ parseAccountType,+ accountTypeChoices,+ LotDirection(..),+ accountTypeLotDirection,+ lotDirectionSign,+) where++import Data.List (intercalate)+import Data.Text (Text)+import Data.Text qualified as T++import Hledger.Data.Types (AccountType(..), Quantity)++-- | Check whether the first argument is a subtype of the second: either equal+-- or one of the defined subtypes.+isAccountSubtypeOf :: AccountType -> AccountType -> Bool+isAccountSubtypeOf Asset Asset = True+isAccountSubtypeOf Liability Liability = True+isAccountSubtypeOf Equity Equity = True+isAccountSubtypeOf Revenue Revenue = True+isAccountSubtypeOf Expense Expense = True+isAccountSubtypeOf Cash Cash = True+isAccountSubtypeOf Cash Asset = True+isAccountSubtypeOf Conversion Conversion = True+isAccountSubtypeOf Conversion Equity = True+isAccountSubtypeOf Gain Gain = True+isAccountSubtypeOf Gain Revenue = True+isAccountSubtypeOf UnrealisedGain UnrealisedGain = True+isAccountSubtypeOf UnrealisedGain Equity = True+isAccountSubtypeOf Imbalance Imbalance = True+isAccountSubtypeOf Imbalance Equity = True+isAccountSubtypeOf _ _ = False++-- | Is this an Asset or Cash (subtype of Asset) account type ?+isAssetType :: AccountType -> Bool+isAssetType = (`isAccountSubtypeOf` Asset)++-- | Is this a Liability account type ?+isLiabilityType :: AccountType -> Bool+isLiabilityType = (`isAccountSubtypeOf` Liability)++-- | Is this an Equity or Conversion (subtype of Equity) account type ?+isEquityType :: AccountType -> Bool+isEquityType = (`isAccountSubtypeOf` Equity)++-- | Is this a Revenue or Gain (subtype of Revenue) account type ?+isRevenueType :: AccountType -> Bool+isRevenueType = (`isAccountSubtypeOf` Revenue)++-- | Is this an Expense account type ?+isExpenseType :: AccountType -> Bool+isExpenseType = (`isAccountSubtypeOf` Expense)++-- | An account type's long-form name (its one-letter code is its 'show' value).+accountTypeName :: AccountType -> Text+accountTypeName Asset = "Asset"+accountTypeName Liability = "Liability"+accountTypeName Equity = "Equity"+accountTypeName Revenue = "Revenue"+accountTypeName Expense = "Expense"+accountTypeName Cash = "Cash"+accountTypeName Conversion = "Conversion"+accountTypeName Gain = "Gain"+accountTypeName UnrealisedGain = "UnrealisedGain"+accountTypeName Imbalance = "Imbalance"++-- | Case-insensitively parse an account type's one-letter code,+-- or if permitted, its long-form name (or another accepted spelling of that).+-- On failure, returns the unparseable text.+parseAccountType :: Bool -> Text -> Either String AccountType+parseAccountType allowlongform s =+ maybe (Left $ T.unpack s) Right $ lookup (T.toLower s) $+ [(T.toLower $ T.pack $ show t, t) | t <- [minBound..maxBound]]+ ++ if allowlongform then [(T.toLower $ accountTypeName t, t) | t <- [minBound..maxBound]] ++ otherspellings else []+ where+ otherspellings =+ ("gains", Gain) :+ [(n, UnrealisedGain) | n <- ["unrealised", "unrealised-gain", "unrealised-gains", "unrealized", "unrealizedgain", "unrealized-gain", "unrealized-gains"]]++-- | The account type codes, and if permitted their long-form names, for showing in messages.+accountTypeChoices :: Bool -> String+accountTypeChoices allowlongform = intercalate ", " $+ map show types ++ if allowlongform then map (T.unpack . accountTypeName) types else []+ where types = [minBound..maxBound] :: [AccountType]++-- | Which way lots flow in a lot-tracking account. In a Long account+-- (assets) a positive posting opens a lot and a negative one closes it; in+-- a Short account (liabilities, holding short positions) it is the reverse:+-- a negative posting opens a short lot and a positive one closes (covers) it.+data LotDirection = Long | Short+ deriving (Eq, Ord, Show)++-- | The lot direction of an account type: Long for assets (and Cash),+-- Short for liabilities, none for other types, which don't hold lots.+accountTypeLotDirection :: AccountType -> Maybe LotDirection+accountTypeLotDirection t+ | isAssetType t = Just Long+ | isLiabilityType t = Just Short+ | otherwise = Nothing++-- | The sign of a posting that opens a lot in this direction: 1 or -1.+-- Multiplying a posting quantity by this gives its lot flow: positive+-- when it opens or receives a lot, negative when it closes or sends one.+lotDirectionSign :: LotDirection -> Quantity+lotDirectionSign Long = 1+lotDirectionSign Short = -1
Hledger/Data/Amount.hs view
@@ -1,465 +1,1705 @@-{-# LANGUAGE StandaloneDeriving #-}-{-|-A simple 'Amount' is some quantity of money, shares, or anything else.-It has a (possibly null) 'Commodity' and a numeric quantity:--@- $1 - £-50- EUR 3.44 - GOOG 500- 1.5h- 90 apples- 0 -@--It may also have an assigned 'Price', representing this amount's per-unit-or total cost in a different commodity. If present, this is rendered like-so:--@- EUR 2 \@ $1.50 (unit price)- EUR 2 \@\@ $3 (total price)-@--A 'MixedAmount' is zero or more simple amounts, so can represent multiple-commodities; this is the type most often used:--@- 0- $50 + EUR 3- 16h + $13.55 + AAPL 500 + 6 oranges-@--When a mixed amount has been \"normalised\", it has no more than one amount-in each commodity and no zero amounts; or it has just a single zero amount-and no others.--Limited arithmetic with simple and mixed amounts is supported, best used-with similar amounts since it mostly ignores assigned prices and commodity-exchange rates.---}--module Hledger.Data.Amount (- -- * Amount- nullamt,- amountWithCommodity,- canonicaliseAmountCommodity,- setAmountPrecision,- -- ** arithmetic- costOfAmount,- divideAmount,- -- ** rendering- showAmount,- showAmountDebug,- showAmountWithoutPrice,- maxprecision,- maxprecisionwithpoint,- -- * MixedAmount- nullmixedamt,- missingamt,- amounts,- normaliseMixedAmount,- canonicaliseMixedAmountCommodity,- mixedAmountWithCommodity,- setMixedAmountPrecision,- -- ** arithmetic- costOfMixedAmount,- divideMixedAmount,- isNegativeMixedAmount,- isZeroMixedAmount,- isReallyZeroMixedAmountCost,- -- ** rendering- showMixedAmount,- showMixedAmountDebug,- showMixedAmountWithoutPrice,- showMixedAmountWithPrecision,- -- * misc.- tests_Hledger_Data_Amount-) where--import Data.Char (isDigit)-import Data.List-import Data.Map (findWithDefault)-import Test.HUnit-import Text.Printf-import qualified Data.Map as Map--import Hledger.Data.Types-import Hledger.Data.Commodity-import Hledger.Utils---deriving instance Show HistoricalPrice------------------------------------------------------------------------------------ Amount--instance Show Amount where show = showAmount--instance Num Amount where- abs (Amount c q p) = Amount c (abs q) p- signum (Amount c q p) = Amount c (signum q) p- fromInteger i = Amount (comm "") (fromInteger i) Nothing- negate a@Amount{quantity=q} = a{quantity=(-q)}- (+) = similarAmountsOp (+)- (-) = similarAmountsOp (-)- (*) = similarAmountsOp (*)---- | The empty simple amount.-nullamt :: Amount-nullamt = Amount unknown 0 Nothing---- | Apply a binary arithmetic operator to two amounts, ignoring and--- discarding any assigned prices, and converting the first to the--- commodity of the second in a simplistic way (1-1 exchange rate).--- The highest precision of either amount is preserved in the result.-similarAmountsOp :: (Double -> Double -> Double) -> Amount -> Amount -> Amount-similarAmountsOp op a@(Amount Commodity{precision=ap} _ _) (Amount bc@Commodity{precision=bp} bq _) =- Amount bc{precision=max ap bp} (quantity (amountWithCommodity bc a) `op` bq) Nothing---- | Convert an amount to the specified commodity, ignoring and discarding--- any assigned prices and assuming an exchange rate of 1.-amountWithCommodity :: Commodity -> Amount -> Amount-amountWithCommodity c (Amount _ q _) = Amount c q Nothing---- | Convert an amount to the commodity of its assigned price, if any. Notes:------ - price amounts must be MixedAmounts with exactly one component Amount (or there will be a runtime error)------ - price amounts should be positive, though this is not currently enforced-costOfAmount :: Amount -> Amount-costOfAmount a@(Amount _ q price) =- case price of- Nothing -> a- Just (UnitPrice (Mixed [Amount pc pq Nothing])) -> Amount pc (pq*q) Nothing- Just (TotalPrice (Mixed [Amount pc pq Nothing])) -> Amount pc (pq*signum q) Nothing- _ -> error' "costOfAmount: Malformed price encountered, programmer error"---- | Divide an amount's quantity by a constant.-divideAmount :: Amount -> Double -> Amount-divideAmount a@Amount{quantity=q} d = a{quantity=q/d}---- | Is this amount negative ? The price is ignored.-isNegativeAmount :: Amount -> Bool-isNegativeAmount Amount{quantity=q} = q < 0---- | Does this amount appear to be zero when displayed with its given precision ?-isZeroAmount :: Amount -> Bool-isZeroAmount = null . filter (`elem` "123456789") . showAmountWithoutPriceOrCommodity---- | Is this amount "really" zero, regardless of the display precision ?--- Since we are using floating point, for now just test to some high precision.-isReallyZeroAmount :: Amount -> Bool-isReallyZeroAmount = null . filter (`elem` "123456789") . printf ("%."++show zeroprecision++"f") . quantity- where zeroprecision = 8---- | Get the string representation of an amount, based on its commodity's--- display settings except using the specified precision.-showAmountWithPrecision :: Int -> Amount -> String-showAmountWithPrecision p = showAmount . setAmountPrecision p---- | Set the display precision in the amount's commodity.-setAmountPrecision :: Int -> Amount -> Amount-setAmountPrecision p a@Amount{commodity=c} = a{commodity=c{precision=p}}---- | Get the unambiguous string representation of an amount, for debugging.-showAmountDebug :: Amount -> String-showAmountDebug (Amount c q pri) = printf "Amount {commodity = %s, quantity = %s, price = %s}"- (show c) (show q) (maybe "" showPriceDebug pri)---- | Get the string representation of an amount, without any \@ price.-showAmountWithoutPrice :: Amount -> String-showAmountWithoutPrice a = showAmount a{price=Nothing}---- | Get the string representation of an amount, without any price or commodity symbol.-showAmountWithoutPriceOrCommodity :: Amount -> String-showAmountWithoutPriceOrCommodity a@Amount{commodity=c} = showAmount a{commodity=c{symbol=""}, price=Nothing}--showPrice :: Price -> String-showPrice (UnitPrice pa) = " @ " ++ showMixedAmount pa-showPrice (TotalPrice pa) = " @@ " ++ showMixedAmount pa--showPriceDebug :: Price -> String-showPriceDebug (UnitPrice pa) = " @ " ++ showMixedAmountDebug pa-showPriceDebug (TotalPrice pa) = " @@ " ++ showMixedAmountDebug pa---- | Get the string representation of an amount, based on its commodity's--- display settings. String representations equivalent to zero are--- converted to just \"0\".-showAmount :: Amount -> String-showAmount (Amount (Commodity {symbol="AUTO"}) _ _) = "" -- can appear in an error message-showAmount a@(Amount (Commodity {symbol=sym,side=side,spaced=spaced}) _ pri) =- case side of- L -> printf "%s%s%s%s" sym' space quantity' price- R -> printf "%s%s%s%s" quantity' space sym' price- where- quantity = showamountquantity a- displayingzero = null $ filter (`elem` "123456789") $ quantity- (quantity',sym') | displayingzero = ("0","")- | otherwise = (quantity,quoteCommoditySymbolIfNeeded sym)- space = if (not (null sym') && spaced) then " " else ""- price = maybe "" showPrice pri---- | Get the string representation of the number part of of an amount,--- using the display settings from its commodity.-showamountquantity :: Amount -> String-showamountquantity (Amount (Commodity {decimalpoint=d,precision=p,separator=s,separatorpositions=spos}) q _) =- punctuatenumber d s spos $ qstr- where- -- isint n = fromIntegral (round n) == n- qstr -- p == maxprecision && isint q = printf "%d" (round q::Integer)- | p == maxprecisionwithpoint = printf "%f" q- | p == maxprecision = chopdotzero $ printf "%f" q- | otherwise = printf ("%."++show p++"f") q---- | Replace a number string's decimal point with the specified character,--- and add the specified digit group separators.-punctuatenumber :: Char -> Char -> [Int] -> String -> String-punctuatenumber dec sep grps str = sign ++ reverse (addseps sep (extend grps) (reverse int)) ++ frac''- where- (sign,num) = break isDigit str- (int,frac) = break (=='.') num- frac' = dropWhile (=='.') frac- frac'' | null frac' = ""- | otherwise = dec:frac'- extend [] = []- extend gs = init gs ++ repeat (last gs)- addseps _ [] str = str- addseps sep (g:gs) str- | length str <= g = str- | otherwise = let (s,rest) = splitAt g str- in s ++ [sep] ++ addseps sep gs rest--chopdotzero str = reverse $ case reverse str of- '0':'.':s -> s- s -> s---- | For rendering: a special precision value which means show all available digits.-maxprecision :: Int-maxprecision = 999998---- | For rendering: a special precision value which forces display of a decimal point.-maxprecisionwithpoint :: Int-maxprecisionwithpoint = 999999---- | Replace an amount's commodity with the canonicalised version from--- the provided commodity map.-canonicaliseAmountCommodity :: Maybe (Map.Map String Commodity) -> Amount -> Amount-canonicaliseAmountCommodity Nothing = id-canonicaliseAmountCommodity (Just canonicalcommoditymap) = fixamount- where- -- like journalCanonicaliseAmounts- fixamount a@Amount{commodity=c} = a{commodity=fixcommodity c}- fixcommodity c@Commodity{symbol=s} = findWithDefault c s canonicalcommoditymap------------------------------------------------------------------------------------ MixedAmount--instance Show MixedAmount where show = showMixedAmount--instance Num MixedAmount where- fromInteger i = Mixed [Amount (comm "") (fromInteger i) Nothing]- negate (Mixed as) = Mixed $ map negate as- (+) (Mixed as) (Mixed bs) = normaliseMixedAmountPreservingPrice $ Mixed $ as ++ bs- (*) = error' "programming error, mixed amounts do not support multiplication"- abs = error' "programming error, mixed amounts do not support abs"- signum = error' "programming error, mixed amounts do not support signum"---- | The empty mixed amount.-nullmixedamt :: MixedAmount-nullmixedamt = Mixed []---- | A temporary value for parsed transactions which had no amount specified.-missingamt :: MixedAmount-missingamt = Mixed [Amount unknown{symbol="AUTO"} 0 Nothing]---- | Simplify a mixed amount's component amounts: combine amounts with the--- same commodity and price, remove any zero amounts, and replace an empty--- amount list with a single zero amount.-normaliseMixedAmountPreservingPrice :: MixedAmount -> MixedAmount-normaliseMixedAmountPreservingPrice (Mixed as) = Mixed as''- where- as'' = if null nonzeros then [nullamt] else nonzeros- (_,nonzeros) = partition (\a -> isReallyZeroAmount a && Mixed [a] /= missingamt) as'- as' = map sumAmountsUsingFirstPrice $ group $ sort as- sort = sortBy (\a1 a2 -> compare (sym a1,price a1) (sym a2,price a2))- group = groupBy (\a1 a2 -> sym a1 == sym a2 && price a1 == price a2)- sym = symbol . commodity---- | Simplify a mixed amount's component amounts: combine amounts with the--- same commodity, remove any zero amounts, and replace an empty amount--- list with a single zero amount. Unlike normaliseMixedAmountPreservingPrice,--- this one discards all but the first price encountered in each commodity.--- (This is used more for display than arithmetic, but seems a bit odd. XXX)-normaliseMixedAmount :: MixedAmount -> MixedAmount-normaliseMixedAmount (Mixed as) = Mixed as''- where - as'' = if null nonzeros then [nullamt] else nonzeros- (_,nonzeros) = partition (\a -> isReallyZeroAmount a && Mixed [a] /= missingamt) as'- as' = map sumAmountsUsingFirstPrice $ group $ sort as- sort = sortBy (\a1 a2 -> compare (sym a1) (sym a2))- group = groupBy (\a1 a2 -> sym a1 == sym a2)- sym = symbol . commodity--sumAmountsUsingFirstPrice [] = nullamt-sumAmountsUsingFirstPrice as = (sum as){price=price $ head as}---- | Get a mixed amount's component amounts.-amounts :: MixedAmount -> [Amount]-amounts (Mixed as) = as---- | Convert a mixed amount's component amounts to the commodity of their--- assigned price, if any.-costOfMixedAmount :: MixedAmount -> MixedAmount-costOfMixedAmount (Mixed as) = Mixed $ map costOfAmount as---- | Divide a mixed amount's quantities by a constant.-divideMixedAmount :: MixedAmount -> Double -> MixedAmount-divideMixedAmount (Mixed as) d = Mixed $ map (flip divideAmount d) as---- | Is this mixed amount negative, if it can be normalised to a single commodity ?-isNegativeMixedAmount :: MixedAmount -> Maybe Bool-isNegativeMixedAmount m = case as of [a] -> Just $ isNegativeAmount a- _ -> Nothing- where as = amounts $ normaliseMixedAmount m---- | Does this mixed amount appear to be zero when displayed with its given precision ?-isZeroMixedAmount :: MixedAmount -> Bool-isZeroMixedAmount = all isZeroAmount . amounts . normaliseMixedAmount---- | Is this mixed amount "really" zero ? See isReallyZeroAmount.-isReallyZeroMixedAmount :: MixedAmount -> Bool-isReallyZeroMixedAmount = all isReallyZeroAmount . amounts . normaliseMixedAmount---- | Is this mixed amount "really" zero, after converting to cost--- commodities where possible ?-isReallyZeroMixedAmountCost :: MixedAmount -> Bool-isReallyZeroMixedAmountCost = isReallyZeroMixedAmount . costOfMixedAmount---- -- | Convert a mixed amount to the specified commodity, assuming an exchange rate of 1.-mixedAmountWithCommodity :: Commodity -> MixedAmount -> Amount-mixedAmountWithCommodity c (Mixed as) = Amount c total Nothing- where- total = sum $ map (quantity . amountWithCommodity c) as---- -- | MixedAmount derived Eq instance in Types.hs doesn't know that we--- -- want $0 = EUR0 = 0. Yet we don't want to drag all this code over there.--- -- For now, use this when cross-commodity zero equality is important.--- mixedAmountEquals :: MixedAmount -> MixedAmount -> Bool--- mixedAmountEquals a b = amounts a' == amounts b' || (isZeroMixedAmount a' && isZeroMixedAmount b')--- where a' = normaliseMixedAmount a--- b' = normaliseMixedAmount b---- | Get the string representation of a mixed amount, showing each of--- its component amounts. NB a mixed amount can have an empty amounts--- list in which case it shows as \"\".-showMixedAmount :: MixedAmount -> String-showMixedAmount m = vConcatRightAligned $ map show $ amounts $ normaliseMixedAmount m---- | Set the display precision in the amount's commodities.-setMixedAmountPrecision :: Int -> MixedAmount -> MixedAmount-setMixedAmountPrecision p (Mixed as) = Mixed $ map (setAmountPrecision p) as---- | Get the string representation of a mixed amount, showing each of its--- component amounts with the specified precision, ignoring their--- commoditys' display precision settings.-showMixedAmountWithPrecision :: Int -> MixedAmount -> String-showMixedAmountWithPrecision p m =- vConcatRightAligned $ map (showAmountWithPrecision p) $ amounts $ normaliseMixedAmount m---- | Get an unambiguous string representation of a mixed amount for debugging.-showMixedAmountDebug :: MixedAmount -> String-showMixedAmountDebug m = printf "Mixed [%s]" as- where as = intercalate "\n " $ map showAmountDebug $ amounts $ normaliseMixedAmount m---- | Get the string representation of a mixed amount, but without--- any \@ prices.-showMixedAmountWithoutPrice :: MixedAmount -> String-showMixedAmountWithoutPrice m = concat $ intersperse "\n" $ map showfixedwidth as- where- (Mixed as) = normaliseMixedAmount $ stripPrices m- stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{price=Nothing}- width = maximum $ map (length . show) as- showfixedwidth = printf (printf "%%%ds" width) . showAmountWithoutPrice---- | Replace a mixed amount's commodity with the canonicalised version from--- the provided commodity map.-canonicaliseMixedAmountCommodity :: Maybe (Map.Map String Commodity) -> MixedAmount -> MixedAmount-canonicaliseMixedAmountCommodity canonicalcommoditymap (Mixed as) = Mixed $ map (canonicaliseAmountCommodity canonicalcommoditymap) as------------------------------------------------------------------------------------ misc--tests_Hledger_Data_Amount = TestList [-- -- Amount-- "costOfAmount" ~: do- costOfAmount (euros 1) `is` euros 1- costOfAmount (euros 2){price=Just $ UnitPrice $ Mixed [dollars 2]} `is` dollars 4- costOfAmount (euros 1){price=Just $ TotalPrice $ Mixed [dollars 2]} `is` dollars 2- costOfAmount (euros (-1)){price=Just $ TotalPrice $ Mixed [dollars 2]} `is` dollars (-2)-- ,"isZeroAmount" ~: do- assertBool "" $ isZeroAmount $ Amount unknown 0 Nothing- assertBool "" $ isZeroAmount $ dollars 0-- ,"negating amounts" ~: do- let a = dollars 1- negate a `is` a{quantity=(-1)}- let b = (dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}- negate b `is` b{quantity=(-1)}-- ,"adding amounts" ~: do- let a1 = dollars 1.23- let a2 = dollars (-1.23)- let a3 = dollars (-1.23)- (a1 + a2) `is` Amount (comm "$") 0 Nothing- (a1 + a3) `is` Amount (comm "$") 0 Nothing- (a2 + a3) `is` Amount (comm "$") (-2.46) Nothing- (a3 + a3) `is` Amount (comm "$") (-2.46) Nothing- sum [a1,a2,a3,-a3] `is` Amount (comm "$") 0 Nothing- -- highest precision is preserved- let ap1 = (dollars 1){commodity=dollar{precision=1}}- ap3 = (dollars 1){commodity=dollar{precision=3}}- (sum [ap1,ap3]) `is` ap3{quantity=2}- (sum [ap3,ap1]) `is` ap3{quantity=2}- -- adding different commodities assumes conversion rate 1- assertBool "" $ isZeroAmount (a1 - euros 1.23)-- ,"showAmount" ~: do- showAmount (dollars 0 + pounds 0) `is` "0"-- -- MixedAmount-- ,"normaliseMixedAmount" ~: do- normaliseMixedAmount (Mixed []) `is` Mixed [nullamt]- assertBool "" $ isZeroMixedAmount $ normaliseMixedAmount (Mixed [Amount {commodity=dollar, quantity=10, price=Nothing}- ,Amount {commodity=dollar, quantity=10, price=Just (TotalPrice (Mixed [Amount {commodity=euro, quantity=7, price=Nothing}]))}- ,Amount {commodity=dollar, quantity=(-10), price=Nothing}- ,Amount {commodity=dollar, quantity=(-10), price=Just (TotalPrice (Mixed [Amount {commodity=euro, quantity=7, price=Nothing}]))}- ])-- ,"adding mixed amounts" ~: do- let dollar0 = dollar{precision=0}- (sum $ map (Mixed . (\a -> [a]))- [Amount dollar 1.25 Nothing,- Amount dollar0 (-1) Nothing,- Amount dollar (-0.25) Nothing])- `is` Mixed [Amount unknown 0 Nothing]-- ,"showMixedAmount" ~: do- showMixedAmount (Mixed [dollars 1]) `is` "$1.00"- showMixedAmount (Mixed [(dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}]) `is` "$1.00 @ €2.00"- showMixedAmount (Mixed [dollars 0]) `is` "0"- showMixedAmount (Mixed []) `is` "0"- showMixedAmount missingamt `is` ""-- ,"showMixedAmountWithoutPrice" ~: do- let a = (dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}- showMixedAmountWithoutPrice (Mixed [a]) `is` "$1.00"- showMixedAmountWithoutPrice (Mixed [a, (-a)]) `is` "0"-- ]+{-|+A simple 'Amount' is some quantity of money, shares, or anything else.+It has a (possibly null) 'CommoditySymbol' and a numeric quantity:++@+ $1+ £-50+ EUR 3.44+ GOOG 500+ 1.5h+ 90 apples+ 0+@++It may also have an 'AmountCost', representing this amount's per-unit+or total cost in a different commodity. If present, this is rendered like+so:++@+ EUR 2 \@ $1.50 (unit cost)+ EUR 2 \@\@ $3 (total cost)+@++A 'MixedAmount' is zero or more simple amounts, so can represent multiple+commodities; this is the type most often used:++@+ 0+ $50 + EUR 3+ 16h + $13.55 + AAPL 500 + 6 oranges+@++A mixed amount is always \"normalised\", it has no more than one amount+in each commodity and cost. When calling 'amounts' it will have no zero+amounts, or just a single zero amount and no other amounts.++Limited arithmetic with simple and mixed amounts is supported, best used+with similar amounts since it mostly ignores costss and commodity exchange rates.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Data.Amount (+ -- * Commodity+ showCommoditySymbol,+ isNonsimpleCommodityChar,+ quoteCommoditySymbolIfNeeded,++ -- * Amount+ -- ** arithmetic+ nullamt,+ missingamt,+ num,+ usd,+ eur,+ gbp,+ per,+ hrs,+ at,+ (@@),+ amountWithCommodity,+ amountCost,+ amountCostBasis,+ amountSetCostToBasis,+ amountIsZero,+ amountLooksZero,+ amountSetQuantity,+ divideAmount,+ divideAmountAndUpdatePrecision,+ multiplyAmount,+ multiplyQuantities,+ invertAmount,+ -- ** styles+ amountstyle,+ canonicaliseAmount,+ styleAmount,+ amountSetStyles,+ amountStyleSetRounding,+ amountStylesSetRounding,+ amountUnstyled,+ commodityStylesFromAmounts,+ addAmountStyle,+ -- canonicalStyleFrom,+ getAmounts,++ -- ** rendering+ AmountFormat(..),+ defaultFmt,+ fullZeroFmt,+ noCostFmt,+ oneLineFmt,+ oneLineNoCostFmt,+ machineFmt,+ showAmount,+ showAmountWith,+ showAmountsDistinctly,+ showAmountB,+ showAmountQuantity,+ showAmountCost,+ showAmountCostB,+ showAmountCostBasis,+ showAmountCostBasisB,+ showAmountCostBasisLedger,+ showAmountCostBasisLedgerB,+ cshowAmount,+ showAmountWithZeroCommodity,+ showAmountDebug,+ showAmountWithoutCost,+ amountSetPrecision,+ amountSetPrecisionMin,+ amountSetPrecisionMax,+ withPrecision,+ amountSetFullPrecision,+ amountSetFullPrecisionUpTo,+ amountInternalPrecision,+ amountDisplayPrecision,+ defaultMaxDisplayPrecision,+ setAmountInternalPrecision,+ withInternalPrecision,+ setAmountDecimalPoint,+ withDecimalPoint,+ amountStripCost,+ + -- * MixedAmount+ nullmixedamt,+ missingmixedamt,+ isMissingMixedAmount,+ mixed,+ mixedAmount,+ maAddAmount,+ maAddAmounts,+ amounts,+ amountsRaw,+ amountsPreservingZeros,+ maCommodities,+ filterMixedAmount,+ filterMixedAmountByCommodity,+ mapMixedAmount,+ unifyMixedAmount,+ mixedAmountStripCosts,+ -- ** arithmetic+ mixedAmountCost,+ mixedAmountCostBasis,+ maNegate,+ maPlus,+ maMinus,+ maSum,+ divideMixedAmount,+ divideMixedAmountAndUpdatePrecision,+ multiplyMixedAmount,+ averageMixedAmounts,+ sumAndAverageMixedAmounts,+ isNegativeAmount,+ isNegativeMixedAmount,+ amountRoundedQuantity,+ mixedAmountIsZero,+ maIsZero,+ maIsNonZero,+ mixedAmountLooksZero,+ -- ** styles+ canonicaliseMixedAmount,+ styleMixedAmount,+ mixedAmountSetStyles,+ mixedAmountUnstyled,+ -- ** rendering+ showMixedAmount,+ showMixedAmountWith,+ showMixedAmountsDistinctly,+ showMixedAmountOneLine,+ showMixedAmountDebug,+ showMixedAmountWithoutCost,+ showMixedAmountOneLineWithoutCost,+ showMixedAmountElided,+ showMixedAmountWithZeroCommodity,+ showMixedAmountB,+ showMixedAmountLinesB,+ showMixedAmountLinesPartsB,+ showMixedAmountOneLinePartsB,+ wbToText,+ wbUnpack,+ mixedAmountSetPrecision,+ mixedAmountSetFullPrecision,+ mixedAmountSetFullPrecisionCapped,+ mixedAmountSetFullPrecisionUpTo,+ mixedAmountSetPrecisionMin,+ mixedAmountSetPrecisionMax,++ -- * misc.+ showPriceDirective,+ tests_Amount+) where++import Prelude hiding (Applicative(..))+import Control.Applicative ((<|>))+import Control.Monad (foldM)+import Data.Char (isDigit)+import Data.Decimal (DecimalRaw(..), decimalPlaces, normalizeDecimal, roundTo)+import Data.Default (Default(..))+import Data.Foldable (toList)+import Data.List (find, intercalate, intersperse, mapAccumL, partition)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List.NonEmpty (NonEmpty(..), nonEmpty)+import Data.Map.Strict qualified as M+import Data.Set qualified as S+import Data.Maybe (catMaybes, fromMaybe, isNothing)+import Data.Semigroup (Semigroup(..))+import Data.Text qualified as T+import Data.Text.Lazy.Builder qualified as TB+import Data.Word (Word8)+import Safe (headDef, lastDef, lastMay)+import System.Console.ANSI (Color(..),ColorIntensity(..))++import Test.Tasty (testGroup)+import Test.Tasty.HUnit ((@?=), assertBool, testCase)++import Hledger.Data.Dates (showDate)+import Hledger.Data.Types+import Hledger.Utils (colorB, error', numDigitsInt, numDigitsInteger)+import Hledger.Utils.Text (textQuoteIfNeeded)+import Text.WideString (WideBuilder(..), wbFromText, wbToText, wbUnpack)+import Data.Functor ((<&>))+-- import Data.Function ((&))+-- import Hledger.Utils.Debug (dbg0)+++-- A 'Commodity' is a symbol representing a currency or some other kind of+-- thing we are tracking, and some display preferences that tell how to+-- display 'Amount's of the commodity - is the symbol on the left or right,+-- are thousands separated by comma, significant decimal places and so on.++-- | Show space-containing commodity symbols quoted, as they are in a journal.+showCommoditySymbol :: T.Text -> T.Text+showCommoditySymbol = textQuoteIfNeeded++-- characters that may not be used in a non-quoted commodity symbol+isNonsimpleCommodityChar :: Char -> Bool+isNonsimpleCommodityChar c = case c of+ '-' -> True+ '+' -> True+ '.' -> True+ '@' -> True+ '*' -> True+ ';' -> True+ '\t' -> True+ '\n' -> True+ ' ' -> True+ '"' -> True+ '{' -> True+ '}' -> True+ '=' -> True+ _ -> isDigit c++quoteCommoditySymbolIfNeeded :: T.Text -> T.Text+quoteCommoditySymbolIfNeeded s+ | T.any isNonsimpleCommodityChar s = "\"" <> s <> "\""+ -- in a posting amount, (X)10 or 10 /x would be read as an amount expression (see amountexprp)+ | T.take 1 s `elem` ["(", "/"] = "\"" <> s <> "\""+ | otherwise = s++-- | Formatting options available when displaying Amounts and MixedAmounts.+-- Similar to "AmountStyle" but lower level, not attached to amounts or commodities, and can override it in some ways.+-- See also hledger manual > "Amount formatting, parseability", which speaks of human, hledger, and machine output.+data AmountFormat = AmountFormat+ { displayCommodity :: Bool -- ^ Whether to display commodity symbols.+ , displayZeroCommodity :: Bool -- ^ Whether to display commodity symbols for zero Amounts.+ , displayCommodityOrder :: Maybe [CommoditySymbol]+ -- ^ For a MixedAmount, an optional order in which to display the commodities.+ -- Also, causes 0s to be generated for any commodities which are not present+ -- (important for tabular reports).+ , displayDigitGroups :: Bool -- ^ Whether to display digit group marks (eg thousands separators)+ , displayForceDecimalMark :: Bool -- ^ Whether to add a trailing decimal mark when there are no decimal digits + -- and there are digit group marks, to disambiguate+ , displayOneLine :: Bool -- ^ Whether to display on one line.+ , displayMinWidth :: Maybe Int -- ^ Minimum width to pad to+ , displayMaxWidth :: Maybe Int -- ^ Maximum width to clip to+ , displayCost :: Bool -- ^ Whether to display Amounts' costs.+ , displayCostBasis :: Bool -- ^ Whether to display Amounts' cost basis (Ledger-style lot syntax).+ , displayColour :: Bool -- ^ Whether to ansi-colourise negative Amounts.+ , displayQuotes :: Bool -- ^ Whether to enclose complex symbols in quotes (normally true)+ , displayLedgerLotSyntax :: Bool -- ^ Whether to display cost basis using Ledger-style lot syntax ({COST} [DATE] (LABEL)) instead of hledger consolidated syntax.+ } deriving (Show)++-- | By default, display amounts using @defaultFmt@ amount display options.+instance Default AmountFormat where def = defaultFmt++-- | Display amounts without colour, and with various other defaults.+defaultFmt :: AmountFormat+defaultFmt = AmountFormat {+ displayCommodity = True+ , displayZeroCommodity = False+ , displayCommodityOrder = Nothing+ , displayDigitGroups = True+ , displayForceDecimalMark = False+ , displayOneLine = False+ , displayMinWidth = Just 0+ , displayMaxWidth = Nothing+ , displayCost = True+ , displayCostBasis = True+ , displayColour = False+ , displayQuotes = True+ , displayLedgerLotSyntax = False+ }++-- | Like defaultFmt but show zero amounts with commodity symbol and styling, like non-zero amounts.+fullZeroFmt :: AmountFormat+fullZeroFmt = defaultFmt{displayZeroCommodity=True}++-- | Like defaultFmt but don't show costs or cost basis.+noCostFmt :: AmountFormat+noCostFmt = defaultFmt{displayCost=False, displayCostBasis=False}++-- | Like defaultFmt but display all amounts on one line.+oneLineFmt :: AmountFormat+oneLineFmt = defaultFmt{displayOneLine=True}++-- | Like noCostFmt but display all amounts on one line.+oneLineNoCostFmt :: AmountFormat+oneLineNoCostFmt = noCostFmt{displayOneLine=True}++-- | A (slightly more) machine-readable amount format; like oneLineNoCostFmt but don't show digit group marks.+machineFmt :: AmountFormat+machineFmt = oneLineNoCostFmt{displayDigitGroups=False}++-------------------------------------------------------------------------------+-- Amount arithmetic++instance Num Amount where+ abs a@Amount{aquantity=q} = a{aquantity=abs q}+ signum a@Amount{aquantity=q} = a{aquantity=signum q}+ fromInteger i = nullamt{aquantity=fromInteger i}+ negate = transformAmount negate+ (+) = similarAmountsOp (+)+ (-) = similarAmountsOp (-)+ (*) = similarAmountsOp (*)++-- | The empty simple amount - a zero with no commodity symbol or cost+-- and the default amount display style.+nullamt :: Amount+nullamt = Amount{acommodity="", aquantity=0, astyle=amountstyle, acost=Nothing, acostbasis=Nothing}++-- | A special amount used as a marker, meaning+-- "no explicit amount provided here, infer it when needed".+-- It is nullamt with commodity symbol "AUTO".+missingamt :: Amount+missingamt = nullamt{acommodity="AUTO"}++-- Handy amount constructors for tests.+-- usd/eur/gbp round their argument to a whole number of pennies/cents.+-- XXX these are a bit clashy+num n = nullamt{acommodity="", aquantity=n}+hrs n = nullamt{acommodity="h", aquantity=n, astyle=amountstyle{asprecision=Precision 2, ascommodityside=R}}+usd n = nullamt{acommodity="$", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}+eur n = nullamt{acommodity="€", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}+gbp n = nullamt{acommodity="£", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}+per n = nullamt{acommodity="%", aquantity=n, astyle=amountstyle{asprecision=Precision 1, ascommodityside=R, ascommodityspaced=True}}+amt `at` costamt = amt{acost=Just $ UnitCost costamt}+amt @@ costamt = amt{acost=Just $ TotalCost costamt}++-- | Apply a binary arithmetic operator to two amounts, which should+-- be in the same commodity if non-zero (warning, this is not checked).+-- A zero result keeps the commodity of the second amount.+-- The result's display style is that of the second amount, with+-- precision set to the highest of either amount.+-- Costs are ignored and discarded.+-- Remember: the caller is responsible for ensuring both amounts have the same commodity.+similarAmountsOp :: (Quantity -> Quantity -> Quantity) -> Amount -> Amount -> Amount+similarAmountsOp op Amount{acommodity=_, aquantity=q1, astyle=AmountStyle{asprecision=p1}}+ Amount{acommodity=c2, aquantity=q2, astyle=s2@AmountStyle{asprecision=p2}} =+ -- trace ("a1:"++showAmountDebug a1) $ trace ("a2:"++showAmountDebug a2) $ traceWith (("= :"++).showAmountDebug)+ nullamt{acommodity=c2, aquantity=q1 `op` q2, astyle=s2{asprecision=max p1 p2}}+ -- c1==c2 || q1==0 || q2==0 =+ -- otherwise = error' "tried to do simple arithmetic with amounts in different commodities"++-- | Convert an amount to the specified commodity, ignoring and discarding+-- any costs and assuming an exchange rate of 1.+amountWithCommodity :: CommoditySymbol -> Amount -> Amount+amountWithCommodity c a = a{acommodity=c, acost=Nothing}++-- | Multiply two quantities. Equivalent to Decimal's (*), but much faster+-- in the usual case: that one multiplies via Rational, rounds to 255 decimal+-- places and normalises via Rational again, costing kilobytes of allocation+-- per multiplication. Here the mantissas are multiplied directly, and the+-- result normalised the same way (to the minimal exponent), whenever the+-- exponents' sum fits in a Decimal.+multiplyQuantities :: Quantity -> Quantity -> Quantity+multiplyQuantities a@(Decimal e1 m1) b@(Decimal e2 m2)+ | m1 == 0 || m2 == 0 = 0+ | e <= fromIntegral (maxBound :: Word8) = normalise (fromIntegral e) (m1 * m2)+ | otherwise = a * b+ where+ e = fromIntegral e1 + fromIntegral e2 :: Int+ -- reduce the exponent to the minimal value, like Decimal's normalizeDecimal+ normalise :: Word8 -> Integer -> Quantity+ normalise 0 m = Decimal 0 m+ normalise ex m = case m `quotRem` 10 of+ (q, 0) -> normalise (ex-1) q+ _ -> Decimal ex m++-- | Convert a amount to its total cost in another commodity,+-- using its attached cost amount if it has one. Notes:+--+-- - cost amounts must be MixedAmounts with exactly one component Amount+-- (or there will be a runtime error XXX)+--+-- - cost amounts should be positive in the Journal+-- (though this is currently not enforced)+--+amountCost :: Amount -> Amount+amountCost a@Amount{aquantity=q, acost=mp} =+ case mp of+ Nothing -> a+ Just (UnitCost p@Amount{aquantity=pq}) -> p{aquantity=multiplyQuantities pq q}+ Just (TotalCost p@Amount{aquantity=pq}) -> p{aquantity=pq}++-- | Convert an Amount to its cost basis when it has a cost basis annotation+-- with a cost (as lot postings do after lot processing), otherwise to its+-- transacted cost as amountCost does. This is what -B/--value=cost reports:+-- for a lot disposal it gives what the disposed units cost, not the proceeds.+amountCostBasis :: Amount -> Amount+amountCostBasis a@Amount{aquantity=q, acostbasis=mcb} =+ case mcb >>= cbCost of+ Just b@Amount{aquantity=bq} -> b{aquantity=multiplyQuantities bq q}+ Nothing -> amountCost a++-- | If this amount has a cost basis with a known per-unit cost, replace its+-- transacted cost with that basis cost, so that 'amountCost', and sums at+-- cost (which merge amounts by commodity and transacted cost, dropping+-- differing bases), reflect the cost basis. Other amounts are unchanged.+amountSetCostToBasis :: Amount -> Amount+amountSetCostToBasis a = case acostbasis a >>= cbCost of+ Just b -> a{acost = Just (UnitCost b)}+ Nothing -> a++-- | Strip all costs from an Amount+amountStripCost :: Amount -> Amount+amountStripCost a = a{acost=Nothing}++-- | Apply a function to an amount's quantity (and its total cost, if it has one).+transformAmount :: (Quantity -> Quantity) -> Amount -> Amount+transformAmount f a@Amount{aquantity=q,acost=p} = a{aquantity=f q, acost=f' <$> p}+ where+ f' (TotalCost a1@Amount{aquantity=pq}) = TotalCost a1{aquantity = f pq}+ f' p' = p'++-- | Divide an amount's quantity (and total cost, if any) by some number.+-- Returns the amount unchanged when the divisor is zero.+divideAmount :: Quantity -> Amount -> Amount+divideAmount 0 a = a+divideAmount n a = transformAmount (/n) a++-- | Like 'divideAmount', but sets the display precision to exactly the number+-- of significant decimal digits in the quotient (capped at+-- 'defaultMaxDisplayPrecision'), so the quotient's digits stay visible without+-- adding trailing zeros. Use this when the quotient is intended for display in+-- a journal entry (eg per-unit cost derived from a total cost); for aggregate+-- report cells, prefer 'divideAmount' to keep the report's chosen precision.+divideAmountAndUpdatePrecision :: Quantity -> Amount -> Amount+divideAmountAndUpdatePrecision 0 a = a+divideAmountAndUpdatePrecision n a = amountSetPrecision (Precision p) a'+ where+ a' = divideAmount n a+ p = min defaultMaxDisplayPrecision (amountInternalPrecision a')++-- | Multiply an amount's quantity (and its total cost, if it has one) by a constant.+multiplyAmount :: Quantity -> Amount -> Amount+multiplyAmount n = transformAmount (multiplyQuantities n)++-- | Replace an amount's quantity, resetting display precision to NaturalPrecision.+-- This is the safe way to set a new quantity that may have different decimal places+-- than the original — NaturalPrecision ensures the exact value is always displayed.+-- Commodity styles will override the precision at rendering time.+amountSetQuantity :: Quantity -> Amount -> Amount+amountSetQuantity q a = a{aquantity=q, astyle=(astyle a){asprecision=NaturalPrecision}}++-- | Invert an amount (replace its quantity q with 1/q).+-- The amount's transacted price, if any, is not changed.+-- An amount with zero quantity is left unchanged.+invertAmount :: Amount -> Amount+invertAmount a@Amount{aquantity=0} = a+invertAmount a@Amount{aquantity=q} = a{aquantity=1/q}++-- | Is this amount negative ? The cost is ignored.+isNegativeAmount :: Amount -> Bool+isNegativeAmount Amount{aquantity=q} = q < 0++-- | Round an Amount's Quantity (internally) to match its display precision. +-- If that is unset or NaturalPrecision, this does nothing.+amountRoundedQuantity :: Amount -> Quantity+amountRoundedQuantity Amount{aquantity=q, astyle=AmountStyle{asprecision=mp}} = case mp of+ NaturalPrecision -> q+ Precision p -> roundTo p q++-- | Apply a test to both an Amount and its total cost, if it has one.+testAmountAndTotalCost :: (Amount -> Bool) -> Amount -> Bool+testAmountAndTotalCost f amt = case acost amt of+ Just (TotalCost cost) -> f amt && f cost+ _ -> f amt++-- | Do this Amount and (and its total cost, if it has one) appear to be zero+-- when rendered with its display precision ?+-- The display precision should usually have a specific value here;+-- if unset, it will be treated like NaturalPrecision.+amountLooksZero :: Amount -> Bool+amountLooksZero = testAmountAndTotalCost looksZero+ where+ looksZero Amount{aquantity=Decimal e q, astyle=AmountStyle{asprecision=p}} = case p of+ Precision d -> if e > d then abs q <= 5*10^(e-d-1) else q == 0+ NaturalPrecision -> q == 0++-- | Is this Amount (and its total cost, if it has one) exactly zero, ignoring its display precision ?+amountIsZero :: Amount -> Bool+amountIsZero = testAmountAndTotalCost (\Amount{aquantity=Decimal _ q} -> q == 0)++-- | Does this amount's internal Decimal representation have the+-- maximum number of decimal places (or digits), suggesting that it probably is+-- representing an infinite decimal ?+-- (Checking the number of digits alone would miss small amounts, like 0.000277.. from 1/3600.)+amountHasMaxDigits :: Amount -> Bool+amountHasMaxDigits Amount{aquantity=q} = decimalPlaces q >= 255 || numDigitsInteger (decimalMantissa q) >= 255+-- XXX this seems not always right. Eg:+-- ghci> let n = 100 / (3.0 :: Decimal)+-- decimalPlaces n+-- 255+-- numDigitsInteger $ decimalMantissa n+-- 257+++-- | Set an amount's display precision, flipped.+withPrecision :: Amount -> AmountPrecision -> Amount+withPrecision = flip amountSetPrecision++-- | Set an amount's display precision.+amountSetPrecision :: AmountPrecision -> Amount -> Amount+amountSetPrecision p a@Amount{astyle=s} = a{astyle=s{asprecision=p}}++-- | Ensure an amount's display precision is at least the given minimum precision.+-- Always sets an explicit Precision.+amountSetPrecisionMin :: Word8 -> Amount -> Amount+amountSetPrecisionMin minp a = amountSetPrecision p a+ where p = Precision $ max minp (amountDisplayPrecision a)++-- | Ensure an amount's display precision is at most the given maximum precision.+-- Always sets an explicit Precision.+amountSetPrecisionMax :: Word8 -> Amount -> Amount+amountSetPrecisionMax maxp a = amountSetPrecision p a+ where p = Precision $ min maxp (amountDisplayPrecision a)++-- | Increase an amount's display precision, if needed, to enough decimal places+-- to show it exactly (showing all significant decimal digits, without trailing zeros).+-- If the amount's display precision is unset, it will be treated as precision 0.+amountSetFullPrecision :: Amount -> Amount+amountSetFullPrecision a = amountSetPrecision p a+ where+ p = max displayprecision naturalprecision+ displayprecision = asprecision $ astyle a+ naturalprecision = Precision $ amountInternalPrecision a+-- XXX Is that last sentence correct ?+-- max (Precision n) NaturalPrecision is NaturalPrecision.+-- Would this work instead ?+-- amountSetFullPrecision a = amountSetPrecision (Precision p) a+-- where p = max (amountDisplayPrecision a) (amountInternalPrecision a)+++-- | We often want to display "infinite decimal" amounts rounded to some readable+-- number of digits, while still displaying amounts with a large but "non infinite"+-- number of decimal digits (eg 10 or 100 or 200 digits) in full.+-- This helper is like amountSetFullPrecision, but with some refinements:+--+-- 1. A maximum display precision can be specified, setting a hard upper limit.+--+-- 2. If no limit is specified, and the internal precision is the maximum (255),+-- indicating an infinite decimal, display precision is set to a smaller default (8).+--+-- This function always sets an explicit display precision (ie, Precision n).+--+amountSetFullPrecisionUpTo :: Maybe Word8 -> Amount -> Amount+amountSetFullPrecisionUpTo mmaxp a = amountSetPrecision (Precision p) a+ where+ p = case mmaxp of+ Just maxp -> min maxp $ max disp intp+ Nothing -> if amountHasMaxDigits a then defaultMaxDisplayPrecision else max disp intp+ where+ disp = amountDisplayPrecision a+ intp = amountInternalPrecision a++-- | The fallback display precision used when showing amounts+-- representing an infinite decimal.+defaultMaxDisplayPrecision :: Word8+defaultMaxDisplayPrecision = 8++-- | How many internal decimal digits are stored for this amount ?+amountInternalPrecision :: Amount -> Word8+amountInternalPrecision = decimalPlaces . normalizeDecimal . aquantity++-- | How many decimal digits will be displayed for this amount ?+amountDisplayPrecision :: Amount -> Word8+amountDisplayPrecision a =+ case asprecision $ astyle a of+ Precision n -> n+ NaturalPrecision -> amountInternalPrecision a++-- | Set an amount's internal decimal precision as well as its display precision.+-- This rounds or pads its Decimal quantity to the specified number of decimal places.+-- Rounding is done with Data.Decimal's default roundTo function:+-- "If the value ends in 5 then it is rounded to the nearest even value (Banker's Rounding)".+setAmountInternalPrecision :: Word8 -> Amount -> Amount+setAmountInternalPrecision p a@Amount{ aquantity=q, astyle=s } = a{+ aquantity=roundTo p q+ ,astyle=s{asprecision=Precision p}+ }++-- | setAmountInternalPrecision with arguments flipped.+withInternalPrecision :: Amount -> Word8 -> Amount+withInternalPrecision = flip setAmountInternalPrecision++-- Amount display styles++-- v1+{-# DEPRECATED canonicaliseAmount "please use styleAmounts instead" #-}+canonicaliseAmount :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount+canonicaliseAmount = styleAmounts++-- v2+{-# DEPRECATED styleAmount "please use styleAmounts instead" #-}+styleAmount :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount+styleAmount = styleAmounts++-- v3+{-# DEPRECATED amountSetStyles "please use styleAmounts instead" #-}+amountSetStyles :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount+amountSetStyles = styleAmounts++-- v4+instance HasAmounts Amount where+ -- | Given some commodity display styles, find and apply the appropriate one to this amount,+ -- and its cost amount if any (and stop; we assume costs don't have costs).+ -- Display precision will be applied (or not) as specified by the style's rounding strategy,+ -- except that costs' precision is never changed (costs are often recorded inexactly,+ -- so we don't want to imply greater precision than they were recorded with).+ -- If no style is found for an amount, it is left unchanged.+ styleAmounts styles a@Amount{aquantity=qty, acommodity=comm, astyle=oldstyle, acost=mcost0} =+ a{astyle=newstyle, acost=mcost1}+ where+ newstyle = mknewstyle False qty oldstyle comm ++ mcost1 = case mcost0 of+ Nothing -> Nothing+ Just (UnitCost ca@Amount{aquantity=cq, astyle=cs, acommodity=ccomm}) -> Just $ UnitCost ca{astyle=mknewstyle True cq cs ccomm}+ Just (TotalCost ca@Amount{aquantity=cq, astyle=cs, acommodity=ccomm}) -> Just $ TotalCost ca{astyle=mknewstyle True cq cs ccomm}++ mknewstyle :: Bool -> Quantity -> AmountStyle -> CommoditySymbol -> AmountStyle+ mknewstyle iscost oldq olds com =+ case M.lookup com styles of+ Just s -> + -- dbg0 "new style" $ + amountStyleApplyWithRounding iscost oldq + (+ -- dbg0 "applying style"+ s)+ (+ -- dbg0 "old style"+ olds)+ Nothing -> olds++-- | Get an amount and its attached cost amount if any. Returns one or two amounts.+getAmounts :: Amount -> [Amount]+getAmounts a@Amount{acost} = a : case acost of+ Nothing -> []+ Just (UnitCost c) -> [c]+ Just (TotalCost c) -> [c]++-- AmountStyle helpers++-- | Replace one AmountStyle with another, but don't just replace the display precision;+-- update that in one of several ways as selected by the new style's "rounding strategy":+--+-- NoRounding - keep the precision unchanged+--+-- SoftRounding -+--+-- if either precision is NaturalPrecision, use NaturalPrecision;+--+-- if the new precision is greater than the old, use the new (adds decimal zeros);+--+-- if the new precision is less than the old, use as close to the new as we can get+-- without dropping (more) non-zero digits (drops decimal zeros).+--+-- for a cost amount, keep the precision unchanged+--+-- HardRounding -+--+-- for a posting amount, use the new precision (may truncate significant digits);+--+-- for a cost amount, keep the precision unchanged+--+-- AllRounding -+--+-- for both posting and cost amounts, do hard rounding.+--+-- Arguments:+--+-- whether this style is for a posting amount or a cost amount,+--+-- the amount's decimal quantity (for inspecting its internal representation), +--+-- the new style, +--+-- the old style.+--+amountStyleApplyWithRounding :: Bool -> Quantity -> AmountStyle -> AmountStyle -> AmountStyle+amountStyleApplyWithRounding iscost q news@AmountStyle{asprecision=newp, asrounding=newr} AmountStyle{asprecision=oldp} =+ case newr of+ NoRounding -> withprec oldp+ SoftRounding -> withprec $ if iscost then oldp else newp'+ where+ newp' = case (newp, oldp) of+ (Precision new, Precision old) ->+ if new >= old+ then Precision new+ else Precision $ max (min old internal) new+ where internal = decimalPlaces $ normalizeDecimal q+ _ -> NaturalPrecision+ HardRounding -> withprec $ if iscost then oldp else newp+ AllRounding -> news+ where+ -- reuse the new style itself when the precision is unchanged, so that amounts share it (saves memory)+ withprec p = if p == newp then news else news{asprecision=p}++-- | Set this amount style's rounding strategy when it is being applied to amounts.+amountStyleSetRounding :: Rounding -> AmountStyle -> AmountStyle+amountStyleSetRounding r as = as{asrounding=r}++-- | Set these amount styles' rounding strategy when they are being applied to amounts.+amountStylesSetRounding :: Rounding -> M.Map CommoditySymbol AmountStyle -> M.Map CommoditySymbol AmountStyle+amountStylesSetRounding r = M.map (amountStyleSetRounding r)++-- | Default amount style+amountstyle = AmountStyle L False Nothing (Just '.') (Precision 0) NoRounding++-- | Reset this amount's display style to the default.+amountUnstyled :: Amount -> Amount+amountUnstyled a = a{astyle=amountstyle}++-- | Given a list of amounts, in parse order (roughly speaking; see journalStyleInfluencingAmounts),+-- build a map from their commodity names to standard commodity+-- display formats. Can return an error message eg if inconsistent+-- number formats are found.+--+-- Though, these amounts may have come from multiple files, so we+-- shouldn't assume they use consistent number formats.+-- Currently we don't enforce that even within a single file,+-- and this function never reports an error.+commodityStylesFromAmounts :: [Amount] -> Either String (M.Map CommoditySymbol AmountStyle)+commodityStylesFromAmounts = Right . foldr addAmountStyle mempty++-- | Add an amount's style to a map of commodity styles, merging it into its+-- commodity's canonical style so far (see canonicalStyle). Amounts are added+-- in reverse order of appearance, so that the first amount's general style wins.+-- When the amount's style adds nothing new, which is the common case, the map+-- is returned unchanged.+addAmountStyle :: Amount -> M.Map CommoditySymbol AmountStyle -> M.Map CommoditySymbol AmountStyle+addAmountStyle Amount{acommodity=c, astyle=s} styles =+ case M.lookup c styles of+ Nothing -> M.insert c s styles+ Just s0 -> let s' = canonicalStyle s s0 in if s' == s0 then styles else M.insert c s' styles++-- -- | Given a list of amount styles (assumed to be from parsed amounts+-- -- in a single commodity), in parse order, choose a canonical style.+-- canonicalStyleFrom :: [AmountStyle] -> AmountStyle+-- canonicalStyleFrom = foldl' canonicalStyle amountstyle++-- TODO: should probably detect and report inconsistencies here.+-- Though, we don't have the info for a good error message, so maybe elsewhere.++-- | Given a pair of AmountStyles, choose a canonical style.+-- This is:+-- the general style of the first amount,+-- with the first digit group style seen,+-- with the maximum precision of all.+canonicalStyle :: AmountStyle -> AmountStyle -> AmountStyle+canonicalStyle a b = a{asprecision = prec, asdecimalmark = decmark, asdigitgroups = mgrps}+ where+ -- precision is maximum of all precisions+ prec = max (asprecision a) (asprecision b)+ -- identify the digit group mark (& group sizes)+ mgrps = asdigitgroups a <|> asdigitgroups b+ -- if a digit group mark was identified above, we can rely on that;+ -- make sure the decimal mark is different. If not, default to period.+ defdecmark = case mgrps of+ Just (DigitGroups '.' _) -> ','+ _ -> '.'+ -- identify the decimal mark: the first one used, or the above default,+ -- but never the same character as the digit group mark.+ -- urgh.. refactor..+ decmark = case mgrps of+ Just _ -> Just defdecmark+ Nothing -> asdecimalmark a <|> asdecimalmark b <|> Just defdecmark+++-- | Set (or clear) an amount's display decimal point.+setAmountDecimalPoint :: Maybe Char -> Amount -> Amount+setAmountDecimalPoint mc a@Amount{ astyle=s } = a{ astyle=s{asdecimalmark=mc} }++-- | Set (or clear) an amount's display decimal point, flipped.+withDecimalPoint :: Amount -> Maybe Char -> Amount+withDecimalPoint = flip setAmountDecimalPoint++-- Amount rendering++-- | Render an amount using its display style and the default amount format.+-- Zero-equivalent amounts are shown as just \"0\".+-- The special "missing" amount is shown as the empty string.+showAmount :: Amount -> String+showAmount = wbUnpack . showAmountB defaultFmt++-- | Like showAmount but uses the given amount format.+showAmountWith :: AmountFormat -> Amount -> String+showAmountWith fmt = wbUnpack . showAmountB fmt++-- | Render two similar amounts as strings using the given format, at enough+-- decimal display precision that the two strings differ. First tries each+-- at its own full (capped) precision; if the strings already differ, both+-- are returned as-is (preserving any per-amount asymmetry). Otherwise both+-- amounts' display precision is increased in lockstep until the strings+-- are distinct, capped at the larger of the two amounts' internal+-- precisions. If the amounts are equal at the Decimal level the loop+-- terminates at the cap. Useful in error messages that compare two+-- amounts which would otherwise round to identical-looking text.+showAmountsDistinctly :: AmountFormat -> Amount -> Amount -> (String, String)+showAmountsDistinctly fmt a b+ | sa0 /= sb0 = (sa0, sb0)+ | otherwise = go start+ where+ a0 = amountSetFullPrecisionUpTo Nothing $ amountSetFullPrecision a+ b0 = amountSetFullPrecisionUpTo Nothing $ amountSetFullPrecision b+ sa0 = showAmountWith fmt a0+ sb0 = showAmountWith fmt b0+ start = max (amountDisplayPrecision a0) (amountDisplayPrecision b0)+ cap = max (amountInternalPrecision a) (amountInternalPrecision b)+ render p = (showAmountWith fmt (setp p a), showAmountWith fmt (setp p b))+ setp p = amountSetPrecision (Precision p)+ go p+ | sa /= sb || p >= cap = (sa, sb)+ | otherwise = go (p + 1)+ where (sa, sb) = render p++-- | Render an amount using its display style and the given amount format, as a builder for efficiency.+-- (This can be converted to a Text with wbToText or to a String with wbUnpack).+-- The special "missing" amount is displayed as the empty string. +showAmountB :: AmountFormat -> Amount -> WideBuilder+showAmountB _ Amount{acommodity="AUTO"} = mempty+showAmountB+ afmt@AmountFormat{displayCommodity, displayZeroCommodity, displayDigitGroups+ ,displayForceDecimalMark, displayCost, displayCostBasis, displayColour, displayQuotes}+ a@Amount{astyle=style} =+ color $ case ascommodityside style of+ L -> (if displayCommodity then wbFromText comm <> space else mempty) <> quantity' <> costbasis <> cost+ R -> quantity' <> (if displayCommodity then space <> wbFromText comm else mempty) <> costbasis <> cost+ where+ color = if displayColour && isNegativeAmount a then colorB Dull Red else id+ quantity = showAmountQuantity displayForceDecimalMark $+ if displayDigitGroups then a else a{astyle=(astyle a){asdigitgroups=Nothing}}+ (quantity', comm)+ | amountLooksZero a && not displayZeroCommodity = (WideBuilder (TB.singleton '0') 1, "")+ | otherwise = (quantity, (if displayQuotes then quoteCommoditySymbolIfNeeded else id) $ acommodity a)+ space = if not (T.null comm) && ascommodityspaced style then WideBuilder (TB.singleton ' ') 1 else mempty+ cost = if displayCost then showAmountCostB afmt a else mempty+ costbasis = if displayCostBasis then+ (if displayLedgerLotSyntax afmt then showAmountCostBasisLedgerB else showAmountCostBasisB) afmt a+ else mempty++-- Show an amount's cost as @ UNITCOST or @@ TOTALCOST, plus a leading space, or "" if there's no cost.+showAmountCost :: Amount -> String+showAmountCost = wbUnpack . showAmountCostB defaultFmt++-- showAmountCost, efficient builder version.+showAmountCostB :: AmountFormat -> Amount -> WideBuilder+showAmountCostB afmt amt = case acost amt of+ Nothing -> mempty+ Just (UnitCost pa) -> WideBuilder (TB.fromString " @ ") 3 <> showAmountB afmt pa+ Just (TotalCost pa) -> WideBuilder (TB.fromString " @@ ") 4 <> showAmountB afmt (sign pa)+ where sign = if aquantity amt < 0 then negate else id++showAmountCostDebug :: Maybe AmountCost -> String+showAmountCostDebug Nothing = ""+showAmountCostDebug (Just (UnitCost pa)) = "@ " ++ showAmountDebug pa+showAmountCostDebug (Just (TotalCost pa)) = "@@ " ++ showAmountDebug pa++-- | Show an amount's cost basis as consolidated lot syntax: {DATE, "LABEL", COST}.+showAmountCostBasis :: Amount -> String+showAmountCostBasis = wbUnpack . showAmountCostBasisB defaultFmt++-- showAmountCostBasis, efficient builder version.+showAmountCostBasisB :: AmountFormat -> Amount -> WideBuilder+showAmountCostBasisB afmt amt = case acostbasis amt of+ Nothing -> mempty+ Just CostBasis{cbCost=Nothing, cbDate=Nothing, cbLabel=Nothing} ->+ WideBuilder (TB.fromString " {}") 3+ Just CostBasis{cbCost, cbDate, cbLabel} ->+ case parts of+ [] -> mempty+ _ -> WideBuilder (TB.fromString " {") 2 <> contents <> WideBuilder (TB.singleton '}') 1+ where+ parts = catMaybes+ [ fmap (wbFromText . T.pack . show) cbDate+ , fmap (\l -> wbFromText ("\"" <> l <> "\"")) cbLabel+ , fmap (showAmountB afmt) cbCost+ ]+ separator = WideBuilder (TB.fromString ", ") 2+ contents = mconcat $ intersperse separator parts++-- | Show an amount's cost basis as Ledger-style lot syntax: {LOTCOST} [LOTDATE] (LOTNOTE).+-- Kept for future --ledger-lot-syntax flag (step 3).+showAmountCostBasisLedger :: Amount -> String+showAmountCostBasisLedger = wbUnpack . showAmountCostBasisLedgerB defaultFmt++-- showAmountCostBasisLedger, efficient builder version.+showAmountCostBasisLedgerB :: AmountFormat -> Amount -> WideBuilder+showAmountCostBasisLedgerB afmt amt = case acostbasis amt of+ Nothing -> mempty+ Just CostBasis{cbCost=Nothing, cbDate=Nothing, cbLabel=Nothing} ->+ WideBuilder (TB.fromString " {}") 3+ Just CostBasis{cbCost, cbDate, cbLabel} ->+ lotdate <> lotnote <> lotcost+ where+ lotcost = case cbCost of+ Nothing -> mempty+ Just a -> WideBuilder (TB.fromString " {") 2 <> showAmountB afmt a <> WideBuilder (TB.singleton '}') 1+ lotdate = case cbDate of+ Nothing -> mempty+ Just d -> WideBuilder (TB.fromString " [") 2 <> wbFromText (T.pack $ show d) <> WideBuilder (TB.singleton ']') 1+ lotnote = case cbLabel of+ Nothing -> mempty+ Just l -> WideBuilder (TB.fromString " (") 2 <> wbFromText l <> WideBuilder (TB.singleton ')') 1++-- | Colour version. For a negative amount, adds ANSI codes to change the colour,+-- currently to hard-coded red.+--+-- > cshowAmount = wbUnpack . showAmountB def{displayColour=True}+cshowAmount :: Amount -> String+cshowAmount = wbUnpack . showAmountB def{displayColour=True}++-- | Get the string representation of an amount, without any \@ cost.+--+-- > showAmountWithoutCost = wbUnpack . showAmountB noCostFmt+showAmountWithoutCost :: Amount -> String+showAmountWithoutCost = wbUnpack . showAmountB noCostFmt++-- | Like showAmount, but show a zero amount's commodity if it has one.+--+-- > showAmountWithZeroCommodity = wbUnpack . showAmountB defaultFmt{displayZeryCommodity=True}+showAmountWithZeroCommodity :: Amount -> String+showAmountWithZeroCommodity = wbUnpack . showAmountB defaultFmt{displayZeroCommodity=True}++-- | Get a string representation of an amount for debugging,+-- appropriate to the current debug level. 9 shows maximum detail.+showAmountDebug :: Amount -> String+showAmountDebug Amount{acommodity="AUTO"} = "(missing)"+showAmountDebug Amount{..} =+ "Amount {acommodity=" ++ show acommodity ++ ", aquantity=" ++ show aquantity+ ++ ", acost=" ++ showAmountCostDebug acost ++ ", astyle=" ++ show astyle ++ "}"++-- | Get a Text Builder for the string representation of the number part of of an amount,+-- using the display settings from its commodity. Also returns the width of the number.+-- With a true first argument, if there are no decimal digits but there are digit group separators,+-- it shows the amount with a trailing decimal mark to help disambiguate it for parsing.+showAmountQuantity :: Bool -> Amount -> WideBuilder+showAmountQuantity disambiguate amt@Amount{astyle=AmountStyle{asdecimalmark=mdec, asdigitgroups=mgrps}} =+ signB <> intB <> fracB+ where+ Decimal decplaces mantissa = amountRoundedQuantity amt+ numtxt = T.pack . show $ abs mantissa+ numlen = T.length numtxt+ intLen = max 1 $ numlen - fromIntegral decplaces+ dec = fromMaybe '.' mdec+ numtxtwithzero = T.replicate (fromIntegral decplaces + 1 - numlen) "0" <> numtxt+ (intPart, fracPart) = T.splitAt intLen numtxtwithzero+ intB = applyDigitGroupStyle mgrps intLen $ if decplaces == 0 then numtxt else intPart+ signB = if mantissa < 0 then WideBuilder (TB.singleton '-') 1 else mempty+ fracB = if decplaces > 0 || (isshowingdigitgroupseparator && disambiguate)+ then WideBuilder (TB.singleton dec <> TB.fromText fracPart) (1 + fromIntegral decplaces)+ else mempty+ where+ isshowingdigitgroupseparator = case mgrps of+ Just (DigitGroups _ (rightmostgrplen:_)) -> intLen > fromIntegral rightmostgrplen+ _ -> False++-- | Given an integer as text, and its length, apply the given DigitGroupStyle,+-- inserting digit group separators between digit groups where appropriate.+-- Returns a Text builder and the number of digit group separators used.+applyDigitGroupStyle :: Maybe DigitGroupStyle -> Int -> T.Text -> WideBuilder+applyDigitGroupStyle Nothing l s = WideBuilder (TB.fromText s) l+applyDigitGroupStyle (Just (DigitGroups _ [])) l s = WideBuilder (TB.fromText s) l+applyDigitGroupStyle (Just (DigitGroups c (g0:gs0))) l0 s0 = addseps (g0:|gs0) (toInteger l0) s0+ where+ addseps (g1:|gs1) l1 s1+ | l2 > 0 = addseps gs2 l2 rest <> WideBuilder (TB.singleton c <> TB.fromText part) (fromIntegral g1 + 1)+ | otherwise = WideBuilder (TB.fromText s1) (fromInteger l1)+ where+ (rest, part) = T.splitAt (fromInteger l2) s1+ gs2 = fromMaybe (g1:|[]) $ nonEmpty gs1+ l2 = l1 - toInteger g1++-------------------------------------------------------------------------------+-- MixedAmount++instance Semigroup MixedAmount where+ (<>) = maPlus+ sconcat = maSum+ stimes n = multiplyMixedAmount (fromIntegral n)++instance Monoid MixedAmount where+ mempty = nullmixedamt+ mconcat = maSum++instance Num MixedAmount where+ fromInteger = mixedAmount . fromInteger+ negate = maNegate+ (+) = maPlus+ (*) = error' "error, mixed amounts do not support multiplication" -- PARTIAL:+ abs = mapMixedAmount (\amt -> amt { aquantity = abs (aquantity amt)})+ signum = error' "error, mixed amounts do not support signum"++-- | The empty mixed amount.+nullmixedamt :: MixedAmount+nullmixedamt = Mixed mempty++-- | A special mixed amount used as a marker, meaning+-- "no explicit amount provided here, infer it when needed".+missingmixedamt :: MixedAmount+missingmixedamt = mixedAmount missingamt++-- | Does this MixedAmount include the "missing amount" marker ?+-- Note: currently does not test for equality with missingmixedamt,+-- instead it looks for missingamt among the Amounts.+-- missingamt should always be alone, but detect it even if not.+isMissingMixedAmount :: MixedAmount -> Bool+isMissingMixedAmount (Mixed ma) = mixedAmountKey missingamt `M.member` ma++-- | Convert amounts in various commodities into a mixed amount.+mixed :: Foldable t => t Amount -> MixedAmount+mixed = maAddAmounts nullmixedamt++-- | Create a MixedAmount from a single Amount.+mixedAmount :: Amount -> MixedAmount+mixedAmount a = Mixed $ M.singleton (mixedAmountKey a) a++-- | Negate mixed amount's quantities (and total costs, if any).+maNegate :: MixedAmount -> MixedAmount+maNegate = transformMixedAmount negate++-- | Sum two MixedAmounts. (Any cost basis on the amounts will be lost.)+maPlus :: MixedAmount -> MixedAmount -> MixedAmount+maPlus (Mixed as) (Mixed bs) = Mixed $ M.unionWith sumSimilarAmounts as bs++-- | Subtract a MixedAmount from another. (Any cost basis on the amounts will be lost.)+maMinus :: MixedAmount -> MixedAmount -> MixedAmount+maMinus a = maPlus a . maNegate++-- | Sum a collection of MixedAmounts. (Any cost basis on the amounts will be lost.)+maSum :: (Foldable t) => t MixedAmount -> MixedAmount+maSum = foldl' maPlus nullmixedamt++-- | Add an Amount to a MixedAmount, and then normalise that.+-- (Any cost basis on the amounts will be lost.)+maAddAmount :: MixedAmount -> Amount -> MixedAmount+maAddAmount (Mixed ma) a = Mixed $ M.insertWith sumSimilarAmounts (mixedAmountKey a) a ma++-- | Add a collection of Amounts to a MixedAmount, and then normalise that.+-- (Any cost basis on the amounts will be lost.)+maAddAmounts :: (Foldable t) => MixedAmount -> t Amount -> MixedAmount+maAddAmounts = foldl' maAddAmount++-- | Divide a mixed amount's quantities (and total costs, if any) by a constant.+-- Returns the mixed amount unchanged when the divisor is zero.+divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount+divideMixedAmount 0 ma = ma+divideMixedAmount n ma = transformMixedAmount (/n) ma++-- | Like 'divideMixedAmount', but sets each component amount's display+-- precision to exactly the number of significant decimal digits in the+-- quotient (capped at 'defaultMaxDisplayPrecision'), so the quotient's+-- digits stay visible without adding trailing zeros. Use this when the+-- quotient is intended for display in a journal entry; for aggregate+-- report cells, prefer 'divideMixedAmount'.+divideMixedAmountAndUpdatePrecision :: Quantity -> MixedAmount -> MixedAmount+divideMixedAmountAndUpdatePrecision 0 ma = ma+divideMixedAmountAndUpdatePrecision n ma =+ mapMixedAmountUnsafe (divideAmountAndUpdatePrecision n) ma++-- | Multiply a mixed amount's quantities (and total costs, if any) by a constant.+multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount+multiplyMixedAmount n = transformMixedAmount (multiplyQuantities n)++-- | Apply a function to a mixed amount's quantities (and its total costs, if it has any).+transformMixedAmount :: (Quantity -> Quantity) -> MixedAmount -> MixedAmount+transformMixedAmount f = mapMixedAmountUnsafe (transformAmount f)++-- | Calculate the average of some mixed amounts.+averageMixedAmounts :: Foldable f => f MixedAmount -> MixedAmount+averageMixedAmounts = snd . sumAndAverageMixedAmounts++-- | Calculate the sum and average of some mixed amounts.+sumAndAverageMixedAmounts :: Foldable f => f MixedAmount -> (MixedAmount, MixedAmount)+sumAndAverageMixedAmounts amts = (total, fromIntegral nAmts `divideMixedAmount` total)+ where+ (nAmts, total) = foldl' (\(n, a) b -> (n + 1, maPlus a b)) (0 :: Int, nullmixedamt) amts++-- | Is this mixed amount negative, if we can tell that unambiguously?+-- Ie when normalised, are all individual commodity amounts negative ?+isNegativeMixedAmount :: MixedAmount -> Maybe Bool+isNegativeMixedAmount m =+ case amounts $ mixedAmountStripCosts m of+ [] -> Just False+ [a] -> Just $ isNegativeAmount a+ as | all isNegativeAmount as -> Just True+ as | not (any isNegativeAmount as) -> Just False+ _ -> Nothing -- multiple amounts with different signs++-- | Does this mixed amount appear to be zero when rendered with its display precision?+-- See amountLooksZero.+mixedAmountLooksZero :: MixedAmount -> Bool+mixedAmountLooksZero (Mixed ma) = all amountLooksZero ma++-- | Is this mixed amount exactly zero, ignoring its display precision?+-- See amountIsZero.+mixedAmountIsZero :: MixedAmount -> Bool+mixedAmountIsZero (Mixed ma) = all amountIsZero ma++-- | Is this mixed amount exactly zero, ignoring its display precision?+--+-- A convenient alias for mixedAmountIsZero.+maIsZero :: MixedAmount -> Bool+maIsZero = mixedAmountIsZero++-- | Is this mixed amount non-zero, ignoring its display precision?+--+-- A convenient alias for not . mixedAmountIsZero.+maIsNonZero :: MixedAmount -> Bool+maIsNonZero = not . mixedAmountIsZero++-- | Get a mixed amount's component amounts, with some cleanups.+-- The following descriptions are old and possibly wrong:+--+-- * amounts in the same commodity are combined unless they have different costs or total costs+--+-- * multiple zero amounts, all with the same non-null commodity, are replaced by just the last of them, preserving the commodity and amount style (all but the last zero amount are discarded)+--+-- * multiple zero amounts with multiple commodities, or no commodities, are replaced by one commodity-less zero amount+--+-- * an empty amount list is replaced by one commodity-less zero amount+--+-- * the special "missing" mixed amount remains unchanged+--+amounts :: MixedAmount -> [Amount]+amounts (Mixed ma)+ | isMissingMixedAmount (Mixed ma) = [missingamt]+ | M.null nonzeros = [newzero]+ | otherwise = toList nonzeros+ where+ newzero = fromMaybe nullamt $ find (not . T.null . acommodity) zeros+ (zeros, nonzeros) = M.partition amountIsZero ma++-- | Get a mixed amount's component amounts, with some cleanups.+-- This is a new version of @amounts@, with updated descriptions+-- and optimised for @print@ to show commodityful zeros.+--+-- * If it contains the "missing amount" marker, only that is returned+-- (discarding any additional amounts).+--+-- * Or if it contains any non-zero amounts, only those are returned+-- (discarding any zeroes).+--+-- * Or if it contains any zero amounts (possibly more than one,+-- possibly in different commodities), all of those are returned.+--+-- * Otherwise the null amount is returned.+--+amountsPreservingZeros :: MixedAmount -> [Amount]+amountsPreservingZeros (Mixed ma)+ | isMissingMixedAmount (Mixed ma) = [missingamt]+ | not $ M.null nonzeros = toList nonzeros+ | not $ M.null zeros = toList zeros+ | otherwise = [nullamt]+ where+ (zeros, nonzeros) = M.partition amountIsZero ma++-- | Get a mixed amount's component amounts without normalising zero and missing+-- amounts. This is used for JSON serialisation, so the order is important. In+-- particular, we want the Amounts given in the order of the MixedAmountKeys,+-- i.e. sorted by commodity and transacted cost.+amountsRaw :: MixedAmount -> [Amount]+amountsRaw (Mixed ma) = toList ma++-- | Get this mixed amount's commodities as a set.+-- Returns an empty set if there are no amounts.+maCommodities :: MixedAmount -> S.Set CommoditySymbol+maCommodities = S.fromList . fmap acommodity . amounts'+ where amounts' ma@(Mixed m) = if M.null m then [] else amounts ma++-- | Unify a MixedAmount to a single commodity value if possible.+-- This consolidates amounts of the same commodity and discards zero+-- amounts; but this one insists on simplifying to a single commodity,+-- and will return Nothing if this is not possible.+unifyMixedAmount :: MixedAmount -> Maybe Amount+unifyMixedAmount = foldM combine 0 . amounts+ where+ combine amt result+ | amountIsZero amt = Just result+ | amountIsZero result = Just amt+ | acommodity amt == acommodity result = Just $ amt + result+ | otherwise = Nothing++-- | Sum amounts which have the same MixedAmountKey; ie they have the same commodity and the same transacted cost if any.+-- If they have total transacted costs, those are also summed.+-- If they have a unit cost, that is preserved.+-- If they have a lot cost basis, that is removed.+sumSimilarAmounts :: Amount -> Amount -> Amount+sumSimilarAmounts a b = (a + b){acost=p, acostbasis=Nothing}+ where+ p = case (acost a, acost b) of+ (Just (TotalCost ap), Just (TotalCost bp))+ -> Just . TotalCost $ ap{aquantity = aquantity ap + aquantity bp }+ _ -> acost a++-- | Filter a mixed amount's component amounts by a predicate.+filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount+filterMixedAmount p (Mixed ma) = Mixed $ M.filter p ma++-- | Return a MixedAmount containing just the amount of the requested commodity+-- that was in the original mixed amount (or zero if there was none).+filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount+filterMixedAmountByCommodity c (Mixed ma)+ | M.null ma' = mixedAmount nullamt{acommodity=c}+ | otherwise = Mixed ma'+ where ma' = M.filter ((c==) . acommodity) ma++-- | Apply a transform to a mixed amount's component 'Amount's.+mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount+mapMixedAmount f (Mixed ma) = mixed . map f $ toList ma++-- | Apply a transform to a mixed amount's component 'Amount's, which does not+-- affect the key of the amount (i.e. doesn't change the commodity or transacted cost).+-- This condition is not checked.+mapMixedAmountUnsafe :: (Amount -> Amount) -> MixedAmount -> MixedAmount+mapMixedAmountUnsafe f (Mixed ma) = Mixed $ M.map f ma -- Use M.map instead of fmap to maintain strictness++-- | Convert all component amounts to cost where possible (see amountCost).+mixedAmountCost :: MixedAmount -> MixedAmount+mixedAmountCost ma0@(Mixed ma)+ | all (isNothing . acost) ma = ma0 -- no costs (the usual case), nothing to convert+ | otherwise = foldl' (\m a -> maAddAmount m (amountCost a)) (Mixed noCosts) withCosts+ where (noCosts, withCosts) = M.partition (isNothing . acost) ma++-- | Convert all component amounts to cost basis (or else transacted cost)+-- where possible (see amountCostBasis).+mixedAmountCostBasis :: MixedAmount -> MixedAmount+mixedAmountCostBasis (Mixed ma) =+ foldl' (\m a -> maAddAmount m (amountCostBasis a)) (Mixed noCosts) withCosts+ where (noCosts, withCosts) = M.partition (\a -> isNothing (acost a) && isNothing (acostbasis a >>= cbCost)) ma++-- -- | MixedAmount derived Eq instance in Types.hs doesn't know that we+-- -- want $0 = EUR0 = 0. Yet we don't want to drag all this code over there.+-- -- For now, use this when cross-commodity zero equality is important.+-- mixedAmountEquals :: MixedAmount -> MixedAmount -> Bool+-- mixedAmountEquals a b = amounts a' == amounts b' || (mixedAmountLooksZero a' && mixedAmountLooksZero b')+-- where a' = mixedAmountStripCosts a+-- b' = mixedAmountStripCosts b++-- Mixed amount styles++-- v1+{-# DEPRECATED canonicaliseMixedAmount "please use mixedAmountSetStyle False (or styleAmounts) instead" #-}+canonicaliseMixedAmount :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount+canonicaliseMixedAmount = styleAmounts++-- v2+{-# DEPRECATED styleMixedAmount "please use styleAmounts instead" #-}+-- | Given a map of standard commodity display styles, find and apply+-- the appropriate style to each individual amount.+styleMixedAmount :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount+styleMixedAmount = styleAmounts++-- v3+{-# DEPRECATED mixedAmountSetStyles "please use styleAmounts instead" #-}+mixedAmountSetStyles :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount+mixedAmountSetStyles = styleAmounts++-- v4+instance HasAmounts MixedAmount where+ styleAmounts styles = mapMixedAmountUnsafe (styleAmounts styles)+ -- getAmounts = concatMap getAmounts . amounts++instance HasAmounts BalanceData where+ styleAmounts styles balance@BalanceData{bdexcludingsubs,bdincludingsubs} =+ balance{bdexcludingsubs=styleAmounts styles bdexcludingsubs, bdincludingsubs=styleAmounts styles bdincludingsubs}+ -- getAmounts BalanceData{bdexcludingsubs, bdincludingsubs} =+ -- getAmounts bdexcludingsubs <> getAmounts bdincludingsubs++instance HasAmounts a => HasAmounts (PeriodData a) where+ styleAmounts styles = fmap (styleAmounts styles)+ -- getAmounts ++instance HasAmounts a => HasAmounts (Account a) where+ styleAmounts styles acct@Account{adata} =+ acct{adata = styleAmounts styles <$> adata}++-- | Reset each individual amount's display style to the default.+mixedAmountUnstyled :: MixedAmount -> MixedAmount+mixedAmountUnstyled = mapMixedAmountUnsafe amountUnstyled++-- Mixed amount rendering+++-- | Render a mixed amount using its amount display styles and the default amount format,+-- after normalising it (to at most one amount in each of its commodities).+-- See showMixedAmountB for special cases.+showMixedAmount :: MixedAmount -> String+showMixedAmount = wbUnpack . showMixedAmountB defaultFmt++-- | Like showMixedAmount but uses the given amount format.+-- See showMixedAmountB for special cases.+showMixedAmountWith :: AmountFormat -> MixedAmount -> String+showMixedAmountWith fmt = wbUnpack . showMixedAmountB fmt++-- | Like 'showAmountsDistinctly' but for 'MixedAmount'. First tries each+-- at its own precision; if those strings already differ, they are returned as-is.+-- Otherwise display precision is increased uniformly (across all commodity components)+-- in lockstep until the rendered strings are distinct, capped at the larger of+-- the two amounts' internal precisions.+showMixedAmountsDistinctly :: AmountFormat -> MixedAmount -> MixedAmount -> (String, String)+showMixedAmountsDistinctly fmt a b+ | sa0 /= sb0 = (sa0, sb0)+ | otherwise = go start+ where+ a0 = mixedAmountSetFullPrecisionUpTo Nothing $ mixedAmountSetFullPrecision a+ b0 = mixedAmountSetFullPrecisionUpTo Nothing $ mixedAmountSetFullPrecision b+ sa0 = showMixedAmountWith fmt a0+ sb0 = showMixedAmountWith fmt b0+ maxprec f x = maximum (0 : map f (amountsRaw x))+ start = max (maxprec amountDisplayPrecision a0) (maxprec amountDisplayPrecision b0)+ cap = max (maxprec amountInternalPrecision a) (maxprec amountInternalPrecision b)+ render p = (showMixedAmountWith fmt (setp p a), showMixedAmountWith fmt (setp p b))+ setp p = mixedAmountSetPrecision (Precision p)+ go p+ | sa /= sb || p >= cap = (sa, sb)+ | otherwise = go (p + 1)+ where (sa, sb) = render p++-- | Get the one-line string representation of a mixed amount (also showing any costs).+-- See showMixedAmountB for special cases.+showMixedAmountOneLine :: MixedAmount -> String+showMixedAmountOneLine = wbUnpack . showMixedAmountB oneLineNoCostFmt{displayCost=True}++-- | Like showMixedAmount, but zero amounts are shown with their+-- commodity if they have one.+-- See showMixedAmountB for special cases.+showMixedAmountWithZeroCommodity :: MixedAmount -> String+showMixedAmountWithZeroCommodity = wbUnpack . showMixedAmountB defaultFmt{displayZeroCommodity=True}++-- | Get the string representation of a mixed amount, without showing any costs.+-- With a True argument, adds ANSI codes to show negative amounts in red.+-- See showMixedAmountB for special cases.+showMixedAmountWithoutCost :: Bool -> MixedAmount -> String+showMixedAmountWithoutCost c = wbUnpack . showMixedAmountB noCostFmt{displayColour=c}++-- | Get the one-line string representation of a mixed amount, but without+-- any \@ costs.+-- With a True argument, adds ANSI codes to show negative amounts in red.+-- See showMixedAmountB for special cases.+showMixedAmountOneLineWithoutCost :: Bool -> MixedAmount -> String+showMixedAmountOneLineWithoutCost c = wbUnpack . showMixedAmountB oneLineNoCostFmt{displayColour=c}++-- | Like showMixedAmountOneLineWithoutCost, but show at most the given width,+-- with an elision indicator if there are more.+-- With a True argument, adds ANSI codes to show negative amounts in red.+-- See showMixedAmountB for special cases.+showMixedAmountElided :: Int -> Bool -> MixedAmount -> String+showMixedAmountElided w c = wbUnpack . showMixedAmountB oneLineNoCostFmt{displayColour=c, displayMaxWidth=Just w}++-- | Get an unambiguous string representation of a mixed amount for debugging.+showMixedAmountDebug :: MixedAmount -> String+showMixedAmountDebug m | m == missingmixedamt = "(missing)"+ | otherwise = "Mixed [" ++ as ++ "]"+ where as = intercalate "\n " $ map showAmountDebug $ amounts m++-- | Render a mixed amount using its amount display styles and the given amount format,+-- as a builder for efficiency.+-- (This can be converted to a Text with wbToText or to a String with wbUnpack).+--+-- Warning: this (and its showMixedAmount aliases above) basically assumes amounts have no costs.+-- It can show misleading costs or not show costs which are there.+--+-- If a maximum width is given then:+--+-- - If displayed on one line, it will display as many Amounts as can+-- fit in the given width, and further Amounts will be elided. There+-- will always be at least one amount displayed, even if this will+-- exceed the requested maximum width.+--+-- - If displayed on multiple lines, any Amounts longer than the+-- maximum width will be elided.+--+-- Zero-equivalent amounts are shown as just \"0\".+--+-- The special "missing" amount is shown as the empty string (?).+--+showMixedAmountB :: AmountFormat -> MixedAmount -> WideBuilder+showMixedAmountB opts ma+ | displayOneLine opts = showMixedAmountOneLineB opts ma+ | otherwise = WideBuilder (wbBuilder . mconcat $ intersperse sep ls) width+ where+ ls = showMixedAmountLinesB opts ma+ width = headDef 0 $ map wbWidth ls+ sep = WideBuilder (TB.singleton '\n') 0++-- | Helper for showMixedAmountB (and postingAsLines, ...) to show a list of Amounts on multiple lines.+-- This returns the list of WideBuilders: one for each Amount, and padded/elided to the appropriate width.+-- This does not honour displayOneLine; all amounts will be displayed as if displayOneLine were False.+showMixedAmountLinesB :: AmountFormat -> MixedAmount -> [WideBuilder]+showMixedAmountLinesB opts ma =+ map fst $ showMixedAmountLinesPartsB opts ma++-- | Like 'showMixedAmountLinesB' but also returns+-- the amounts associated with each text builder.+showMixedAmountLinesPartsB :: AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]+showMixedAmountLinesPartsB opts@AmountFormat{displayMaxWidth=mmax,displayMinWidth=mmin} ma =+ zip (map (adBuilder . pad) elided) amts+ where+ astrs = amtDisplayList (wbWidth sep) (showAmountB opts) amts+ amts = orderedAmounts opts $+ if displayCost opts then ma else mixedAmountStripCosts ma+ sep = WideBuilder (TB.singleton '\n') 0+ width = maximum $ map (wbWidth . adBuilder) elided++ pad amt+ | Just mw <- mmin =+ let w = (max width mw) - wbWidth (adBuilder amt)+ in amt{ adBuilder = WideBuilder (TB.fromText $ T.replicate w " ") w <> adBuilder amt }+ | otherwise = amt++ elided = maybe id elideTo mmax astrs+ elideTo m xs = maybeAppend elisionStr short+ where+ elisionStr = elisionDisplay (Just m) (wbWidth sep) (length long) $ lastDef nullAmountDisplay short+ (short, long) = partition ((m>=) . wbWidth . adBuilder) xs++-- | Like 'showMixedAmountOneLineB' but returns the individual amounts as separate+-- builders, along with their amounts, and without any padding or eliding+-- (displayMinWidth and displayMaxWidth are ignored).+-- Used eg for HTML output, where each amount gets its own styled element.+showMixedAmountOneLinePartsB :: AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]+showMixedAmountOneLinePartsB opts ma =+ [ (showAmountB opts a, a)+ | a <- orderedAmounts opts $ if displayCost opts then ma else mixedAmountStripCosts ma ]++-- | Helper for showMixedAmountB to deal with single line displays. This does not+-- honour displayOneLine: all amounts will be displayed as if displayOneLine+-- were True.+showMixedAmountOneLineB :: AmountFormat -> MixedAmount -> WideBuilder+showMixedAmountOneLineB opts@AmountFormat{displayMaxWidth=mmax,displayMinWidth=mmin} ma =+ WideBuilder (wbBuilder . pad . mconcat . intersperse sep $ map adBuilder elided)+ . max width $ fromMaybe 0 mmin+ where+ width = maybe 0 adTotal $ lastMay elided+ astrs = amtDisplayList (wbWidth sep) (showAmountB opts) . orderedAmounts opts $+ if displayCost opts then ma else mixedAmountStripCosts ma+ sep = WideBuilder (TB.fromString ", ") 2+ n = length astrs++ pad = (WideBuilder (TB.fromText $ T.replicate w " ") w <>)+ where w = fromMaybe 0 mmin - width++ elided = maybe id elideTo mmax astrs+ elideTo m = addElide . takeFitting m . withElided+ -- Add the last elision string to the end of the display list+ addElide [] = []+ addElide xs = maybeAppend (snd $ last xs) $ map fst xs+ -- Return the elements of the display list which fit within the maximum width+ -- (including their elision strings). Always display at least one amount,+ -- regardless of width.+ takeFitting _ [] = []+ takeFitting m (x:xs) = x : dropWhileRev (\(a,e) -> m < adTotal (fromMaybe a e)) xs+ dropWhileRev p = foldr (\x xs -> if null xs && p x then [] else x:xs) []++ -- Add the elision strings (if any) to each amount+ withElided = zipWith (\n2 amt -> (amt, elisionDisplay Nothing (wbWidth sep) n2 amt)) [n-1,n-2..0]++-- Get a mixed amount's component amounts with a bit of cleanup,+-- optionally preserving multiple zeros in different commodities,+-- optionally sorting them according to a commodity display order.+orderedAmounts :: AmountFormat -> MixedAmount -> [Amount]+orderedAmounts AmountFormat{displayZeroCommodity=preservezeros, displayCommodityOrder=mcommodityorder} =+ if preservezeros then amountsPreservingZeros else amounts+ <&> maybe id (mapM findfirst) mcommodityorder -- maybe sort them (somehow..)+ where+ -- Find the first amount with the given commodity, otherwise a null amount in that commodity.+ findfirst :: CommoditySymbol -> [Amount] -> Amount+ findfirst c = fromMaybe nullamtc . find ((c==) . acommodity)+ where+ nullamtc = amountWithCommodity c nullamt++data AmountDisplay = AmountDisplay+ { adBuilder :: !WideBuilder -- ^ String representation of the Amount+ , adTotal :: !Int -- ^ Cumulative length of MixedAmount this Amount is part of,+ -- including separators+ } deriving (Show)++nullAmountDisplay :: AmountDisplay+nullAmountDisplay = AmountDisplay mempty 0++amtDisplayList :: Int -> (Amount -> WideBuilder) -> [Amount] -> [AmountDisplay]+amtDisplayList sep showamt = snd . mapAccumL display (-sep)+ where+ display tot amt = (tot', AmountDisplay str tot')+ where+ str = showamt amt+ tot' = tot + (wbWidth str) + sep++-- The string "m more", added to the previous running total+elisionDisplay :: Maybe Int -> Int -> Int -> AmountDisplay -> Maybe AmountDisplay+elisionDisplay mmax sep n lastAmt+ | n > 0 = Just $ AmountDisplay (WideBuilder (TB.fromText str) len) (adTotal lastAmt + len)+ | otherwise = Nothing+ where+ fullString = T.pack $ show n ++ " more.."+ -- sep from the separator, 7 from " more..", numDigits n from number+ fullLength = sep + 7 + numDigitsInt n++ str | Just m <- mmax, fullLength > m = T.take (m - 2) fullString <> ".."+ | otherwise = fullString+ len = case mmax of Nothing -> fullLength+ Just m -> max 2 $ min m fullLength++maybeAppend :: Maybe a -> [a] -> [a]+maybeAppend Nothing = id+maybeAppend (Just a) = (++[a])++-- | Set the display precision in the amount's commodities.+mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount+mixedAmountSetPrecision p = mapMixedAmountUnsafe (amountSetPrecision p)++-- | In each component amount, increase the display precision sufficiently+-- to render it exactly (showing all significant decimal digits).+mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount+mixedAmountSetFullPrecision = mapMixedAmountUnsafe amountSetFullPrecision++-- | Like mixedAmountSetFullPrecision, except that an amount with a repeating decimal+-- (from division, rounded at the 255th decimal place) gets 8 decimal places, not 255.+mixedAmountSetFullPrecisionCapped :: MixedAmount -> MixedAmount+mixedAmountSetFullPrecisionCapped = mapMixedAmountUnsafe $ \a ->+ if amountHasMaxDigits a then amountSetFullPrecisionUpTo Nothing a else amountSetFullPrecision a++-- | In each component amount, increase the display precision sufficiently+-- to render it exactly if possible, but not more than the given max precision,+-- and if no max precision is given and the amount has infinite decimals,+-- limit display precision to a hard-coded smaller number (8).+-- See amountSetFullPrecisionUpTo.+mixedAmountSetFullPrecisionUpTo :: Maybe Word8 -> MixedAmount -> MixedAmount+mixedAmountSetFullPrecisionUpTo mmaxp = mapMixedAmountUnsafe (amountSetFullPrecisionUpTo mmaxp)++-- | In each component amount, ensure the display precision is at least the given value.+-- Makes all amounts have an explicit Precision.+mixedAmountSetPrecisionMin :: Word8 -> MixedAmount -> MixedAmount+mixedAmountSetPrecisionMin p = mapMixedAmountUnsafe (amountSetPrecisionMin p)++-- | In each component amount, ensure the display precision is at most the given value.+-- Makes all amounts have an explicit Precision.+mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount+mixedAmountSetPrecisionMax p = mapMixedAmountUnsafe (amountSetPrecisionMax p)++-- | Remove all transacted costs and cost bases from a MixedAmount.+mixedAmountStripCosts :: MixedAmount -> MixedAmount+mixedAmountStripCosts ma0@(Mixed ma)+ | all hasNoCosts ma = ma0 -- no costs (the usual case), nothing to strip+ | otherwise = foldl' (\m a -> maAddAmount m a{acost=Nothing, acostbasis=Nothing}) (Mixed noCosts) withCosts+ where+ hasNoCosts a = isNothing (acost a) && isNothing (acostbasis a)+ (noCosts, withCosts) = M.partition hasNoCosts ma+++-- | Render a price directive in journal format ("P DATE COMMODITY AMOUNT").+-- Always shows the to-currency, even on a zero quantity, so the directive+-- round-trips back to the same conversion pair.+showPriceDirective :: PriceDirective -> T.Text+showPriceDirective pd = T.unwords+ [ "P"+ , showDate (pddate pd)+ , quoteCommoditySymbolIfNeeded (pdcommodity pd)+ , wbToText $ showAmountB defaultFmt{displayZeroCommodity=True} (pdamount pd)+ ]+++-------------------------------------------------------------------------------+-- tests++tests_Amount = testGroup "Amount" [+ testGroup "Amount" [++ testCase "amountCost" $ do+ amountCost (eur 1) @?= eur 1+ amountCost (eur 2){acost=Just $ UnitCost $ usd 2} @?= usd 4+ amountCost (eur 1){acost=Just $ TotalCost $ usd 2} @?= usd 2+ amountCost (eur (-1)){acost=Just $ TotalCost $ usd (-2)} @?= usd (-2)++ ,testCase "multiplyQuantities" $ do+ -- same result and representation as Decimal's (*)+ let same a b = (multiplyQuantities a b, decimalPlaces $ multiplyQuantities a b) @?= (a * b, decimalPlaces $ a * b)+ same 0.71 3+ same 1.50 (-2.0)+ same 0 100+ same (Decimal 200 3) (Decimal 100 5)+ multiplyQuantities 2.50 4 @?= 10++ ,testCase "amountLooksZero" $ do+ assertBool "" $ amountLooksZero nullamt+ assertBool "" $ amountLooksZero $ usd 0++ ,testCase "negating amounts" $ do+ negate (usd 1) @?= (usd 1){aquantity= -1}+ let b = (usd 1){acost=Just $ UnitCost $ eur 2} in negate b @?= b{aquantity= -1}++ ,testCase "adding amounts without costs" $ do+ (usd 1.23 + usd (-1.23)) @?= usd 0+ (usd 1.23 + usd (-1.23)) @?= usd 0+ (usd (-1.23) + usd (-1.23)) @?= usd (-2.46)+ sum [usd 1.23,usd (-1.23),usd (-1.23),-(usd (-1.23))] @?= usd 0+ -- highest precision is preserved+ asprecision (astyle $ sum [usd 1 `withPrecision` Precision 1, usd 1 `withPrecision` Precision 3]) @?= Precision 3+ asprecision (astyle $ sum [usd 1 `withPrecision` Precision 3, usd 1 `withPrecision` Precision 1]) @?= Precision 3+ -- adding different commodities assumes conversion rate 1+ assertBool "" $ amountLooksZero (usd 1.23 - eur 1.23)++ ,testCase "showAmount" $ do+ showAmount (usd 0 + gbp 0) @?= "0"++ ]++ ,testGroup "MixedAmount" [++ testCase "comparing mixed amounts compares based on quantities" $ do+ let usdpos = mixed [usd 1]+ usdneg = mixed [usd (-1)]+ eurneg = mixed [eur (-12)]+ compare usdneg usdpos @?= LT+ compare eurneg usdpos @?= LT++ ,testCase "adding mixed amounts to zero, the commodity and amount style are preserved" $+ maSum (map mixedAmount+ [usd 1.25+ ,usd (-1) `withPrecision` Precision 3+ ,usd (-0.25)+ ])+ @?= mixedAmount (usd 0 `withPrecision` Precision 3)++ ,testCase "adding mixed amounts with total costs" $ do+ maSum (map mixedAmount+ [usd 1 @@ eur 1+ ,usd (-2) @@ eur 1+ ])+ @?= mixedAmount (usd (-1) @@ eur 2)++ ,testCase "showMixedAmount" $ do+ showMixedAmount (mixedAmount (usd 1)) @?= "$1.00"+ showMixedAmount (mixedAmount (usd 1 `at` eur 2)) @?= "$1.00 @ €2.00"+ showMixedAmount (mixedAmount (usd 0)) @?= "0"+ showMixedAmount nullmixedamt @?= "0"+ showMixedAmount missingmixedamt @?= ""++ ,testCase "showMixedAmountWithoutCost" $ do+ let a = usd 1 `at` eur 2+ showMixedAmountWithoutCost False (mixedAmount (a)) @?= "$1.00"+ showMixedAmountWithoutCost False (mixed [a, -a]) @?= "0"++ ,testGroup "amounts" [+ testCase "a missing amount overrides any other amounts" $+ amounts (mixed [usd 1, missingamt]) @?= [missingamt]+ ,testCase "costless same-commodity amounts are combined" $+ amounts (mixed [usd 0, usd 2]) @?= [usd 2]+ ,testCase "amounts with same unit cost are combined" $+ amounts (mixed [usd 1 `at` eur 1, usd 1 `at` eur 1]) @?= [usd 2 `at` eur 1]+ ,testCase "amounts with different unit costs are not combined" $+ amounts (mixed [usd 1 `at` eur 1, usd 1 `at` eur 2]) @?= [usd 1 `at` eur 1, usd 1 `at` eur 2]+ ,testCase "amounts with total costs are combined" $+ amounts (mixed [usd 1 @@ eur 1, usd 1 @@ eur 1]) @?= [usd 2 @@ eur 2]+ ]++ ,testCase "mixedAmountStripCosts" $ do+ amounts (mixedAmountStripCosts nullmixedamt) @?= [nullamt]+ assertBool "" $ mixedAmountLooksZero $ mixedAmountStripCosts+ (mixed [usd 10+ ,usd 10 @@ eur 7+ ,usd (-10)+ ,usd (-10) @@ eur (-7)+ ])++ ]++ ]
+ Hledger/Data/BalanceData.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE CPP #-}+{-|+++A 'BalanceData is a data type tracking a number of postings, exclusive, and inclusive balance+for given date ranges.++-}+module Hledger.Data.BalanceData+( mapBalanceData+, opBalanceData++, tests_BalanceData+) where+++import Test.Tasty (testGroup)+import Test.Tasty.HUnit ((@?=), testCase)++import Hledger.Data.Amount+import Hledger.Data.Types+++instance Show BalanceData where+ showsPrec d (BalanceData e i n) =+ showParen (d > 10) $+ showString "BalanceData"+ . showString "{ bdexcludingsubs = " . showString (wbUnpack (showMixedAmountB defaultFmt e))+ . showString ", bdincludingsubs = " . showString (wbUnpack (showMixedAmountB defaultFmt i))+ . showString ", bdnumpostings = " . shows n+ . showChar '}'++instance Semigroup BalanceData where+ BalanceData e i n <> BalanceData e' i' n' = BalanceData (maPlus e e') (maPlus i i') (n + n')++instance Monoid BalanceData where+ mempty = BalanceData nullmixedamt nullmixedamt 0++-- | Apply an operation to both 'MixedAmount' in an 'BalanceData'.+mapBalanceData :: (MixedAmount -> MixedAmount) -> BalanceData -> BalanceData+mapBalanceData f a = a{bdexcludingsubs = f $ bdexcludingsubs a, bdincludingsubs = f $ bdincludingsubs a}++-- | Merge two 'BalanceData', using the given operation to combine their amounts.+opBalanceData :: (MixedAmount -> MixedAmount -> MixedAmount) -> BalanceData -> BalanceData -> BalanceData+opBalanceData f a b = a{bdexcludingsubs = f (bdexcludingsubs a) (bdexcludingsubs b), bdincludingsubs = f (bdincludingsubs a) (bdincludingsubs b)}+++-- tests++tests_BalanceData = testGroup "BalanceData" [++ testCase "opBalanceData maPlus" $ do+ opBalanceData maPlus (BalanceData (mixed [usd 1]) (mixed [usd 2]) 5) (BalanceData (mixed [usd 3]) (mixed [usd 4]) 0)+ @?= BalanceData (mixed [usd 4]) (mixed [usd 6]) 5,++ testCase "opBalanceData maMinus" $ do+ opBalanceData maMinus (BalanceData (mixed [usd 1]) (mixed [usd 2]) 5) (BalanceData (mixed [usd 3]) (mixed [usd 4]) 0)+ @?= BalanceData (mixed [usd (-2)]) (mixed [usd (-2)]) 5+ ]
+ Hledger/Data/Balancing.hs view
@@ -0,0 +1,1556 @@+{-|+Functions for ensuring transactions and journals are balanced.+-}++{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Data.Balancing+( -- * BalancingOpts+ BalancingOpts(..)+, HasBalancingOpts(..)+, defbalancingopts+ -- * transaction balancing+, isTransactionBalanced+, balanceSingleTransaction+, balanceTransactionHelper+, transactionBalanceError+, transactionBalancingSum+, roundedPostingTagName+, transactionRoundCalculatedAmounts+, postingRoundCalculatedAmounts+ -- * assertion validation+, transactionCheckAssertions+ -- * journal balancing+, journalBalanceTransactions+, journalBalanceTransactionsAndDeferAssertions+ -- * tests+, tests_Balancing+)+where++import Control.Applicative ((<|>))+import Control.Monad (forM, forM_, when, unless)+import Control.Monad.Except (ExceptT(..), runExceptT, throwError, catchError)+import Control.Monad.Reader as R (ReaderT, reader, runReaderT, ask, asks)+import Control.Monad.ST (ST, runST)+import Control.Monad.Trans.Class (lift)+import Data.Array.ST (STArray, getElems, newListArray, writeArray)+import Data.Bifunctor (second)+import Data.Foldable (asum)+import Data.Function ((&))+import Data.Functor ((<&>), void)+import Data.HashTable.Class qualified as H (toList)+import Data.HashTable.ST.Cuckoo qualified as H+import Data.List (partition, sortOn, intercalate)+import Data.List.Extra (nubSort)+import Data.Either (isRight)+import Data.Maybe (fromJust, fromMaybe, isJust, isNothing, mapMaybe)+import Data.STRef (STRef, newSTRef, readSTRef, modifySTRef')+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Time.Calendar (addDays, fromGregorian)+import Data.Map qualified as M+import Safe (headErr)+import Text.Printf (printf)++import Hledger.Data.Types+import Hledger.Data.AccountName (accountNameType, defaultImbalanceAccount, isAccountNamePrefixOf)+import Hledger.Data.Amount+import Hledger.Data.Journal+import Hledger.Data.Lots (isSetAsideGainPosting, lotBaseAccount, transactionAutoSplitFeeOutflows, transactionHasLotfulAmounts, transactionTagGainPostings)+import Hledger.Data.Posting+import Hledger.Data.Transaction+import Hledger.Data.Errors+import Hledger.Utils+++data BalancingOpts = BalancingOpts+ { ignore_assertions_ :: Bool -- ^ should failing balance assertions be ignored ?+ , infer_balancing_costs_ :: Bool -- ^ Are we permitted to infer missing costs to balance transactions ?+ -- Distinct from InputOpts{infer_costs_}.+ , commodity_styles_ :: Maybe (M.Map CommoditySymbol AmountStyle) -- ^ commodity display styles+ , txn_balancing_ :: TransactionBalancingPrecision+ , infer_imbalance_ :: Bool -- ^ should tolerated imbalances be shown, by adding imbalance postings to transactions ?+ , imbalance_account_ :: AccountName -- ^ the account for imbalance postings (see journalAccountForType)+ , account_types_ :: M.Map AccountName AccountType -- ^ account type map, passed through for any balancing helpers that need it+ , lotful_commodities_ :: S.Set CommoditySymbol -- ^ commodities declared lotful, used to guide balancing cost inference (when lots are enabled)+ , account_lots_tags_ :: M.Map AccountName T.Text -- ^ declared lots: tag values by account, used to detect lots: NONE opt-outs (when lots are enabled)+ , lenient_lots_ :: Bool -- ^ with --ignore-lots: relax the lot quantity mismatch veto, inferring a balancing conversion cost anyway+ , verbose_balancing_tags_ :: Bool -- ^ should tags added by balancing helpers (eg lot fee splits) also be made visible in comments ?+ } deriving (Eq, Ord, Show)++defbalancingopts :: BalancingOpts+defbalancingopts = BalancingOpts+ { ignore_assertions_ = False+ , infer_balancing_costs_ = True+ , commodity_styles_ = Nothing+ , txn_balancing_ = TBPEntry+ , infer_imbalance_ = False+ , imbalance_account_ = defaultImbalanceAccount+ , account_types_ = M.empty+ , lotful_commodities_ = S.empty+ , account_lots_tags_ = M.empty+ , lenient_lots_ = False+ , verbose_balancing_tags_ = False+ }++-- | Check that this transaction would appear balanced to a human when displayed.+-- On success, returns the empty list, otherwise one or more error messages.+--+-- In more detail:+-- For the real postings, and separately for the balanced virtual postings:+--+-- 1. Convert amounts to cost where possible+--+-- 2. When there are two or more non-zero amounts+-- (appearing non-zero when displayed, using the given display styles if provided),+-- are they a mix of positives and negatives ?+-- This is checked separately to give a clearer error message.+-- (Best effort; could be confused by postings with multicommodity amounts.)+--+-- 3. Does the amounts' sum appear non-zero when displayed ?+-- (using the given display styles if provided)+--+transactionCheckBalanced :: BalancingOpts -> Transaction -> [String]+transactionCheckBalanced BalancingOpts{commodity_styles_=_mglobalstyles, txn_balancing_, lotful_commodities_, lenient_lots_} t = errs+ where+ -- get real and balanced virtual postings, to be checked separately+ (rps, bvps) = foldr partitionPosting ([], []) $ tpostings t+ where+ partitionPosting p ~(l, r) = case preal p of+ RealPosting -> (p:l, r)+ BalancedVirtualPosting -> (l, p:r)+ VirtualPosting -> (l, r)++ postingBalancingAmount = postingBalancingAmountWith setaside++ -- An exactly zero sum (the usual case) looks zero at any precision,+ -- so the display styles are inferred and applied only for inexact sums.+ lookszero a = mixedAmountIsZero a || lookszeroatdisplayprecision a+ lookszeroatdisplayprecision = case txn_balancing_ of+ TBPDisplay -> lookszeroatglobaldisplayprecision+ TBPEntry -> lookszeroatlocaltransactionprecision++ lookszeroatlocaltransactionprecision = mixedAmountLooksZero . styleAmounts (transactionCommodityStylesWith HardRounding t)+ lookszeroatglobaldisplayprecision = mixedAmountLooksZero . maybe id styleAmounts _mglobalstyles++ -- check that the sum looks like zero+ (rsumcost, bvsumcost) = (foldMap postingBalancingAmount rps, foldMap postingBalancingAmount bvps)+ (rsumamts, bvsumamts) = (map postingBalancingAmount (nongain rps), map postingBalancingAmount (nongain bvps))+ setaside = isSetAsideGainPosting t+ nongain = filter (not . setaside)+ gainnote ps = if any setaside ps then " (excluding gain postings)" else ""+ (rsumok, bvsumok) = (lookszero rsumcost, lookszero bvsumcost)+ (rsumokold, bvsumokold) = (lookszeroatglobaldisplayprecision rsumcost, lookszeroatglobaldisplayprecision bvsumcost)++ -- when there's multiple non-zeros, check they do not all have the same sign+ (rsignsok, bvsignsok) = (signsOk rps, signsOk bvps)+ where+ signsOk ps = length nonzeros < 2 || length nonzerosigns > 1+ where+ nonzeros = filter (not.lookszero) $ map postingBalancingAmount ps+ nonzerosigns = nubSort $ mapMaybe isNegativeMixedAmount nonzeros++ -- Generate error messages if any. Show amounts with their original precisions.+ errs = filter (not.null) [rmsg, bvmsg]+ where+ showamt =+ showMixedAmountWith oneLineNoCostFmt{displayZeroCommodity=True} .+ mixedAmountSetFullPrecisionUpTo Nothing .+ mixedAmountSetFullPrecision+ rmsg+ | rsumok = ""+ | not rsignsok = "The real postings all have the same sign."+ | otherwise = "The real postings' sum should be 0 but is "+ ++ showamt rsumcost+ ++ "\n " ++ intercalate " + " (map showamt rsumamts) ++ " = " ++ showamt rsumcost ++ gainnote rps+ ++ roundedmsg rps+ ++ (if rsumokold then oldbalancingmsg else "")+ ++ lotmismatchmsg rps+ bvmsg+ | bvsumok = ""+ | not bvsignsok = "The balanced virtual postings all have the same sign."+ | otherwise = "The balanced virtual postings' sum should be 0 but is: "+ ++ showamt bvsumcost+ ++ "\n " ++ intercalate " + " (map showamt bvsumamts) ++ " = " ++ showamt bvsumcost ++ gainnote bvps+ ++ roundedmsg bvps+ ++ (if bvsumokold then oldbalancingmsg else "")+ ++ lotmismatchmsg bvps+ -- When a balancing conversion cost was not inferred because of a+ -- lot quantity mismatch (see lotMismatchCommodities), explain that,+ -- since a user unaware of lot processing might expect this entry+ -- to balance by inference.+ lotmismatchmsg ps = case map T.unpack $ lotMismatchCommodities lotful_commodities_ ps of+ [] -> ""+ cs -> unlines $ [+ "\nNote, " ++ intercalate ", " cs ++ " is a lot-tracked commodity being transferred between accounts,"+ ,"so no balancing conversion cost was inferred; its quantities are expected"+ ,"to add up. If the difference is a fee, you can either"+ ,"- record the fee expense in the lot-tracked commodity, with posting(s)"+ ," adding up to the missing quantity"+ ,"- or split the sending posting into a transfer part and fee part(s)"+ ," matching the fee expense(s)."+ ]+ ++ ["(With --ignore-lots, a balancing conversion cost is inferred instead.)" | not lenient_lots_]+ -- When some amounts were calculated with * or / in amount expressions, and changed+ -- by rounding (see roundedPostingTagName), mention that.+ roundedmsg ps+ | any (postingHasTag roundedPostingTagName) ps =+ "\nNote, amounts calculated with * or / are rounded; to split unevenly, leave one amount blank."+ | otherwise = ""+ oldbalancingmsg = unlines [+ -- -------------------------------------------------------------------------------+ "\nNote, hledger <1.50 accepted this entry because of the global display precision,"+ ,"but hledger 1.50+ checks more strictly, using the entry's local precision."+ ,"You can use --txn-tolerance=display to keep it working, or fix it (recommended);"+ ,"see 'Transaction balancing' in the hledger manual."+ ]++-- | A posting's amount as it counts towards its transaction's balance:+-- converted to cost, unless it has been marked as a redundant cost+-- (equivalent to some nearby equity conversion postings), in which case the cost is ignored;+-- or nothing, if it is a disposal's realised gain posting, which is set aside+-- (according to the given predicate, usually 'isSetAsideGainPosting' partially applied to the transaction).+-- A disposal balances at cost basis, which is equivalent to its non-gain postings balancing+-- at transacted cost (see Hledger.Data.Lots.transactionTagGainPostings;+-- not when the entry has conversion postings, see isSetAsideGainPosting).+postingBalancingAmountWith :: (Posting -> Bool) -> Posting -> MixedAmount+postingBalancingAmountWith setaside p+ | costPostingTagName `elem` map fst (ptags p) = mixedAmountStripCosts $ pamount p+ | setaside p = nullmixedamt+ | otherwise = mixedAmountCost $ pamount p++-- | The sum of all of this transaction's postings, converted to cost as when balancing it,+-- including any unbalanced virtual postings. For a balanced transaction this is zero+-- (or a tolerated imbalance; see transactionCheckBalanced) plus the unbalanced virtual postings' amounts.+-- This is the amount a sum: query tests for a transaction.+transactionBalancingSum :: Transaction -> MixedAmount+transactionBalancingSum t = foldMap (postingBalancingAmountWith setaside) $ tpostings t+ where setaside = isSetAsideGainPosting t++-- | Postings which would show this balanced transaction's remaining imbalance+-- (tolerated because it's smaller than the balancing precision; see transactionCheckBalanced),+-- making the transaction balance exactly. These are postings to the given account,+-- one for each commodity of the real postings' imbalance, and likewise (but balanced virtual)+-- for the balanced virtual postings' imbalance, or none if the transaction balances exactly.+-- They are tagged with imbalancePostingTagName and generatedPostingTagName+-- (and with a true verbosetags argument, visibly too).+-- They behave like amountless postings written by the user, whose amount was inferred:+-- their amounts have the given commodity display styles but keep their full precision,+-- and since their original posting is amountless, these don't influence commodity display precisions+-- (see isExplicitAmount).+-- Imbalances which would display as zero are ignored. These are leftovers from hledger's own division+-- (repeating decimals, rounded at the 255th decimal place), too small to show at the 8 decimal places+-- used to display repeating decimals (see amountSetFullPrecisionUpTo).+-- Imbalances calculated from written amounts and costs are finite decimals, shown in full.+transactionImbalancePostings :: Bool -> AccountName -> M.Map CommoditySymbol AmountStyle -> Transaction -> [Posting]+transactionImbalancePostings verbosetags acct styles t =+ [ imbalancePosting r a+ | r <- [RealPosting, BalancedVirtualPosting]+ , a <- amounts $ foldMap (postingBalancingAmountWith setaside) [p | p <- tpostings t, preal p == r]+ , not $ amountLooksZero $ amountSetFullPrecisionUpTo Nothing a+ ]+ where+ setaside = isSetAsideGainPosting t+ imbalancePosting r a = p{poriginal = Just p{pamount = missingmixedamt}}+ where+ p = postingAddHiddenAndMaybeVisibleTag False verbosetags (generatedPostingTagName, "")+ $ postingAddHiddenAndMaybeVisibleTag False verbosetags (imbalancePostingTagName, "")+ $ nullposting{paccount = acct, preal = r,+ pamount = styleAmounts (styles & amountStylesSetRounding NoRounding) $ mixedAmount $ negate a}++-- | With the infer_imbalance_ option, add postings showing this balanced transaction's+-- tolerated imbalance, if any (see 'transactionImbalancePostings').+-- Returns the (possibly) updated transaction, and the added postings.+transactionMaybeAddImbalancePostings :: BalancingOpts -> Transaction -> (Transaction, [Posting])+transactionMaybeAddImbalancePostings bopts t+ | not (infer_imbalance_ bopts) || null ips = (t, [])+ | otherwise = (txnTieKnot t{tpostings = tpostings t ++ ips}, ips)+ where+ ips = transactionImbalancePostings (verbose_balancing_tags_ bopts) (imbalance_account_ bopts) (fromMaybe M.empty $ commodity_styles_ bopts) t++-- | Legacy form of transactionCheckBalanced.+isTransactionBalanced :: BalancingOpts -> Transaction -> Bool+isTransactionBalanced bopts = null . transactionCheckBalanced bopts++-- | Verify that any assertions in this transaction hold +-- when included in the larger journal.+transactionCheckAssertions :: BalancingOpts -> Journal -> Transaction -> Either String Transaction+transactionCheckAssertions bopts j t =+ if (ignore_assertions_ bopts) then Right t else do+ j' <- journalStyleAmounts j + let newtxns = sortOn tdate (jtxns j' ++ [ t ])+ case journalBalanceTransactions bopts j'{jtxns = newtxns} of+ Right _ -> Right t+ Left e -> Left e++-- | Balance this isolated transaction, ensuring that its postings+-- (and its balanced virtual postings) sum to 0,+-- by inferring a missing amount or conversion price(s) if needed.+-- Or if balancing is not possible, because the amounts don't sum to 0 or+-- because there's more than one missing amount, return an error message.+--+-- Note this is not as accurate as @balanceTransactionInJournal@,+-- which considers the whole journal when calculating balance assignments and balance assertions.+balanceSingleTransaction :: BalancingOpts -> Transaction -> Either String Transaction+balanceSingleTransaction bopts = fmap fst . balanceTransactionHelper bopts++-- | Like 'balanceTransactionHelper', but in a lots journal, first try+-- balancing the transaction with its lot fee outflows auto-split+-- ('transactionAutoSplitFeeOutflows'): a lot transfer with a priced fee+-- only balances at cost in split form. If no split applies or the split+-- form doesn't balance, balance the unsplit form as usual (preserving its+-- error message if both fail). Lot classification runs after balancing and+-- will classify the split postings (#2686, #2692).+balanceTransactionHelperMaybeSplittingLotFees :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])+balanceTransactionHelperMaybeSplittingLotFees bopts t0+ | not haslots = balanceTransactionHelper bopts t0 -- no lots involved, nothing to tag or split+ | S.null lotfulcomms = balanceTransactionHelper bopts t -- no lotful commodities declared, no fee splitting+ | length (tpostings t2) == length (tpostings t) = balanceTransactionHelper bopts t -- no split applied+ | otherwise = case balanceTransactionHelper bopts t2 of+ r@(Right _) -> r+ Left _ -> balanceTransactionHelper bopts t+ where+ lotfulcomms = lotful_commodities_ bopts+ -- Could this entry involve lots ? Only if some amount has a cost basis or is in a lotful commodity.+ haslots = transactionHasLotfulAmounts lotfulcomms t0+ -- Tag any user-written gain postings in a disposal first, so the balancer+ -- sets them aside. (journalFinalise does this too, but callers balancing a+ -- single entry, like hledger add, rely on it happening here.)+ t = transactionTagGainPostings (not $ lenient_lots_ bopts) (verbose_balancing_tags_ bopts) (accountNameType (account_types_ bopts)) (`S.member` lotfulcomms)+ (accountUsesNoLotsWith (account_lots_tags_ bopts)) t0+ t2 = transactionAutoSplitFeeOutflows (verbose_balancing_tags_ bopts) (accountNameType (account_types_ bopts)) (`S.member` lotfulcomms)+ (accountUsesNoLotsWith (account_lots_tags_ bopts)) t++-- | An internal tag added by the journal reader to postings whose amount was calculated with+-- * or / in an amount expression, and changed by rounding (see+-- transactionRoundCalculatedAmounts) (#2648).+-- If the transaction doesn't balance, the error mentions the rounding.+-- The tag is removed when the transaction balances, so it is not seen by users or queries.+roundedPostingTagName :: TagName+roundedPostingTagName = "_rounded-posting"++-- | Remove the internal 'roundedPostingTagName' tag from a transaction's postings, if any.+transactionRemoveRoundedTags :: Transaction -> Transaction+transactionRemoveRoundedTags t+ | any (postingHasTag roundedPostingTagName) $ tpostings t =+ t{tpostings = [p{ptags = filter ((/= roundedPostingTagName) . fst) $ ptags p} | p <- tpostings t]}+ | otherwise = t++-- | Round the amounts in a transaction's postings which were calculated with * or / in an+-- amount expression, and which are exact until now (see amountexprp) (#2648).+-- Each is rounded to the transaction's balancing precision for its commodity, ie the most+-- decimal places of that commodity's posting amounts in the entry, as written, including any+-- amounts written in expressions, not counting costs (see transactionCommodityStyles).+-- As in balancing, amounts to be generated by balance assignments count too; their assigned+-- amounts are used for this.+-- This is done after all postings have been read, so it doesn't depend on their order.+-- Postings whose amount is changed by this get the internal roundedPostingTagName tag,+-- so that if the transaction doesn't balance, the error can mention the rounding.+-- The balancer removes the tag (see balanceTransactionHelper).+transactionRoundCalculatedAmounts :: Transaction -> Transaction+transactionRoundCalculatedAmounts t = t{tpostings = map roundposting $ tpostings t}+ where+ styles = transactionCommodityStyles t{tpostings = map withassignedamount $ tpostings t}+ withassignedamount p = case pbalanceassertion p of+ Just ba | hasBalanceAssignment p -> p{pamount = mixedAmount $ baamount ba}+ _ -> p+ roundposting p = case postingRoundCalculatedAmounts styles p of+ (p', True) -> postingAddTags p' [(roundedPostingTagName, "")]+ (p', False) -> p'++-- | Round the amounts in this posting which were calculated with * or / in an amount expression+-- (see amountexprp) (#2648). These are the amounts with more decimal places than their precision,+-- which is the most decimal places written in the amounts they were calculated from;+-- other parsed amounts never have more.+-- Each is rounded to the precision of its commodity's style in the given map,+-- or to its own precision if that is larger or the commodity is not in the map.+-- This uses banker's rounding, like other hledger rounding, and the rounded amount gets that precision.+-- Also returns whether this changed any amount's quantity.+postingRoundCalculatedAmounts :: M.Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)+postingRoundCalculatedAmounts styles p+ | not $ any iscalculated amts = (p, False)+ | otherwise = (p{pamount = mapMixedAmount roundcalculated $ pamount p}, any changed amts)+ where+ amts = amountsRaw $ pamount p+ iscalculated a = case asprecision $ astyle a of+ Precision n -> amountInternalPrecision a > n+ NaturalPrecision -> False+ precision a = case (asprecision $ astyle a, asprecision <$> M.lookup (acommodity a) styles) of+ (Precision n, Just (Precision m)) -> max n m+ (Precision n, _) -> n+ (NaturalPrecision, _) -> amountInternalPrecision a+ rounded a = let a' = amountSetPrecision (Precision $ precision a) a in a'{aquantity = amountRoundedQuantity a'}+ roundcalculated a = if iscalculated a then rounded a else a+ changed a = iscalculated a && aquantity (rounded a) /= aquantity a++-- | Helper used by balanceSingleTransaction and balanceTransactionWithBalanceAssignmentAndCheckAssertionsB;+-- use one of those instead.+-- It also returns a list of accounts and amounts that were inferred.+balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])+balanceTransactionHelper bopts t = do+ let lbl = lbl_ "balanceTransactionHelper"+ (t', inferredamtsandaccts) <- t+ & (if infer_balancing_costs_ bopts then transactionInferBalancingCosts (lenient_lots_ bopts) (lotful_commodities_ bopts) else id)+ & dbg9With (lbl "amounts after balancing-cost-inferring".show.map showMixedAmountOneLine.transactionAmounts)+ & transactionInferBalancingAmount (fromMaybe M.empty $ commodity_styles_ bopts) (account_types_ bopts)+ <&> dbg9With (lbl "balancing amounts inferred".show.map (second showMixedAmountOneLine).snd)+ case transactionCheckBalanced bopts t' of+ [] -> Right (txnTieKnot $ transactionRemoveRoundedTags t', inferredamtsandaccts)+ errs -> Left $ transactionBalanceError t' errs'+ where+ ismulticommodity = (length $ transactionCommodities t') > 1+ errs' =+ [ "Automatic commodity conversion is disabled by strict mode or the balanced check."+ | ismulticommodity && not (infer_balancing_costs_ bopts)+ ] +++ errs+ -- silence hints for now+ -- +++ -- if ismulticommodity+ -- then+ -- [ "Consider adjusting this entry's amounts, adding missing postings,"+ -- , "or recording conversion price(s) with @, @@ or equity postings." + -- ]+ -- else []++transactionCommodities :: Transaction -> S.Set CommoditySymbol+transactionCommodities t = mconcat $ map (maCommodities . pamount) $ tpostings t++-- | Generate a transaction balancing error message, given the transaction+-- and one or more suberror messages.+transactionBalanceError :: Transaction -> [String] -> String+transactionBalanceError t errs = printf "%s:\n%s\n\nThis %stransaction is unbalanced.\n%s"+ (sourcePosPairPretty $ tsourcepos t)+ (textChomp ex)+ (if ismulticommodity then "multi-commodity " else "" :: String)+ (chomp $ unlines errs)+ where+ ismulticommodity = (length $ transactionCommodities t) > 1+ (_f,_l,_mcols,ex) = makeTransactionErrorExcerpt t finderrcols+ where+ finderrcols _ = Nothing+ -- finderrcols t = Just (1, Just w)+ -- where+ -- w = maximumDef 1 $ map T.length $ T.lines $ showTransaction t++-- | Infer up to one missing amount for this transactions's real postings, and+-- likewise for its balanced virtual postings, if needed; or return an error+-- message if we can't. Returns the updated transaction and any inferred posting amounts,+-- with the corresponding accounts, in order).+--+-- We can infer a missing amount when there are multiple postings and exactly+-- one of them is amountless. If the amounts had price(s) the inferred amount+-- have the same price(s), and will be converted to the price commodity.+transactionInferBalancingAmount ::+ M.Map CommoditySymbol AmountStyle -- ^ commodity display styles+ -> M.Map AccountName AccountType -- ^ account type map (passed through; reserved for future use)+ -> Transaction+ -> Either String (Transaction, [(AccountName, MixedAmount)])+transactionInferBalancingAmount styles _atypes t@Transaction{tpostings=ps}+ | all hasAmount ps = Right (t, []) -- nothing to infer (the usual case), keep the transaction as is+ | length amountlessrealps > 1+ = Left $ transactionBalanceError t+ ["There can't be more than one real posting with no amount."+ ,"(Remember to put two or more spaces between account and amount.)"]+ | length amountlessbvps > 1+ = Left $ transactionBalanceError t+ ["There can't be more than one balanced virtual posting with no amount."+ ,"(Remember to put two or more spaces between account and amount.)"]+ | otherwise+ = let psandinferredamts = map inferamount ps+ inferredacctsandamts = [(paccount p, amt) | (p, Just amt) <- psandinferredamts]+ in Right (+ t{tpostings=map fst psandinferredamts}+ ,inferredacctsandamts+ -- & dbg9With (lbl "inferred".show.map (showMixedAmountOneLine.snd))+ )+ where+ lbl = lbl_ "transactionInferBalancingAmount"+ -- Gain postings in a disposal are set aside (see transactionCheckBalanced):+ -- they don't contribute to the sum, and an amountless one is not inferred+ -- here (journalAddOrCheckGainPostings fills it in after lot matching).+ setaside = isSetAsideGainPosting t+ (amountfulrealps, amountlessrealps) = partition hasAmount $ filter (not . setaside) (realPostings t)+ realsum = maSum $ map balancingamount amountfulrealps+ -- & dbg9With (lbl "real balancing amount".showMixedAmountOneLine)+ (amountfulbvps, amountlessbvps) = partition hasAmount $ filter (not . setaside) (balancedVirtualPostings t)+ bvsum = maSum $ map balancingamount amountfulbvps+ -- A posting's amount at cost, unless its cost is represented by equity+ -- conversion postings, in which case the cost is ignored (as in transactionCheckBalanced).+ balancingamount p+ | costPostingTagName `elem` map fst (ptags p) = mixedAmountStripCosts $ pamount p+ | otherwise = mixedAmountCost $ pamount p++ inferamount :: Posting -> (Posting, Maybe MixedAmount)+ inferamount p | setaside p = (p, Nothing)+ inferamount p =+ let+ minferredamt = case preal p of+ RealPosting | not (hasAmount p) -> Just realsum+ BalancedVirtualPosting | not (hasAmount p) -> Just bvsum+ VirtualPosting | not (hasAmount p) -> Just 0+ _ -> Nothing+ in+ case minferredamt of+ Nothing -> (p, Nothing)+ Just a -> (p{pamount=a', poriginal=Just $ originalPosting p}, Just a')+ where+ -- Inferred amounts are converted to cost, and zero amounts+ -- alongside non-zero ones are dropped (a cost posting's quantity+ -- and its conversion posting cancel, leaving a zero which lot+ -- classification would otherwise see as a lotful amount).+ -- Also ensure the new amount has the standard style for its commodity+ -- (since the main amount styling pass happened before this balancing pass);+ a' = maNegate a+ & mixedAmountCost+ & dropZeroResidues+ -- Apply global commodity styles for formatting, but keep the precision unchanged.+ -- This inferred amount's precision won't influence local or global precisions.+ & styleAmounts (styles & amountStylesSetRounding NoRounding)+ & dbg9With (lbl "balancing amount styled".showMixedAmountOneLine)+ dropZeroResidues ma+ | any (not . amountIsZero) (amountsRaw ma) = filterMixedAmount (not . amountIsZero) ma+ | otherwise = ma++-- | Infer costs for this transaction's posting amounts, if needed to make+-- the postings balance, and if permitted. This is done once for the real+-- postings and again (separately) for the balanced virtual postings. When+-- it's not possible, the transaction is left unchanged.+--+-- The simplest example is a transaction with two postings, each in a+-- different commodity, with no costs specified. In this case we'll add a+-- cost to the first posting such that it can be converted to the commodity+-- of the second posting (with -B), and such that the postings balance.+--+-- In general, we can infer a cost (conversion rate) when the sum of posting amounts+-- contains exactly two different commodities and no explicit costs. Also+-- all postings are expected to contain an explicit amount (no missing+-- amounts) in a single commodity. Otherwise no cost inferring is attempted.+--+-- The transaction itself could contain more than two commodities, and/or+-- costs, if they cancel out; what matters is that the sum of posting amounts+-- contains exactly two commodities and zero costs.+--+-- There can also be more than two postings in either of the commodities.+--+-- We want to avoid excessive display of digits when the calculated cost is+-- an irrational number, while hopefully also ensuring the displayed numbers+-- make sense if the user does a manual calculation. This is (mostly) achieved+-- in two ways:+--+-- - when there is only one posting in the "from" commodity, a total cost+-- (@@) is used, and all available decimal digits are shown+--+-- - otherwise, a suitable averaged unit cost (@) is applied to the relevant+-- postings, with display precision equal to the summed display precisions+-- of the two commodities being converted between, or 2, whichever is larger.+--+-- (We don't always calculate a good-looking display precision for unit costs+-- when the commodity display precisions are low, eg when a journal doesn't+-- use any decimal places. The minimum of 2 helps make the costs shown by the+-- print command a bit less surprising in this case. Could do better.)+--+transactionInferBalancingCosts :: Bool -> S.Set CommoditySymbol -> Transaction -> Transaction+transactionInferBalancingCosts lenientlots lotfulcomms t@Transaction{tpostings=ps} =+ case (inferrerFor RealPosting, inferrerFor BalancedVirtualPosting) of+ (Nothing, Nothing) -> t -- no costs can be inferred (the usual case), keep the transaction as is+ (mreal, mbv) -> t{tpostings=map (fromMaybe id mbv . fromMaybe id mreal) ps}+ where+ inferrerFor = costInferrerFor lenientlots lotfulcomms t++-- | Does one of these postings make this commodity look lot-related ?+-- True if the commodity appears in a posting amount with a cost basis+-- annotation.+-- (Lot classification runs after balancing, so ptype tags can't be used+-- here; this is a shape check.)+commodityHasLotPosting :: [Posting] -> CommoditySymbol -> Bool+commodityHasLotPosting postings comm = any (\p ->+ any (\a -> acommodity a == comm && isJust (acostbasis a)) (amountsRaw $ pamount p)+ ) postings++-- | Is this commodity lot-related (see commodityHasLotPosting, or declared+-- lotful) and appearing with both signs among these postings (a+-- transfer-like shape) ?+lotRelatedBothSigns :: S.Set CommoditySymbol -> [Posting] -> CommoditySymbol -> Bool+lotRelatedBothSigns lotfulcomms postings c =+ (commodityHasLotPosting postings c || c `S.member` lotfulcomms)+ && any (\x -> acommodity x == c && aquantity x > 0) pamounts+ && any (\x -> acommodity x == c && aquantity x < 0) pamounts+ where pamounts = concatMap (amountsRaw . pamount) postings++-- | The lot-related commodities among these postings (of one realness)+-- whose quantities look mismatched: the commodity appears with both signs+-- (a transfer-like shape), yet its residual is nonzero and not exactly one+-- posting's amount. Balancing cost inference is declined for such entries+-- (see costInferrerFor): an inferred cost would attach to both sides, mask+-- the imbalance (eg a fee deducted in kind but recorded in cash), and+-- surface later as a confusing lot error; the balancedness check reports+-- it better, with a note (see transactionCheckBalanced). When the residual+-- equals one posting's amount (a dispose posting alongside a matched+-- transfer pair, eg a same-account reclassify+fee entry), or the commodity+-- appears with one sign only (a bare sale or purchase), a cost is inferred+-- as documented. Returns [] unless the postings' residual is exactly two+-- unpriced opposite-signed commodities (the case where a balancing cost+-- could otherwise be inferred).+lotMismatchCommodities :: S.Set CommoditySymbol -> [Posting] -> [CommoditySymbol]+lotMismatchCommodities lotfulcomms postings =+ case sumamounts of+ [a,b] | all (isNothing . acost) sumamounts+ , signum (aquantity a) /= signum (aquantity b)+ -> map acommodity $ filter lotrelatedMismatch [a,b]+ _ -> []+ where+ sumamounts = amounts $ sumPostings postings+ pamounts = concatMap (amountsRaw . pamount) postings+ lotrelatedMismatch a =+ lotRelatedBothSigns lotfulcomms postings c+ && not (any (\x -> acommodity x == c && aquantity x == aquantity a) pamounts)+ where c = acommodity a++-- | Generate a posting update function which assigns a suitable cost to+-- balance the posting, if and as appropriate for the given transaction and+-- posting realness (real or balanced virtual); or Nothing if we cannot or+-- should not infer costs.+costInferrerFor :: Bool -> S.Set CommoditySymbol -> Transaction -> PostingRealness -> Maybe (Posting -> Posting)+costInferrerFor lenientlots lotfulcomms t pt = infercost <$> inferFromAndTo+ where+ lbl = lbl_ "costInferrerFor"+ setaside = isSetAsideGainPosting t+ postings = filter (\p -> preal p == pt && not (setaside p)) $ tpostings t -- gain postings are set aside, as in transactionCheckBalanced+ pcommodities = map acommodity $ concatMap (amounts . pamount) postings+ sumamounts = amounts $ sumPostings postings -- amounts normalises to one amount per commodity & price++ -- We can infer prices if there are no prices given, exactly two commodities in the normalised+ -- sum of postings in this transaction, these two have opposite signs, and neither looks like+ -- a lot quantity mismatch (see lotMismatchCommodities; this veto is skipped in lenient+ -- --ignore-lots mode, letting such entries load). The amount we are+ -- converting from is normally the first commodity to appear in the ordered list of postings;+ -- but if exactly one of the two commodities looks lot-related (its posting has a cost basis+ -- annotation or an inherited lots: account tag), or failing that, is a declared lotful+ -- commodity (#2686), prefer that one, so the inferred cost is attached to the posting that+ -- needs it for lot tracking. (Lot classification runs after balancing, so tags can't be+ -- used here; these are shape checks.)+ -- If we cannot infer prices, return Nothing.+ inferFromAndTo = case sumamounts of+ [a,b] | noprices, oppositesigns, lenientlots || null (lotMismatchCommodities lotfulcomms postings) ->+ prefer (commodityHasLotPosting postings) <|> prefer (`S.member` lotfulcomms) <|> asum (map orderIfMatches pcommodities)+ where+ prefer hasquality = case (hasquality (acommodity a), hasquality (acommodity b)) of+ (True, False) -> Just (a, b)+ (False, True) -> Just (b, a)+ _ -> Nothing+ noprices = all (isNothing . acost) sumamounts+ oppositesigns = signum (aquantity a) /= signum (aquantity b)+ orderIfMatches x | x == acommodity a = Just (a,b)+ | x == acommodity b = Just (b,a)+ | otherwise = Nothing+ _ -> Nothing++ -- When the from commodity is lot-related and appears with both signs,+ -- and exactly one single-amount posting equals the residual, attach the+ -- whole cost to that posting only (as a total cost), leaving the others+ -- unpriced: they form matched transfer pairs, which must stay unpriced+ -- for lot classification; only the odd one out (a dispose, eg a fee+ -- disposal alongside a transfer) needs the cost (#2692).+ isTargeted fromamount =+ lotRelatedBothSigns lotfulcomms postings (acommodity fromamount)+ && length residualPostings == 1+ where+ residualPostings =+ [ () | q <- postings, [a] <- [amounts (pamount q)]+ , acommodity a == acommodity fromamount, aquantity a == aquantity fromamount ]++ -- For each posting, if the posting type matches, there is only a single amount in the posting,+ -- and the commodity of the amount matches the amount we're converting from+ -- (and, in the targeted case above, its quantity is the whole residual),+ -- then set its cost based on the ratio between fromamount and toamount.+ infercost (fromamount, toamount) p+ | [a] <- amounts (pamount p), preal p == pt, acommodity a == acommodity fromamount+ , not (isTargeted fromamount) || aquantity a == aquantity fromamount+ = p{ pamount = mixedAmount a{acost=Just conversionprice}+ & dbg9With (lbl "inferred cost".showMixedAmountOneLine)+ , poriginal = Just $ originalPosting p }+ | otherwise = p+ where+ -- In the targeted case, or if only one Amount in the posting list matches fromamount,+ -- we can use TotalCost.+ -- Otherwise divide the conversion equally among the Amounts by using a unit price.+ conversionprice+ | isTargeted fromamount = TotalCost $ negate toamount+ | otherwise = case filter (== acommodity fromamount) pcommodities of+ [_] -> TotalCost $ negate toamount+ _ -> UnitCost $ showFully $ negate unitcost `withPrecision` unitprecision++ unitcost = aquantity fromamount `divideAmount` toamount+ unitprecision = case (asprecision $ astyle fromamount, asprecision $ astyle toamount) of+ (Precision a, Precision b) -> Precision . max 2 $ saturatedAdd a b+ _ -> NaturalPrecision+ saturatedAdd a b = if maxBound - a < b then maxBound else a + b+ -- Show the unit cost exactly, or if it's a repeating decimal, with 8 decimal places,+ -- like other calculated amounts (or with unitprecision, if that's more).+ showFully u = amountSetPrecisionMin (amountDisplayPrecision u) $ amountSetFullPrecisionUpTo Nothing u+++-- "Transaction balancing", including: inferring missing amounts,+-- applying balance assignments, checking transaction balancedness,+-- checking balance assertions, respecting posting dates. These things+-- are all interdependent.+-- WARN tricky algorithm and code ahead. +--+-- Code overview as of 20190219, this could/should be simplified/documented more:+-- parseAndFinaliseJournal['] (Cli/Utils.hs), journalAddForecast (Common.hs), journalAddBudgetGoalTransactions (BudgetReport.hs), tests (BalanceReport.hs)+-- journalBalanceTransactions+-- runST+-- runExceptT+-- balanceSingleTransaction (Transaction.hs)+-- balanceTransactionHelper+-- runReaderT+-- balanceTransactionAndCheckAssertionsB+-- addAmountAndCheckAssertionB+-- addOrAssignAmountAndCheckAssertionB+-- balanceTransactionHelper (Transaction.hs)+-- uiCheckBalanceAssertions d ui@UIState{aopts=UIOpts{cliopts_=copts}, ajournal=j} (ErrorScreen.hs)+-- journalCheckBalanceAssertions+-- journalBalanceTransactions+-- transactionWizard, postingsBalanced (Add.hs), tests (Transaction.hs)+-- balanceSingleTransaction (Transaction.hs) XXX hledger add won't allow balance assignments + missing amount ?++-- | Monad used for statefully balancing/amount-inferring/assertion-checking+-- a sequence of transactions.+-- Perhaps can be simplified, or would a different ordering of layers make sense ?+-- If you see a way, let us know.+type Balancing s = ReaderT (BalancingState s) (ExceptT String (ST s))++-- | Whether and how to check balance assertions while balancing:+-- not at all; erroring at the first failure; or checking but deferring+-- a failure - recording the first one in the given mutable slot and+-- continuing, so it can be reported later+-- (see journalBalanceTransactionsAndDeferAssertions).+data AssertionsMode s+ = DontCheckAssertions+ | CheckAssertions+ | DeferAssertions (STRef s (Maybe String))++-- | The state used while balancing a sequence of transactions.+data BalancingState s = BalancingState {+ -- read only+ bsBalancingOpts :: BalancingOpts -- ^ the balancing options (with the journal's commodity display styles), for balancing the transactions with balance assignments+ ,bsUnassignable :: S.Set AccountName -- ^ accounts where balance assignments may not be used (because of auto posting rules)+ ,bsAssrt :: AssertionsMode s -- ^ whether/how to check balance assertions+ ,bsAliases :: CommodityAliases -- ^ commodity aliases with a quantity other than 1, whose amounts running balances keep unconverted (see postingRunningBalanceAmount)+ -- mutable+ ,bsBalances :: H.HashTable s AccountName MixedAmount -- ^ running account balances, initially empty+ ,bsTransactions :: STArray s Integer Transaction -- ^ a mutable array of the transactions being balanced+ -- (for efficiency ? journalBalanceTransactions says: not strictly necessary but avoids a sort at the end I think)+ }++-- | Access the current balancing state, and possibly modify the mutable bits,+-- lifting through the Except and Reader layers into the Balancing monad.+withRunningBalance :: (BalancingState s -> ST s a) -> Balancing s a+withRunningBalance f = ask >>= lift . lift . f++-- | Get this account's current exclusive running balance.+getRunningBalanceB :: AccountName -> Balancing s MixedAmount+getRunningBalanceB acc = withRunningBalance $ \BalancingState{bsBalances, bsAliases} -> do+ maConvertAliases bsAliases . fromMaybe nullmixedamt <$> H.lookup bsBalances acc++-- | Get this account's current inclusive running balance+-- (the sum of the running balances of this account and any subaccounts seen so far).+getInclusiveRunningBalanceB :: AccountName -> Balancing s MixedAmount+getInclusiveRunningBalanceB acc = withRunningBalance $ \BalancingState{bsBalances, bsAliases} ->+ maConvertAliases bsAliases <$> H.foldM+ (\ibal (a, amt) -> return $+ if acc==a || acc `isAccountNamePrefixOf` a then maPlus ibal amt else ibal)+ nullmixedamt+ bsBalances++-- | Add this amount to this account's exclusive running balance.+-- Returns the new running balance.+addToRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount+addToRunningBalanceB acc amt = withRunningBalance $ \BalancingState{bsBalances} -> do+ old <- fromMaybe nullmixedamt <$> H.lookup bsBalances acc+ let new = maPlus old amt+ H.insert bsBalances acc new+ return new++-- | Set this account's exclusive running balance to this amount.+-- Returns the change in exclusive running balance.+setRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount+setRunningBalanceB acc amt = withRunningBalance $ \BalancingState{bsBalances, bsAliases} -> do+ old <- fromMaybe nullmixedamt <$> H.lookup bsBalances acc+ H.insert bsBalances acc amt+ return $ maMinus amt $ maConvertAliases bsAliases old++-- | Set this account's exclusive running balance to whatever amount+-- makes its *inclusive* running balance (the sum of exclusive running+-- balances of this account and any subaccounts) be the given amount.+-- Returns the change in exclusive running balance.+setInclusiveRunningBalanceB :: AccountName -> MixedAmount -> Balancing s MixedAmount+setInclusiveRunningBalanceB acc newibal = withRunningBalance $ \BalancingState{bsBalances, bsAliases} -> do+ oldebal <- maConvertAliases bsAliases . fromMaybe nullmixedamt <$> H.lookup bsBalances acc+ allebals <- H.toList bsBalances+ let subsibal = -- sum of any subaccounts' running balances+ maConvertAliases bsAliases . maSum . map snd $ filter ((acc `isAccountNamePrefixOf`).fst) allebals+ let newebal = maMinus newibal subsibal+ H.insert bsBalances acc newebal+ return $ maMinus newebal oldebal++-- | The amount a posting adds to its account's running balance.+-- An amount converted from a commodity alias with a quantity is kept in the alias, as written+-- (without costs), and running balances are converted only when they're used (see maConvertAliases).+-- This way, eg three amounts of 10 min add up to exactly 0.5 h,+-- though each of them converts to 0.1666.. h, rounded at the 255th decimal place.+postingRunningBalanceAmount :: CommodityAliases -> Posting -> MixedAmount+postingRunningBalanceAmount aliases p+ | M.null aliases = pamount p+ | any ((`M.member` aliases) . acommodity) (amountsRaw written)+ && mixedAmountIsZero (maConvertAliases aliases written `maMinus` mixedAmountStripCosts (pamount p)) = written+ | otherwise = pamount p+ where written = mixedAmountStripCosts $ pamount $ originalPosting p++-- | Convert any amounts in these commodity aliases to their commodity.+-- Each alias's total is divided only once, so the result is exact when possible+-- (eg 30 min is exactly 0.5 h).+maConvertAliases :: CommodityAliases -> MixedAmount -> MixedAmount+maConvertAliases aliases ma+ | M.null aliases = ma+ | otherwise = foldMap (mixedAmount . fst . convertAliasAmount aliases) $ amountsRaw $ mixedAmountStripCosts ma++-- | Update (overwrite) this transaction in the balancing state.+updateTransactionB :: Transaction -> Balancing s ()+updateTransactionB t = withRunningBalance $ \BalancingState{bsTransactions} ->+ void $ writeArray bsTransactions (tindex t) t++-- | Infer any missing amounts and/or conversion costs+-- (as needed to balance transactions and satisfy balance assignments);+-- and check that all transactions are balanced;+-- and (optional) check that all balance assertions pass.+-- Or, return an error message (just the first error encountered).+--+-- Assumes journalStyleAmounts has been called, since amount styles+-- affect transaction balancing.+--+-- This does multiple things at once because amount inferring, balance+-- assignments, balance assertions and posting dates are interdependent.+--+journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal+journalBalanceTransactions bopts j = fst <$> journalBalanceTransactionsHelper False bopts j++-- | Like journalBalanceTransactions, but instead of erroring at the first+-- failed balance assertion, keep going and also return the first assertion+-- failure's error message, if any. This lets callers (journalFinalise) run+-- further checks, eg the lot stages, and report their errors first.+journalBalanceTransactionsAndDeferAssertions :: BalancingOpts -> Journal -> Either String (Journal, Maybe String)+journalBalanceTransactionsAndDeferAssertions = journalBalanceTransactionsHelper True++journalBalanceTransactionsHelper :: Bool -> BalancingOpts -> Journal -> Either String (Journal, Maybe String)+journalBalanceTransactionsHelper deferassertions bopts' j' =+ let+ -- ensure transactions are numbered, so we can store them by number+ j@Journal{jtxns=ts} = journalNumberTransactions j'+ -- display precisions used in balanced checking+ styles = Just $+ -- Use all the specified commodity display precisions, with hard rounding, when checking txn balancedness.+ -- XXX Problem, those precisions will also be used when inferring balancing amounts;+ -- it would be better to give those the precision of the amount they are balancing.+ journalCommodityStylesWith HardRounding+ j+ bopts = bopts'{commodity_styles_=styles}+ -- XXX ^ The commodity directive styles and default style and inferred styles+ -- are merged into the command line styles in commodity_styles_ - why ?+ -- Mainly for the precisions, used during amount and cost inference and balanced checking ?+ -- balance assignments are not allowed on accounts affected by auto postings+ autopostingaccts = S.fromList . map (paccount . tmprPosting) . concatMap tmpostingrules $ jtxnmodifiers j+ in+ -- Store the transactions in a mutable array, which we'll update as we balance them.+ -- Not strictly necessary but avoids a sort at the end I think.+ runST $ do+ balancedtxns <- newListArray (1, toInteger $ length ts) ts+ -- Holds the first deferred balance assertion failure, if any.+ massertionerr <- newSTRef Nothing+ let assertionsmode+ | ignore_assertions_ bopts = DontCheckAssertions+ | deferassertions = DeferAssertions massertionerr+ | otherwise = CheckAssertions++ -- Process all transactions, or short-circuit with an error.+ runExceptT $ do++ -- Two passes are required:+ -- 1. Step through the transactions, balancing the ones which don't have balance assignments,+ -- postponing those which do until later. The balanced ones are split into their postings,+ -- keeping these and the not-yet-balanced transactions in the same relative order.+ -- (With --infer-imbalance, balanced transactions also get postings showing any tolerated imbalance.)+ psandts :: [Either Posting Transaction] <- fmap concat $ forM ts $ \case+ t | null $ assignmentPostings t -> case fst . transactionMaybeAddImbalancePostings bopts . fst <$> balanceTransactionHelperMaybeSplittingLotFees bopts t of+ Left e -> throwError e+ Right t' -> do+ lift $ writeArray balancedtxns (tindex t') t'+ return $ map Left $ tpostings t'+ t -> return [Right t]++ -- 2. Step through these items in date order (and preserved same-day order),+ -- keeping running balances for all accounts.+ -- This pass serves only balance assignments and assertions, so it is+ -- skipped when there are none to process (a big saving on large journals).+ let+ checkingassertions = case assertionsmode of DontCheckAssertions -> False; _ -> True+ hasassertions = any (isJust . pbalanceassertion) [p | Left p <- psandts]+ hasassignments = any isRight psandts+ when (hasassignments || (checkingassertions && hasassertions)) $ do+ runningbals <- lift $ H.newSized (length $ journalAccountNamesUsed j)+ let aliases = M.filter (\(_, q, _) -> q /= 1) $ journalCommodityAliases j+ flip runReaderT (BalancingState bopts autopostingaccts assertionsmode aliases runningbals balancedtxns) $ do+ -- On encountering any not-yet-balanced transaction with a balance assignment,+ -- enact the balance assignment then finish balancing the transaction.+ -- And, check any balance assertions encountered along the way.+ void $ mapM' balanceTransactionAndCheckAssertionsB $ sortOn (either postingDate tdate) psandts++ -- Return the now fully-balanced and checked transactions,+ -- and any deferred balance assertion failure.+ ts' <- lift $ getElems balancedtxns+ merr <- lift $ readSTRef massertionerr+ return (j{jtxns=ts'}, merr)++-- Before #2039: "Costs are removed, which helps eg assertions.test: 15. Mix different commodities and assignments."++-- | This function is called statefully on each of a date-ordered sequence of+-- 1. fully explicit postings from already-balanced transactions and+-- 2. not-yet-balanced transactions containing balance assignments.+-- It executes balance assignments and finishes balancing the transactions,+-- and checks balance assertions on each posting as it goes.+-- An error will be thrown if a transaction can't be balanced+-- or if an illegal balance assignment is found (cf checkIllegalBalanceAssignment).+-- This stores the balanced transactions in case 2 but not in case 1.+balanceTransactionAndCheckAssertionsB :: Either Posting Transaction -> Balancing s ()+balanceTransactionAndCheckAssertionsB (Left p@Posting{}) =+ -- Update the account's running balance and check the balance assertion if any.+ -- Cost is ignored when checking balance assertions currently.+ void $ addAmountAndCheckAssertionB $ postingStripCosts p+balanceTransactionAndCheckAssertionsB (Right t@Transaction{tpostings=ps}) = do+ -- make sure we can handle the balance assignments+ mapM_ checkIllegalBalanceAssignmentB ps+ -- for each posting, in date order (though without disturbing their display order),+ -- 1. infer its amount from the balance assignment if applicable,+ -- 2. update the account's running balance, and+ -- 3. check the balance assertion if any.+ ps' <- ps+ & zip [1..] -- attach original positions+ & sortOn (postingDate.snd) -- sort by date+ & mapM addOrAssignAmountAndCheckAssertionB -- infer amount, check assertion on each one+ <&> sortOn fst -- restore original order+ <&> map snd -- discard positions++ -- infer any remaining missing amounts, and make sure the transaction is now fully balanced+ -- (using all the balancing options, as for the other transactions)+ bopts1 <- R.asks bsBalancingOpts+ let t1 = t{tpostings=ps'}+ -- The transaction may be a lot transfer with a fee (whose outflow amount+ -- possibly was only just inferred from a balance assignment): a priced+ -- fee's entry only balances in split form, and any elided posting must+ -- infer the post-split residual (rather than wrongly absorbing the fee's+ -- cost value). (#2686)+ balanceres = balanceTransactionHelperMaybeSplittingLotFees bopts1 t1+ case balanceres of+ Left err -> throwError err+ Right (t', inferredacctsandamts) -> do+ -- with --infer-imbalance, show any tolerated imbalance+ let (t'', imbalanceps) = transactionMaybeAddImbalancePostings bopts1 t'+ -- for each amount just inferred or added, update the running balance+ mapM_ (uncurry addToRunningBalanceB) $ inferredacctsandamts ++ [(paccount p, pamount p) | p <- imbalanceps]+ -- and save the balanced transaction.+ updateTransactionB t''++type NumberedPosting = (Integer, Posting)++-- | If this posting has an explicit amount, add it to the account's running balance.+-- If it has a missing amount and a balance assignment, infer the amount from, and+-- reset the running balance to, the assigned balance.+-- If it has a missing amount and no balance assignment, leave it for later.+-- Then test the balance assertion if any.+addOrAssignAmountAndCheckAssertionB :: NumberedPosting -> Balancing s NumberedPosting+addOrAssignAmountAndCheckAssertionB (i,p@Posting{paccount=acc, pbalanceassertion=mba})+ -- an explicit posting amount+ | hasAmount p = do+ aliases <- R.asks bsAliases+ newbal <- addToRunningBalanceB acc $ postingRunningBalanceAmount aliases p+ checkOrDeferBalanceAssertionB p newbal+ return (i,p)++ -- no explicit posting amount, but there is a balance assignment+ | Just BalanceAssertion{baamount,batotal,bainclusive} <- mba = do+ let (getbal, setbal) | bainclusive = (getInclusiveRunningBalanceB, setInclusiveRunningBalanceB)+ | otherwise = (getRunningBalanceB, setRunningBalanceB)+ newbal <- if batotal+ -- a total balance assignment (==, all commodities)+ then return $ mixedAmount baamount+ -- a partial balance assignment (=, one commodity), keeping the other commodities+ else do+ oldbalothercommodities <- filterMixedAmount ((acommodity baamount /=) . acommodity) <$> getbal acc+ return $ maAddAmount oldbalothercommodities baamount+ diff <- setbal acc newbal+ let p' = p{pamount=filterMixedAmount (not . amountIsZero) diff, poriginal=Just $ originalPosting p}+ checkOrDeferBalanceAssertionB p' newbal+ return (i,p')++ -- no explicit posting amount, no balance assignment+ | otherwise = return (i,p)++-- | Add the posting's amount to its account's running balance, and+-- optionally check the posting's balance assertion if any.+-- The posting is expected to have an explicit amount (otherwise this does nothing).+-- Adding and checking balance assertions are tightly paired because we+-- need to see the balance as it stands after each individual posting.+addAmountAndCheckAssertionB :: Posting -> Balancing s Posting+addAmountAndCheckAssertionB p | hasAmount p = do+ aliases <- R.asks bsAliases+ newbal <- addToRunningBalanceB (paccount p) $ postingRunningBalanceAmount aliases p+ checkOrDeferBalanceAssertionB p newbal+ return p+addAmountAndCheckAssertionB p = return p++-- | Check the posting's balance assertion (if any) against the given balance,+-- per the current assertions mode: not at all; erroring immediately on a+-- failure; or recording the first failure and continuing.+checkOrDeferBalanceAssertionB :: Posting -> MixedAmount -> Balancing s ()+checkOrDeferBalanceAssertionB p newbal0 = do+ newbal <- R.asks $ \s -> maConvertAliases (bsAliases s) newbal0+ R.reader bsAssrt >>= \case+ DontCheckAssertions -> return ()+ CheckAssertions -> checkBalanceAssertionB p newbal+ DeferAssertions ref -> checkBalanceAssertionB p newbal `catchError` \e ->+ lift . lift $ modifySTRef' ref (<|> Just e)++-- | Check a posting's balance assertion against the given actual balance, and+-- return an error if the assertion is not satisfied.+-- If the assertion is partial, unasserted commodities in the actual balance+-- are ignored; if it is total, they will cause the assertion to fail.+checkBalanceAssertionB :: Posting -> MixedAmount -> Balancing s ()+checkBalanceAssertionB p@Posting{pbalanceassertion=Just (BalanceAssertion{baamount,batotal})} actualbal =+ forM_ (baamount : otheramts) $ \amt -> checkBalanceAssertionOneCommodityB p amt actualbal+ where+ assertedcomm = acommodity baamount+ otheramts | batotal = map (\a -> a{aquantity=0}) . amountsRaw+ $ filterMixedAmount ((/=assertedcomm).acommodity) actualbal+ | otherwise = []+checkBalanceAssertionB _ _ = return ()++-- | Does this (single commodity) expected balance match the amount of that+-- commodity in the given (multicommodity) actual balance, ignoring costs ?+-- If not, returns a balance assertion failure message based on the provided posting.+-- To match, the amounts must be exactly equal (display precision is ignored here).+-- If the assertion is inclusive, the expected amount is compared with the account's+-- subaccount-inclusive balance; otherwise, with the subaccount-exclusive balance.+checkBalanceAssertionOneCommodityB :: Posting -> Amount -> MixedAmount -> Balancing s ()+checkBalanceAssertionOneCommodityB p@Posting{paccount=assertedacct} assertedcommbal actualbal = do+ let isinclusive = maybe False bainclusive $ pbalanceassertion p+ let istotal = maybe False batotal $ pbalanceassertion p+ -- mstyles <- R.asks (commodity_styles_ . bsBalancingOpts)+ -- let styled = maybe id styleAmounts mstyles+ actualbal' <- if isinclusive then getInclusiveRunningBalanceB assertedacct else return actualbal+ let+ assertedcomm = acommodity assertedcommbal++ -- The asserted single-commodity balance, without cost+ assertedcommbalcostless = amountStripCost assertedcommbal++ -- The balance in this commodity, from the current multi-commodity running balance at this point.+ -- This is unnormalised, and could include one or more different costs.+ actualcommbal = filterMixedAmountByCommodity assertedcomm $ actualbal'++ -- The above balance without costs, as a single Amount (Amount's + discards costs).+ actualcommbalcostless = sum $ amountsRaw actualcommbal++ -- test the assertion+ pass =+ aquantity assertedcommbalcostless+ ==+ aquantity actualcommbalcostless++ errmsg = chomp $ printf (unlines+ [ "%s:",+ "%s\n",+ "Balance assertion failed in %s",+ "%s at this point, %s, ignoring costs,",+ "the asserted balance is: %s",+ "but the calculated balance is: %s",+ "(difference: %s)",+ "To troubleshoot, check this account's running balance with assertions disabled, eg:",+ "hledger reg -E --ignore-assertions '%s'%s -e %s%s"+ ])++ (sourcePosPretty pos) -- position+ (textChomp ex) -- journal excerpt+ acct -- asserted account+ (if istotal then "Across all commodities" else "In commodity " <> assertedcommstr) -- asserted commodity or all commodities ?+ (if isinclusive then "including subaccounts" else "excluding subaccounts" :: String) -- inclusive or exclusive balance asserted ?+ (pad assertedstr -- asserted amount, without cost+ <> if debugLevel >= 2 then " (with cost: " <> T.pack (showAmountWith fmt assertedcommbal) <> ")" else ""+ )+ (pad actualstr -- actual amount, without cost+ <> if debugLevel >= 2 then " (with costs: " <> T.pack (showMixedAmountWith fmt actualcommbal) <> ")" else ""+ )+ diffstr -- their difference+ (T.unpack (regexEscape (paccount p)) ++ if isinclusive then "" else "$") -- query matching the account(s) postings+ (if istotal then "" else (" cur:" ++ quoteForCommandLine (T.unpack (regexEscape (assertedcomm))))) -- query matching the commodity(ies)+ (show $ addDays 1 $ postingDate p) -- exclusive end date just after the assertion's date+ lotSubHint -- lot subaccount hint (empty for non-lot accounts)++ where+ acct = T.unpack $ paccount p+ ass = fromJust $ pbalanceassertion p -- PARTIAL: fromJust won't fail, there is a balance assertion+ pos = baposition ass+ (_,_,_,ex) = makeBalanceAssertionErrorExcerpt p+ assertedcommstr = if T.null assertedcomm then "\"\"" else assertedcomm+ fmt = oneLineFmt{displayZeroCommodity=True}+ (assertedstr, actualstr) =+ showAmountsDistinctly fmt assertedcommbalcostless actualcommbalcostless+ diffstr = showAmountWith fmt $ assertedcommbalcostless - actualcommbalcostless+ pad = fitText (Just w) Nothing False False . T.pack where w = max (length assertedstr) (length actualstr)+ -- If this is a lot subaccount assertion, remind that balance assertions generally+ -- don't work on lot subaccounts. (#2659)+ lotSubHint+ | isLotSub =+ "\n\nNote '" ++ T.unpack assertedacct ++ "' is a lot subaccount.\n"+ ++ "Balance assertions aren't supported here unless all postings\n"+ ++ "to this lot mention the lot subaccount name explicitly.\n"+ ++ "So it's probably best to avoid using balance assertions on this account.\n"+ ++ "If needed, you could assert the parent account's balance instead."+ | otherwise = ""+ where+ isLotSub = assertedacct /= lotBaseAccount assertedacct++ unless pass $ throwError errmsg+{- XXX+When the posting amount has a cost, the highlight region expands to the full line:++*** Exception: Error: /Users/simon/src/hledger/2024-01-21.j:12:69:+ | 2023-12-31 closing balances+12 | assets:cash:petty:saved:rent -4.00 EUR @ 2 UAH == 0.00 EUR+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+ | equity:opening/closing balances 8 UAH++Maybe it's better than the normal region ?++*** Exception: Error: /Users/simon/src/hledger/2024-01-21.j:12:61:+ | 2023-12-31 closing balances+12 | assets:cash:petty:saved:rent -4.00 EUR == 0.00 EUR @ 3 UAH+ | ^^^^^^^^^^^^^^^^^^^+ | equity:opening/closing balances 4.00 EUR++If changed also check flycheck-hledger, which currently highlights the equals:++ assets:cash:petty:saved:rent -4.00 EUR @ 2 UAH == 0.00 EUR @ 3 UAH + --+-}++-- | Throw an error if this posting is trying to do an illegal balance assignment.+checkIllegalBalanceAssignmentB :: Posting -> Balancing s ()+checkIllegalBalanceAssignmentB p = do+ checkBalanceAssignmentPostingDateB p+ checkBalanceAssignmentUnassignableAccountB p++-- XXX these should show position. annotateErrorWithTransaction t ?++-- | Throw an error if this posting is trying to do a balance assignment and+-- has a custom posting date (which makes amount inference too hard/impossible).+checkBalanceAssignmentPostingDateB :: Posting -> Balancing s ()+checkBalanceAssignmentPostingDateB p =+ when (hasBalanceAssignment p && isJust (pdate p)) $+ throwError $ chomp $ unlines [+ "Balance assignments and custom posting dates may not be combined."+ ,""+ ,chomp1 $ T.unpack $ maybe (T.unlines $ showPostingLines p) showTransaction $ ptransaction p+ ,"Balance assignments may not be used on postings with a custom posting date"+ ,"(it makes balancing the journal impossible)."+ ,"Please write the posting amount explicitly (or remove the posting date)."+ ]++-- | Throw an error if this posting is trying to do a balance assignment and+-- the account does not allow balance assignments (eg because it is referenced+-- by an auto posting rule, which might generate additional postings to it).+checkBalanceAssignmentUnassignableAccountB :: Posting -> Balancing s ()+checkBalanceAssignmentUnassignableAccountB p = do+ unassignable <- R.asks bsUnassignable+ when (hasBalanceAssignment p && paccount p `S.member` unassignable) $+ throwError $ chomp $ unlines [+ "Balance assignments and auto postings may not be combined."+ ,""+ ,chomp1 $ T.unpack $ maybe (T.unlines $ showPostingLines p) (showTransaction) $ ptransaction p+ ,"Balance assignments may not be used on accounts affected by auto posting rules"+ ,"(it makes balancing the journal impossible)."+ ,"Please write the posting amount explicitly (or remove the auto posting rule(s))."+ ]++-- lenses++makeHledgerClassyLenses ''BalancingOpts++-- tests++tests_Balancing :: TestTree+tests_Balancing =+ testGroup "Balancing" [++ testCase "transactionInferBalancingAmount" $ do+ (fst <$> transactionInferBalancingAmount M.empty M.empty nulltransaction) @?= Right nulltransaction+ (fst <$> transactionInferBalancingAmount M.empty M.empty nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` missingamt]}) @?=+ Right nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` usd 5]}+ (fst <$> transactionInferBalancingAmount M.empty M.empty nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` (eur 3 @@ usd 4), "c" `post` missingamt]}) @?=+ Right nulltransaction{tpostings = ["a" `post` usd (-5), "b" `post` (eur 3 @@ usd 4), "c" `post` usd 1]}++ , testGroup "balanceSingleTransaction" [+ testCase "detect unbalanced entry, sign error" $+ assertLeft+ (balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ "test"+ ""+ []+ [posting {paccount = "a", pamount = mixedAmount (usd 1)}, posting {paccount = "b", pamount = mixedAmount (usd 1)}]))+ ,testCase "detect unbalanced entry, multiple missing amounts" $+ assertLeft $+ balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ "test"+ ""+ []+ [ posting {paccount = "a", pamount = missingmixedamt}+ , posting {paccount = "b", pamount = missingmixedamt}+ ])+ ,testCase "one missing amount is inferred" $+ (pamount . last . tpostings <$>+ balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ ""+ ""+ []+ [posting {paccount = "a", pamount = mixedAmount (usd 1)}, posting {paccount = "b", pamount = missingmixedamt}])) @?=+ Right (mixedAmount $ usd (-1))+ ,testCase "conversion price is inferred" $+ (pamount . headErr . tpostings <$> -- PARTIAL headErr succeeds because non-null postings list+ balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ ""+ ""+ []+ [ posting {paccount = "a", pamount = mixedAmount (usd 1.35)}+ , posting {paccount = "b", pamount = mixedAmount (eur (-1))}+ ])) @?=+ Right (mixedAmount $ usd 1.35 @@ eur 1)+ ,testCase "balanceSingleTransaction balances based on cost if there are unit prices" $+ assertRight $+ balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2011 01 01)+ Nothing+ Unmarked+ ""+ ""+ ""+ []+ [ posting {paccount = "a", pamount = mixedAmount $ usd 1 `at` eur 2}+ , posting {paccount = "a", pamount = mixedAmount $ usd (-2) `at` eur 1}+ ])+ ,testCase "balanceSingleTransaction balances based on cost if there are total prices" $+ assertRight $+ balanceSingleTransaction defbalancingopts+ (Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2011 01 01)+ Nothing+ Unmarked+ ""+ ""+ ""+ []+ [ posting {paccount = "a", pamount = mixedAmount $ usd 1 @@ eur 1}+ , posting {paccount = "a", pamount = mixedAmount $ usd (-2) @@ eur (-1)}+ ])+ ]+ , testGroup "isTransactionBalanced" [+ testCase "detect balanced" $+ assertBool "" $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}+ , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}+ ]+ ,testCase "detect unbalanced" $+ assertBool "" $+ not $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}+ , posting {paccount = "c", pamount = mixedAmount (usd (-1.01))}+ ]+ ,testCase "detect unbalanced, one posting" $+ assertBool "" $+ not $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [posting {paccount = "b", pamount = mixedAmount (usd 1.00)}]+ ,testCase "one zero posting is considered balanced for now" $+ assertBool "" $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [posting {paccount = "b", pamount = mixedAmount (usd 0)}]+ ,testCase "virtual postings don't need to balance" $+ assertBool "" $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}+ , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}+ , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = VirtualPosting}+ ]+ ,testCase "balanced virtual postings need to balance among themselves" $+ assertBool "" $+ not $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}+ , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}+ , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}+ ]+ ,testCase "balanced virtual postings need to balance among themselves (2)" $+ assertBool "" $+ isTransactionBalanced defbalancingopts $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2009 01 01)+ Nothing+ Unmarked+ ""+ "a"+ ""+ []+ [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}+ , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}+ , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}+ , posting {paccount = "3", pamount = mixedAmount (usd (-100)), preal = BalancedVirtualPosting}+ ]+ ]++ ,testGroup "journalBalanceTransactions" [++ testCase "missing-amounts" $ do+ let ej = journalBalanceTransactions defbalancingopts $ samplejournalMaybeExplicit False+ assertRight ej+ journalPostings <$> ej @?= Right (journalPostings samplejournal)++ ,testCase "balance-assignment" $ do+ let ej = journalBalanceTransactions defbalancingopts $+ --2019/01/01+ -- (a) = 1+ nulljournal{ jtxns = [+ transaction (fromGregorian 2019 01 01) [ vpost' "a" missingamt (balassert (num 1)) ]+ ]}+ assertRight ej+ case ej of Right j -> (jtxns j & headErr & tpostings & headErr & pamount & amountsRaw) @?= [num 1] -- PARTIAL headErrs succeed because non-null txns & postings lists given+ Left _ -> error' "balance-assignment test: shouldn't happen"++ ,testCase "same-day-1" $ do+ assertRight $ journalBalanceTransactions defbalancingopts $+ --2019/01/01+ -- (a) = 1+ --2019/01/01+ -- (a) 1 = 2+ nulljournal{ jtxns = [+ transaction (fromGregorian 2019 01 01) [ vpost' "a" missingamt (balassert (num 1)) ]+ ,transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 1) (balassert (num 2)) ]+ ]}++ ,testCase "same-day-2" $ do+ assertRight $ journalBalanceTransactions defbalancingopts $+ --2019/01/01+ -- (a) 2 = 2+ --2019/01/01+ -- b 1+ -- a+ --2019/01/01+ -- a 0 = 1+ nulljournal{ jtxns = [+ transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 2) (balassert (num 2)) ]+ ,transaction (fromGregorian 2019 01 01) [+ post' "b" (num 1) Nothing+ ,post' "a" missingamt Nothing+ ]+ ,transaction (fromGregorian 2019 01 01) [ post' "a" (num 0) (balassert (num 1)) ]+ ]}++ ,testCase "out-of-order" $ do+ assertRight $ journalBalanceTransactions defbalancingopts $+ --2019/1/2+ -- (a) 1 = 2+ --2019/1/1+ -- (a) 1 = 1+ nulljournal{ jtxns = [+ transaction (fromGregorian 2019 01 02) [ vpost' "a" (num 1) (balassert (num 2)) ]+ ,transaction (fromGregorian 2019 01 01) [ vpost' "a" (num 1) (balassert (num 1)) ]+ ]}++ ]++ ,testGroup "transactionCheckAssertions" $ [+ testCase "simple assertion on same day" $ do + assertRight $ + transactionCheckAssertions defbalancingopts nulljournal{ jtxns = [+ transaction (fromGregorian 2025 01 01) [ vpost' "a" (usd 1) Nothing ]+ ] } (transaction (fromGregorian 2025 01 01) [ vpost' "a" (usd 1) (balassert (usd 2)) ])++ ,testCase "inclusive assertions" $ do + assertRight $ + transactionCheckAssertions defbalancingopts nulljournal{ jtxns = [+ transaction (fromGregorian 2025 01 01) [ vpost' "a:a" (usd 1) Nothing ] + ,transaction (fromGregorian 2025 01 02) [ vpost' "a:b" (usd 2) Nothing]+ ,transaction (fromGregorian 2025 01 02) [ vpost' "a:c" (usd 5) Nothing]+ ,transaction (fromGregorian 2025 01 03) [ vpost' "a:d" (eur 10) Nothing]+ ] } (transaction (fromGregorian 2025 01 04) [ vpost' "a" (usd 2) (balassertParInc (usd 10))])++ ,testCase "multicommodity assertion" $ do + assertRight $ + transactionCheckAssertions defbalancingopts nulljournal{ jtxns = [+ transaction (fromGregorian 2025 01 01) [ vpost' "a" (usd 1) Nothing ] + ,transaction (fromGregorian 2025 01 02) [ vpost' "a:b" (eur 2) Nothing ]+ ,transaction (fromGregorian 2025 01 02) [ vpost' "a:c" (usd 5) Nothing ]+ ,transaction (fromGregorian 2025 01 03) [ vpost' "a:b" (eur (-2)) Nothing ]+ ] } (transaction (fromGregorian 2025 01 03) [ vpost' "a" (usd 2) (balassertTotInc (usd 8)) ])+ ]++ ,testGroup "commodityStylesFromAmounts" $ [++ -- Journal similar to the one on #1091:+ -- 2019/09/24+ -- (a) 1,000.00+ -- + -- 2019/09/26+ -- (a) 1000,000+ --+ testCase "1091a" $ do+ commodityStylesFromAmounts [+ nullamt{aquantity=1000, astyle=AmountStyle L False Nothing (Just ',') (Precision 3) NoRounding}+ ,nullamt{aquantity=1000, astyle=AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 2) NoRounding}+ ]+ @?=+ -- The commodity style should have period as decimal mark+ -- and comma as digit group mark.+ Right (M.fromList [+ ("", AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 3) NoRounding)+ ])+ -- same journal, entries in reverse order+ ,testCase "1091b" $ do+ commodityStylesFromAmounts [+ nullamt{aquantity=1000, astyle=AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 2) NoRounding}+ ,nullamt{aquantity=1000, astyle=AmountStyle L False Nothing (Just ',') (Precision 3) NoRounding}+ ]+ @?=+ -- The commodity style should have period as decimal mark+ -- and comma as digit group mark.+ Right (M.fromList [+ ("", AmountStyle L False (Just (DigitGroups ',' [3])) (Just '.') (Precision 3) NoRounding)+ ])++ ]++ ]
− Hledger/Data/Commodity.hs
@@ -1,67 +0,0 @@-{-|--A 'Commodity' is a symbol representing a currency or some other kind of-thing we are tracking, and some display preferences that tell how to-display 'Amount's of the commodity - is the symbol on the left or right,-are thousands separated by comma, significant decimal places and so on.---}-module Hledger.Data.Commodity-where-import Data.List-import Data.Map ((!))-import Data.Maybe-import Test.HUnit-import qualified Data.Map as Map--import Hledger.Data.Types-import Hledger.Utils---nonsimplecommoditychars = "0123456789-.@;\n \""--quoteCommoditySymbolIfNeeded s | any (`elem` nonsimplecommoditychars) s = "\"" ++ s ++ "\""- | otherwise = s---- convenient amount and commodity constructors, for tests etc.--unknown = Commodity {symbol="", side=L,spaced=False,decimalpoint='.',precision=0,separator=',',separatorpositions=[]}-dollar = Commodity {symbol="$",side=L,spaced=False,decimalpoint='.',precision=2,separator=',',separatorpositions=[]}-euro = Commodity {symbol="€",side=L,spaced=False,decimalpoint='.',precision=2,separator=',',separatorpositions=[]}-pound = Commodity {symbol="£",side=L,spaced=False,decimalpoint='.',precision=2,separator=',',separatorpositions=[]}-hour = Commodity {symbol="h",side=R,spaced=False,decimalpoint='.',precision=1,separator=',',separatorpositions=[]}--dollars n = Amount dollar n Nothing-euros n = Amount euro n Nothing-pounds n = Amount pound n Nothing-hours n = Amount hour n Nothing--defaultcommodities = [dollar, euro, pound, hour, unknown]---- | Look up one of the hard-coded default commodities. For use in tests.-comm :: String -> Commodity-comm sym = fromMaybe - (error' "commodity lookup failed") - $ find (\(Commodity{symbol=s}) -> s==sym) defaultcommodities---- | Find the conversion rate between two commodities. Currently returns 1.-conversionRate :: Commodity -> Commodity -> Double-conversionRate _ _ = 1---- | Convert a list of commodities to a map from commodity symbols to--- unique, display-preference-canonicalised commodities.-canonicaliseCommodities :: [Commodity] -> Map.Map String Commodity-canonicaliseCommodities cs =- Map.fromList [(s,firstc{precision=maxp}) | s <- symbols,- let cs = commoditymap ! s,- let firstc = head cs,- let maxp = maximum $ map precision cs- ]- where- commoditymap = Map.fromList [(s, commoditieswithsymbol s) | s <- symbols]- commoditieswithsymbol s = filter ((s==) . symbol) cs- symbols = nub $ map symbol cs--tests_Hledger_Data_Commodity = TestList [- ]-
+ Hledger/Data/Currency.hs view
@@ -0,0 +1,196 @@+{-|++Currency names, symbols and codes.+Reference:+- https://www.xe.com/symbols+- https://www.xe.com/currency++-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.Currency (+ CurrencyCode,+ CurrencySymbol,+ currencies,+ cryptocurrencies,+ currencySymbolToCode,+ currencyCodeToSymbol,+ toCurrencyCode,+)+where+import Data.Map qualified as M+import Data.Maybe (fromMaybe)+import Data.Text (Text)++-- | An ISO 4217 currency code, like EUR.+-- Generally used for fiat currencies, but may also use the X* convention for non-country currencies+-- (eg XAU, XBT), or ISO 20022 cryptocurrency codes (eg ADA).+type CurrencyCode = Text++-- | A traditional currency symbol like $ or ¥ (as opposed to a currency code like USD or JPY).+-- Usually one character, sometimes more, like C$ or BZ$.+type CurrencySymbol = Text++-- | Look for a currency code corresponding to this currency symbol.+--+-- >>> currencySymbolToCode ""+-- Nothing+-- >>> currencySymbolToCode "$"+-- Just "USD"+currencySymbolToCode :: CurrencySymbol -> Maybe CurrencyCode+currencySymbolToCode s = M.lookup s currencyCodesBySymbol++-- | Look for a currency symbol corresponding to this currency code.+--+-- >>> currencyCodeToSymbol "CZK" -- Just "Kč"+-- Just "K\269"+currencyCodeToSymbol :: CurrencyCode -> Maybe CurrencySymbol+currencyCodeToSymbol c = M.lookup c currencySymbolsByCode++-- | Like 'currencySymbolToCode', but return the input unchanged if no ISO+-- code is known. Useful for normalising free-form commodity labels: known+-- currency symbols become ISO codes, while tickers/abbreviations pass through.+--+-- >>> toCurrencyCode "$"+-- "USD"+-- >>> toCurrencyCode "BTC"+-- "BTC"+toCurrencyCode :: CurrencySymbol -> CurrencyCode+toCurrencyCode s = fromMaybe s (currencySymbolToCode s)++currencyCodesBySymbol = M.fromList [(s,c) | (_,c,s) <- currencies]+currencySymbolsByCode = M.fromList [(c,s) | (_,c,s) <- currencies]++currencies = [+ -- country and currency name ISO 4217 code symbol+ ("Albania Lek", "ALL", "Lek"),+ ("Afghanistan Afghani", "AFN", "؋"),+ ("Argentina Peso", "ARS", "$"),+ ("Aruba Guilder", "AWG", "ƒ"),+ ("Australia Dollar", "AUD", "$"),+ ("Azerbaijan Manat", "AZN", "₼"),+ ("Bahamas Dollar", "BSD", "$"),+ ("Barbados Dollar", "BBD", "$"),+ ("Belarus Ruble", "BYN", "Br"),+ ("Belize Dollar", "BZD", "BZ$"),+ ("Bermuda Dollar", "BMD", "$"),+ ("Bolivia Bolíviano", "BOB", "$b"),+ ("Bosnia and Herzegovina Convertible Mark", "BAM", "KM"),+ ("Botswana Pula", "BWP", "P"),+ ("Bulgaria Lev", "BGN", "лв"),+ ("Brazil Real", "BRL", "R$"),+ ("Brunei Darussalam Dollar", "BND", "$"),+ ("Cambodia Riel", "KHR", "៛"),+ ("Canada Dollar", "CAD", "$"),+ ("Cayman Islands Dollar", "KYD", "$"),+ ("Chile Peso", "CLP", "$"),+ ("China Yuan Renminbi", "CNY", "¥"),+ ("Colombia Peso", "COP", "$"),+ ("Costa Rica Colon", "CRC", "₡"),+ ("Croatia Kuna", "HRK", "kn"),+ ("Cuba Peso", "CUP", "₱"),+ ("Czech Republic Koruna", "CZK", "Kč"),+ ("Denmark Krone", "DKK", "kr"),+ ("Dominican Republic Peso", "DOP", "RD$"),+ ("East Caribbean Dollar", "XCD", "$"),+ ("Egypt Pound", "EGP", "£"),+ ("El Salvador Colon", "SVC", "$"),+ ("Euro Member Countries", "EUR", "€"),+ ("Falkland Islands (Malvinas) Pound", "FKP", "£"),+ ("Fiji Dollar", "FJD", "$"),+ ("Ghana Cedi", "GHS", "¢"),+ ("Gibraltar Pound", "GIP", "£"),+ ("Guatemala Quetzal", "GTQ", "Q"),+ ("Guernsey Pound", "GGP", "£"),+ ("Guyana Dollar", "GYD", "$"),+ ("Honduras Lempira", "HNL", "L"),+ ("Hong Kong Dollar", "HKD", "$"),+ ("Hungary Forint", "HUF", "Ft"),+ ("Iceland Krona", "ISK", "kr"),+ ("India Rupee", "INR", "₹"),+ ("Indonesia Rupiah", "IDR", "Rp"),+ ("Iran Rial", "IRR", "﷼"),+ ("Isle of Man Pound", "IMP", "£"),+ ("Israel Shekel", "ILS", "₪"),+ ("Jamaica Dollar", "JMD", "J$"),+ ("Japan Yen", "JPY", "¥"),+ ("Jersey Pound", "JEP", "£"),+ ("Kazakhstan Tenge", "KZT", "лв"),+ ("Korea (North) Won", "KPW", "₩"),+ ("Korea (South) Won", "KRW", "₩"),+ ("Kyrgyzstan Som", "KGS", "лв"),+ ("Laos Kip", "LAK", "₭"),+ ("Lebanon Pound", "LBP", "£"),+ ("Liberia Dollar", "LRD", "$"),+ ("Macedonia Denar", "MKD", "ден"),+ ("Malaysia Ringgit", "MYR", "RM"),+ ("Mauritius Rupee", "MUR", "₨"),+ ("Mexico Peso", "MXN", "$"),+ ("Mongolia Tughrik", "MNT", "₮"),+ ("Mozambique Metical", "MZN", "MT"),+ ("Namibia Dollar", "NAD", "$"),+ ("Nepal Rupee", "NPR", "₨"),+ ("Netherlands Antilles Guilder", "ANG", "ƒ"),+ ("New Zealand Dollar", "NZD", "$"),+ ("Nicaragua Cordoba", "NIO", "C$"),+ ("Nigeria Naira", "NGN", "₦"),+ ("Norway Krone", "NOK", "kr"),+ ("Oman Rial", "OMR", "﷼"),+ ("Pakistan Rupee", "PKR", "₨"),+ ("Panama Balboa", "PAB", "B/."),+ ("Paraguay Guarani", "PYG", "Gs"),+ ("Peru Sol", "PEN", "S/."),+ ("Philippines Peso", "PHP", "₱"),+ ("Poland Zloty", "PLN", "zł"),+ ("Qatar Riyal", "QAR", "﷼"),+ ("Romania Leu", "RON", "lei"),+ ("Russia Ruble", "RUB", "₽"),+ ("Saint Helena Pound", "SHP", "£"),+ ("Saudi Arabia Riyal", "SAR", "﷼"),+ ("Serbia Dinar", "RSD", "Дин."),+ ("Seychelles Rupee", "SCR", "₨"),+ ("Singapore Dollar", "SGD", "$"),+ ("Solomon Islands Dollar", "SBD", "$"),+ ("Somalia Shilling", "SOS", "S"),+ ("South Africa Rand", "ZAR", "R"),+ ("Sri Lanka Rupee", "LKR", "₨"),+ ("Sweden Krona", "SEK", "kr"),+ ("Switzerland Franc", "CHF", "CHF"),+ ("Suriname Dollar", "SRD", "$"),+ ("Syria Pound", "SYP", "£"),+ ("Taiwan New Dollar", "TWD", "NT$"),+ ("Thailand Baht", "THB", "฿"),+ ("Trinidad and Tobago Dollar", "TTD", "TT$"),+ ("Turkey Lira", "TRY", "₺"),+ ("Tuvalu Dollar", "TVD", "$"),+ ("Ukraine Hryvnia", "UAH", "₴"),+ ("United Kingdom Pound", "GBP", "£"),+ ("United States Dollar", "USD", "$"),+ ("Uruguay Peso", "UYU", "$U"),+ ("Uzbekistan Som", "UZS", "лв"),+ ("Venezuela Bolívar", "VEF", "Bs"),+ ("Viet Nam Dong", "VND", "₫"),+ ("Yemen Rial", "YER", "﷼"),+ ("Zimbabwe Dollar", "ZWD", "Z$")+ ]++-- | The top 100 cryptocurrencies by market capitalisation, as ticker+-- symbols, in descending rank order. Snapshot taken from the CoinGecko+-- public API on 2026-04-30:+-- https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1+cryptocurrencies :: [CurrencyCode]+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"+ ]++-- tests_Currency = testGroup "Currency" []
Hledger/Data/Dates.hs view
@@ -1,685 +1,1308 @@-{-|--Date parsing and utilities for hledger.--For date and time values, we use the standard Day and UTCTime types.--A 'SmartDate' is a date which may be partially-specified or relative.-Eg 2008\/12\/31, but also 2008\/12, 12\/31, tomorrow, last week, next year.-We represent these as a triple of strings like (\"2008\",\"12\",\"\"),-(\"\",\"\",\"tomorrow\"), (\"\",\"last\",\"week\").--A 'DateSpan' is the span of time between two specific calendar dates, or-an open-ended span where one or both dates are unspecified. (A date span-with both ends unspecified matches all dates.)--An 'Interval' is ledger's \"reporting interval\" - weekly, monthly,-quarterly, etc.---}---- XXX fromGregorian silently clips bad dates, use fromGregorianValid instead ?--module Hledger.Data.Dates-where--import Control.Monad-import Data.List-import Data.Maybe-import Data.Time.Format-import Data.Time.Calendar-import Data.Time.Calendar.OrdinalDate-import Data.Time.Clock-import Data.Time.LocalTime-import Safe (readMay)-import System.Locale (defaultTimeLocale)-import Test.HUnit-import Text.ParserCombinators.Parsec-import Text.Printf--import Hledger.Data.Types-import Hledger.Utils---showDate :: Day -> String-showDate = formatTime defaultTimeLocale "%C%y/%m/%d"---- | Get the current local date.-getCurrentDay :: IO Day-getCurrentDay = do- t <- getZonedTime- return $ localDay (zonedTimeToLocalTime t)---- | Get the current local month number.-getCurrentMonth :: IO Int-getCurrentMonth = do- (_,m,_) <- toGregorian `fmap` getCurrentDay- return m---- | Get the current local year.-getCurrentYear :: IO Integer-getCurrentYear = do- (y,_,_) <- toGregorian `fmap` getCurrentDay- return y--elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a-elapsedSeconds t1 = realToFrac . diffUTCTime t1---- | Split a DateSpan into one or more consecutive spans at the specified interval.-splitSpan :: Interval -> DateSpan -> [DateSpan]-splitSpan _ (DateSpan Nothing Nothing) = [DateSpan Nothing Nothing]-splitSpan NoInterval s = [s]-splitSpan (Days n) s = splitspan startofday (applyN n nextday) s-splitSpan (Weeks n) s = splitspan startofweek (applyN n nextweek) s-splitSpan (Months n) s = splitspan startofmonth (applyN n nextmonth) s-splitSpan (Quarters n) s = splitspan startofquarter (applyN n nextquarter) s-splitSpan (Years n) s = splitspan startofyear (applyN n nextyear) s-splitSpan (DayOfMonth n) s = splitspan (nthdayofmonthcontaining n) (applyN (n-1) nextday . nextmonth) s-splitSpan (DayOfWeek n) s = splitspan (nthdayofweekcontaining n) (applyN (n-1) nextday . nextweek) s--- splitSpan (WeekOfYear n) s = splitspan startofweek (applyN n nextweek) s--- splitSpan (MonthOfYear n) s = splitspan startofmonth (applyN n nextmonth) s--- splitSpan (QuarterOfYear n) s = splitspan startofquarter (applyN n nextquarter) s---- Split the given span using the provided helper functions:--- start is applied to the span's start date to get the first sub-span's start date--- next is applied to a sub-span's start date to get the next sub-span's start date-splitspan :: (Day -> Day) -> (Day -> Day) -> DateSpan -> [DateSpan]-splitspan _ _ (DateSpan Nothing Nothing) = []-splitspan start next (DateSpan Nothing (Just e)) = splitspan start next (DateSpan (Just $ start e) (Just $ next $ start e))-splitspan start next (DateSpan (Just s) Nothing) = splitspan start next (DateSpan (Just $ start s) (Just $ next $ start s))-splitspan start next span@(DateSpan (Just s) (Just e))- | s == e = [span]- | otherwise = splitspan' start next span- where- splitspan' start next (DateSpan (Just s) (Just e))- | s >= e = []- | otherwise = DateSpan (Just subs) (Just sube) : splitspan' start next (DateSpan (Just sube) (Just e))- where subs = start s- sube = next subs- splitspan' _ _ _ = error' "won't happen, avoids warnings"---- | Count the days in a DateSpan, or if it is open-ended return Nothing.-daysInSpan :: DateSpan -> Maybe Integer-daysInSpan (DateSpan (Just d1) (Just d2)) = Just $ diffDays d2 d1-daysInSpan _ = Nothing---- | Does the span include the given date ?-spanContainsDate :: DateSpan -> Day -> Bool-spanContainsDate (DateSpan Nothing Nothing) _ = True-spanContainsDate (DateSpan Nothing (Just e)) d = d < e-spanContainsDate (DateSpan (Just b) Nothing) d = d >= b-spanContainsDate (DateSpan (Just b) (Just e)) d = d >= b && d < e- --- | Combine two datespans, filling any unspecified dates in the first--- with dates from the second.-orDatesFrom (DateSpan a1 b1) (DateSpan a2 b2) = DateSpan a b- where a = if isJust a1 then a1 else a2- b = if isJust b1 then b1 else b2---- | Calculate the intersection of two datespans.-spanIntersect (DateSpan b1 e1) (DateSpan b2 e2) = DateSpan b e- where- b = latest b1 b2- e = earliest e1 e2--latest d Nothing = d-latest Nothing d = d-latest (Just d1) (Just d2) = Just $ max d1 d2--earliest d Nothing = d-earliest Nothing d = d-earliest (Just d1) (Just d2) = Just $ min d1 d2---- | Parse a period expression to an Interval and overall DateSpan using--- the provided reference date, or return a parse error.-parsePeriodExpr :: Day -> String -> Either ParseError (Interval, DateSpan)-parsePeriodExpr refdate = parsewith (periodexpr refdate)--maybePeriod :: Day -> String -> Maybe (Interval,DateSpan)-maybePeriod refdate = either (const Nothing) Just . parsePeriodExpr refdate---- | Show a DateSpan as a human-readable pseudo-period-expression string.-dateSpanAsText :: DateSpan -> String-dateSpanAsText (DateSpan Nothing Nothing) = "all"-dateSpanAsText (DateSpan Nothing (Just e)) = printf "to %s" (show e)-dateSpanAsText (DateSpan (Just b) Nothing) = printf "from %s" (show b)-dateSpanAsText (DateSpan (Just b) (Just e)) = printf "%s to %s" (show b) (show e)- --- | Convert a single smart date string to a date span using the provided--- reference date, or raise an error.-spanFromSmartDateString :: Day -> String -> DateSpan-spanFromSmartDateString refdate s = spanFromSmartDate refdate sdate- where- sdate = fromparse $ parsewith smartdateonly s--spanFromSmartDate :: Day -> SmartDate -> DateSpan-spanFromSmartDate refdate sdate = DateSpan (Just b) (Just e)- where- (ry,rm,_) = toGregorian refdate- (b,e) = span sdate- span :: SmartDate -> (Day,Day)- span ("","","today") = (refdate, nextday refdate)- span ("","this","day") = (refdate, nextday refdate)- span ("","","yesterday") = (prevday refdate, refdate)- span ("","last","day") = (prevday refdate, refdate)- span ("","","tomorrow") = (nextday refdate, addDays 2 refdate)- span ("","next","day") = (nextday refdate, addDays 2 refdate)- span ("","last","week") = (prevweek refdate, thisweek refdate)- span ("","this","week") = (thisweek refdate, nextweek refdate)- span ("","next","week") = (nextweek refdate, startofweek $ addDays 14 refdate)- span ("","last","month") = (prevmonth refdate, thismonth refdate)- span ("","this","month") = (thismonth refdate, nextmonth refdate)- span ("","next","month") = (nextmonth refdate, startofmonth $ addGregorianMonthsClip 2 refdate)- span ("","last","quarter") = (prevquarter refdate, thisquarter refdate)- span ("","this","quarter") = (thisquarter refdate, nextquarter refdate)- span ("","next","quarter") = (nextquarter refdate, startofquarter $ addGregorianMonthsClip 6 refdate)- span ("","last","year") = (prevyear refdate, thisyear refdate)- span ("","this","year") = (thisyear refdate, nextyear refdate)- span ("","next","year") = (nextyear refdate, startofyear $ addGregorianYearsClip 2 refdate)- span ("","",d) = (day, nextday day) where day = fromGregorian ry rm (read d)- span ("",m,"") = (startofmonth day, nextmonth day) where day = fromGregorian ry (read m) 1- span ("",m,d) = (day, nextday day) where day = fromGregorian ry (read m) (read d)- span (y,"","") = (startofyear day, nextyear day) where day = fromGregorian (read y) 1 1- span (y,m,"") = (startofmonth day, nextmonth day) where day = fromGregorian (read y) (read m) 1- span (y,m,d) = (day, nextday day) where day = fromGregorian (read y) (read m) (read d)--showDay :: Day -> String-showDay day = printf "%04d/%02d/%02d" y m d where (y,m,d) = toGregorian day---- | Convert a smart date string to an explicit yyyy\/mm\/dd string using--- the provided reference date, or raise an error.-fixSmartDateStr :: Day -> String -> String-fixSmartDateStr d s = either- (\e->error' $ printf "could not parse date %s %s" (show s) (show e))- id- $ fixSmartDateStrEither d s---- | A safe version of fixSmartDateStr.-fixSmartDateStrEither :: Day -> String -> Either ParseError String-fixSmartDateStrEither d = either Left (Right . showDate) . fixSmartDateStrEither' d--fixSmartDateStrEither' :: Day -> String -> Either ParseError Day-fixSmartDateStrEither' d s = case parsewith smartdateonly (lowercase s) of- Right sd -> Right $ fixSmartDate d sd- Left e -> Left e---- | Convert a SmartDate to an absolute date using the provided reference date.-fixSmartDate :: Day -> SmartDate -> Day-fixSmartDate refdate sdate = fix sdate- where- fix :: SmartDate -> Day- fix ("","","today") = fromGregorian ry rm rd- fix ("","this","day") = fromGregorian ry rm rd- fix ("","","yesterday") = prevday refdate- fix ("","last","day") = prevday refdate- fix ("","","tomorrow") = nextday refdate- fix ("","next","day") = nextday refdate- fix ("","last","week") = prevweek refdate- fix ("","this","week") = thisweek refdate- fix ("","next","week") = nextweek refdate- fix ("","last","month") = prevmonth refdate- fix ("","this","month") = thismonth refdate- fix ("","next","month") = nextmonth refdate- fix ("","last","quarter") = prevquarter refdate- fix ("","this","quarter") = thisquarter refdate- fix ("","next","quarter") = nextquarter refdate- fix ("","last","year") = prevyear refdate- fix ("","this","year") = thisyear refdate- fix ("","next","year") = nextyear refdate- fix ("","",d) = fromGregorian ry rm (read d)- fix ("",m,"") = fromGregorian ry (read m) 1- fix ("",m,d) = fromGregorian ry (read m) (read d)- fix (y,"","") = fromGregorian (read y) 1 1- fix (y,m,"") = fromGregorian (read y) (read m) 1- fix (y,m,d) = fromGregorian (read y) (read m) (read d)- (ry,rm,rd) = toGregorian refdate--prevday :: Day -> Day-prevday = addDays (-1)-nextday = addDays 1-startofday = id--thisweek = startofweek-prevweek = startofweek . addDays (-7)-nextweek = startofweek . addDays 7-startofweek day = fromMondayStartWeek y w 1- where- (y,_,_) = toGregorian day- (w,_) = mondayStartWeek day--thismonth = startofmonth-prevmonth = startofmonth . addGregorianMonthsClip (-1)-nextmonth = startofmonth . addGregorianMonthsClip 1-startofmonth day = fromGregorian y m 1 where (y,m,_) = toGregorian day--thisquarter = startofquarter-prevquarter = startofquarter . addGregorianMonthsClip (-3)-nextquarter = startofquarter . addGregorianMonthsClip 3-startofquarter day = fromGregorian y (firstmonthofquarter m) 1- where- (y,m,_) = toGregorian day- firstmonthofquarter m = ((m-1) `div` 3) * 3 + 1--thisyear = startofyear-prevyear = startofyear . addGregorianYearsClip (-1)-nextyear = startofyear . addGregorianYearsClip 1-startofyear day = fromGregorian y 1 1 where (y,_,_) = toGregorian day--nthdayofmonthcontaining n d | d1 >= d = d1- | otherwise = d2- where d1 = addDays (fromIntegral n-1) s- d2 = addDays (fromIntegral n-1) $ nextmonth s- s = startofmonth d--nthdayofweekcontaining n d | d1 >= d = d1- | otherwise = d2- where d1 = addDays (fromIntegral n-1) s- d2 = addDays (fromIntegral n-1) $ nextweek s- s = startofweek d--------------------------------------------------------------------------- parsing--firstJust ms = case dropWhile (==Nothing) ms of- [] -> Nothing- (md:_) -> md---- | Parse a couple of date-time string formats to a time type.-parsedatetimeM :: String -> Maybe LocalTime-parsedatetimeM s = firstJust [- parseTime defaultTimeLocale "%Y/%m/%d %H:%M:%S" s,- parseTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" s- ]---- | Parse a couple of date string formats to a time type.-parsedateM :: String -> Maybe Day-parsedateM s = firstJust [ - parseTime defaultTimeLocale "%Y/%m/%d" s,- parseTime defaultTimeLocale "%Y-%m-%d" s - ]---- | Parse a date-time string to a time type, or raise an error.-parsedatetime :: String -> LocalTime-parsedatetime s = fromMaybe (error' $ "could not parse timestamp \"" ++ s ++ "\"")- (parsedatetimeM s)---- | Parse a date string to a time type, or raise an error.-parsedate :: String -> Day-parsedate s = fromMaybe (error' $ "could not parse date \"" ++ s ++ "\"")- (parsedateM s)---- | Parse a time string to a time type using the provided pattern, or--- return the default.-parsetimewith :: ParseTime t => String -> String -> t -> t-parsetimewith pat s def = fromMaybe def $ parseTime defaultTimeLocale pat s--{-| -Parse a date in any of the formats allowed in ledger's period expressions,-and maybe some others:--> 2004-> 2004/10-> 2004/10/1-> 10/1-> 21-> october, oct-> yesterday, today, tomorrow-> this/next/last week/day/month/quarter/year--Returns a SmartDate, to be converted to a full date later (see fixSmartDate).-Assumes any text in the parse stream has been lowercased.--}-smartdate :: GenParser Char st SmartDate-smartdate = do- -- XXX maybe obscures date errors ? see ledgerdate- (y,m,d) <- choice' [yyyymmdd, ymd, ym, md, y, d, month, mon, today, yesterday, tomorrow, lastthisnextthing]- return (y,m,d)---- | Like smartdate, but there must be nothing other than whitespace after the date.-smartdateonly :: GenParser Char st SmartDate-smartdateonly = do- d <- smartdate- many spacenonewline- eof- return d--datesepchars = "/-."-datesepchar = oneOf datesepchars--validYear, validMonth, validDay :: String -> Bool-validYear s = length s >= 4 && isJust (readMay s :: Maybe Int)-validMonth s = maybe False (\n -> n>=1 && n<=12) $ readMay s-validDay s = maybe False (\n -> n>=1 && n<=31) $ readMay s--failIfInvalidYear, failIfInvalidMonth, failIfInvalidDay :: (Monad m) => String -> m ()-failIfInvalidYear s = unless (validYear s) $ fail $ "bad year number: " ++ s-failIfInvalidMonth s = unless (validMonth s) $ fail $ "bad month number: " ++ s-failIfInvalidDay s = unless (validDay s) $ fail $ "bad day number: " ++ s--yyyymmdd :: GenParser Char st SmartDate-yyyymmdd = do- y <- count 4 digit- m <- count 2 digit- failIfInvalidMonth m- d <- count 2 digit- failIfInvalidDay d- return (y,m,d)--ymd :: GenParser Char st SmartDate-ymd = do- y <- many1 digit- failIfInvalidYear y- datesepchar- m <- many1 digit- failIfInvalidMonth m- datesepchar- d <- many1 digit- failIfInvalidDay d- return $ (y,m,d)--ym :: GenParser Char st SmartDate-ym = do- y <- many1 digit- failIfInvalidYear y- datesepchar- m <- many1 digit- failIfInvalidMonth m- return (y,m,"")--y :: GenParser Char st SmartDate-y = do- y <- many1 digit- failIfInvalidYear y- return (y,"","")--d :: GenParser Char st SmartDate-d = do- d <- many1 digit- failIfInvalidDay d- return ("","",d)--md :: GenParser Char st SmartDate-md = do- m <- many1 digit- failIfInvalidMonth m- datesepchar- d <- many1 digit- failIfInvalidDay d- return ("",m,d)--months = ["january","february","march","april","may","june",- "july","august","september","october","november","december"]-monthabbrevs = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]-weekdays = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]-weekdayabbrevs = ["mon","tue","wed","thu","fri","sat","sun"]--monthIndex s = maybe 0 (+1) $ lowercase s `elemIndex` months-monIndex s = maybe 0 (+1) $ lowercase s `elemIndex` monthabbrevs--month :: GenParser Char st SmartDate-month = do- m <- choice $ map (try . string) months- let i = monthIndex m- return ("",show i,"")--mon :: GenParser Char st SmartDate-mon = do- m <- choice $ map (try . string) monthabbrevs- let i = monIndex m- return ("",show i,"")--today,yesterday,tomorrow :: GenParser Char st SmartDate-today = string "today" >> return ("","","today")-yesterday = string "yesterday" >> return ("","","yesterday")-tomorrow = string "tomorrow" >> return ("","","tomorrow")--lastthisnextthing :: GenParser Char st SmartDate-lastthisnextthing = do- r <- choice [- string "last"- ,string "this"- ,string "next"- ]- many spacenonewline -- make the space optional for easier scripting- p <- choice [- string "day"- ,string "week"- ,string "month"- ,string "quarter"- ,string "year"- ]--- XXX support these in fixSmartDate--- ++ (map string $ months ++ monthabbrevs ++ weekdays ++ weekdayabbrevs)- - return ("",r,p)--periodexpr :: Day -> GenParser Char st (Interval, DateSpan)-periodexpr rdate = choice $ map try [- intervalanddateperiodexpr rdate,- intervalperiodexpr,- dateperiodexpr rdate,- (return (NoInterval,DateSpan Nothing Nothing))- ]--intervalanddateperiodexpr :: Day -> GenParser Char st (Interval, DateSpan)-intervalanddateperiodexpr rdate = do- many spacenonewline- i <- reportinginterval- many spacenonewline- s <- periodexprdatespan rdate- return (i,s)--intervalperiodexpr :: GenParser Char st (Interval, DateSpan)-intervalperiodexpr = do- many spacenonewline- i <- reportinginterval- return (i, DateSpan Nothing Nothing)--dateperiodexpr :: Day -> GenParser Char st (Interval, DateSpan)-dateperiodexpr rdate = do- many spacenonewline- s <- periodexprdatespan rdate- return (NoInterval, s)---- Parse a reporting interval.-reportinginterval :: GenParser Char st Interval-reportinginterval = choice' [- tryinterval "day" "daily" Days,- tryinterval "week" "weekly" Weeks,- tryinterval "month" "monthly" Months,- tryinterval "quarter" "quarterly" Quarters,- tryinterval "year" "yearly" Years,- do string "biweekly"- return $ Weeks 2,- do string "bimonthly"- return $ Months 2,- do string "every"- many spacenonewline- n <- fmap read $ many1 digit- thsuffix- many spacenonewline- string "day"- many spacenonewline- string "of"- many spacenonewline- string "week"- return $ DayOfWeek n,- do string "every"- many spacenonewline- n <- fmap read $ many1 digit- thsuffix- many spacenonewline- string "day"- optional $ do- many spacenonewline- string "of"- many spacenonewline- string "month"- return $ DayOfMonth n- ]- where-- thsuffix = choice' $ map string ["st","nd","rd","th"]-- -- Parse any of several variants of a basic interval, eg "daily", "every day", "every N days".- tryinterval :: String -> String -> (Int -> Interval) -> GenParser Char st Interval- tryinterval singular compact intcons =- choice' [- do string compact- return $ intcons 1,- do string "every"- many spacenonewline- string singular- return $ intcons 1,- do string "every"- many spacenonewline- n <- fmap read $ many1 digit- many spacenonewline- string plural- return $ intcons n- ]- where plural = singular ++ "s"--periodexprdatespan :: Day -> GenParser Char st DateSpan-periodexprdatespan rdate = choice $ map try [- doubledatespan rdate,- fromdatespan rdate,- todatespan rdate,- justdatespan rdate- ]--doubledatespan :: Day -> GenParser Char st DateSpan-doubledatespan rdate = do- optional (string "from" >> many spacenonewline)- b <- smartdate- many spacenonewline- optional (string "to" >> many spacenonewline)- e <- smartdate- return $ DateSpan (Just $ fixSmartDate rdate b) (Just $ fixSmartDate rdate e)--fromdatespan :: Day -> GenParser Char st DateSpan-fromdatespan rdate = do- string "from" >> many spacenonewline- b <- smartdate- return $ DateSpan (Just $ fixSmartDate rdate b) Nothing--todatespan :: Day -> GenParser Char st DateSpan-todatespan rdate = do- string "to" >> many spacenonewline- e <- smartdate- return $ DateSpan Nothing (Just $ fixSmartDate rdate e)--justdatespan :: Day -> GenParser Char st DateSpan-justdatespan rdate = do- optional (string "in" >> many spacenonewline)- d <- smartdate- return $ spanFromSmartDate rdate d---- | Make a datespan from two valid date strings parseable by parsedate--- (or raise an error). Eg: mkdatespan \"2011/1/1\" \"2011/12/31\".-mkdatespan :: String -> String -> DateSpan-mkdatespan b = DateSpan (Just $ parsedate b) . Just . parsedate--nulldatespan :: DateSpan-nulldatespan = DateSpan Nothing Nothing--nulldate :: Day-nulldate = parsedate "0000/00/00"--tests_Hledger_Data_Dates = TestList- [-- "parsedate" ~: do- let date1 = parsedate "2008/11/26"- parsedate "2008/02/03" `is` parsetimewith "%Y/%m/%d" "2008/02/03" date1- parsedate "2008-02-03" `is` parsetimewith "%Y/%m/%d" "2008/02/03" date1-- ,"period expressions" ~: do- let todaysdate = parsedate "2008/11/26"- let str `gives` result = show (parsewith (periodexpr todaysdate) str) `is` ("Right " ++ result)- "from aug to oct" `gives` "(NoInterval,DateSpan (Just 2008-08-01) (Just 2008-10-01))"- "aug to oct" `gives` "(NoInterval,DateSpan (Just 2008-08-01) (Just 2008-10-01))"- "every 3 days in aug" `gives` "(Days 3,DateSpan (Just 2008-08-01) (Just 2008-09-01))"- "daily from aug" `gives` "(Days 1,DateSpan (Just 2008-08-01) Nothing)"- "every week to 2009" `gives` "(Weeks 1,DateSpan Nothing (Just 2009-01-01))"-- ,"splitSpan" ~: do- let gives (interval, span) = (splitSpan interval span `is`)- (NoInterval,mkdatespan "2008/01/01" "2009/01/01") `gives`- [mkdatespan "2008/01/01" "2009/01/01"]- (Quarters 1,mkdatespan "2008/01/01" "2009/01/01") `gives`- [mkdatespan "2008/01/01" "2008/04/01"- ,mkdatespan "2008/04/01" "2008/07/01"- ,mkdatespan "2008/07/01" "2008/10/01"- ,mkdatespan "2008/10/01" "2009/01/01"- ]- (Quarters 1,nulldatespan) `gives`- [nulldatespan]- (Days 1,mkdatespan "2008/01/01" "2008/01/01") `gives`- [mkdatespan "2008/01/01" "2008/01/01"]- (Quarters 1,mkdatespan "2008/01/01" "2008/01/01") `gives`- [mkdatespan "2008/01/01" "2008/01/01"]- (Months 1,mkdatespan "2008/01/01" "2008/04/01") `gives`- [mkdatespan "2008/01/01" "2008/02/01"- ,mkdatespan "2008/02/01" "2008/03/01"- ,mkdatespan "2008/03/01" "2008/04/01"- ]- (Months 2,mkdatespan "2008/01/01" "2008/04/01") `gives`- [mkdatespan "2008/01/01" "2008/03/01"- ,mkdatespan "2008/03/01" "2008/05/01"- ]- (Weeks 1,mkdatespan "2008/01/01" "2008/01/15") `gives`- [mkdatespan "2007/12/31" "2008/01/07"- ,mkdatespan "2008/01/07" "2008/01/14"- ,mkdatespan "2008/01/14" "2008/01/21"- ]- (Weeks 2,mkdatespan "2008/01/01" "2008/01/15") `gives`- [mkdatespan "2007/12/31" "2008/01/14"- ,mkdatespan "2008/01/14" "2008/01/28"- ]- (DayOfMonth 2,mkdatespan "2008/01/01" "2008/04/01") `gives`- [mkdatespan "2008/01/02" "2008/02/02"- ,mkdatespan "2008/02/02" "2008/03/02"- ,mkdatespan "2008/03/02" "2008/04/02"- ]- (DayOfWeek 2,mkdatespan "2011/01/01" "2011/01/15") `gives`- [mkdatespan "2011/01/04" "2011/01/11"- ,mkdatespan "2011/01/11" "2011/01/18"- ]-- ,"fixSmartDateStr" ~: do- let gives = is . fixSmartDateStr (parsedate "2008/11/26")- "1999-12-02" `gives` "1999/12/02"- "1999.12.02" `gives` "1999/12/02"- "1999/3/2" `gives` "1999/03/02"- "19990302" `gives` "1999/03/02"- "2008/2" `gives` "2008/02/01"- "0020/2" `gives` "0020/02/01"- "1000" `gives` "1000/01/01"- "4/2" `gives` "2008/04/02"- "2" `gives` "2008/11/02"- "January" `gives` "2008/01/01"- "feb" `gives` "2008/02/01"- "today" `gives` "2008/11/26"- "yesterday" `gives` "2008/11/25"- "tomorrow" `gives` "2008/11/27"- "this day" `gives` "2008/11/26"- "last day" `gives` "2008/11/25"- "next day" `gives` "2008/11/27"- "this week" `gives` "2008/11/24" -- last monday- "last week" `gives` "2008/11/17" -- previous monday- "next week" `gives` "2008/12/01" -- next monday- "this month" `gives` "2008/11/01"- "last month" `gives` "2008/10/01"- "next month" `gives` "2008/12/01"- "this quarter" `gives` "2008/10/01"- "last quarter" `gives` "2008/07/01"- "next quarter" `gives` "2009/01/01"- "this year" `gives` "2008/01/01"- "last year" `gives` "2007/01/01"- "next year" `gives` "2009/01/01"--- "last wed" `gives` "2008/11/19"--- "next friday" `gives` "2008/11/28"--- "next january" `gives` "2009/01/01"-- ]+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE NoMonoLocalBinds #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}+{-|++Date parsing and utilities for hledger.++For date and time values, we use the standard Day and UTCTime types.++A 'SmartDate' is a date which may be partially-specified or relative.+Eg 2008\/12\/31, but also 2008\/12, 12\/31, tomorrow, last week, next year,+in 5 days, in -3 quarters.+We represent these as a triple of strings like (\"2008\",\"12\",\"\"),+(\"\",\"\",\"tomorrow\"), (\"\",\"last\",\"week\").++A 'DateSpan' is the span of time between two specific calendar dates, or+an open-ended span where one or both dates are unspecified. (A date span+with both ends unspecified matches all dates.)++An 'Interval' is ledger's \"reporting interval\" - weekly, monthly,+quarterly, etc.++'Period' will probably replace DateSpan in due course.++-}++-- XXX fromGregorian silently clips bad dates, use fromGregorianValid instead ?++module Hledger.Data.Dates (+ -- * Misc date handling utilities+ fromEFDay,+ modifyEFDay,+ getCurrentDay,+ getCurrentMonth,+ getCurrentYear,+ nulldate,+ spanContainsDate,+ periodContainsDate,+ parsedate,+ showDate,+ showEFDate,+ showDateSpan,+ showDateSpanDebug,+ showDateSpanAbbrev,+ showDateSpanAbbrevWith,+ showDateSpanFull,+ showDateSpanForQuery,+ elapsedSeconds,+ prevday,+ periodexprp,+ reportingintervalp,+ parsePeriodExpr,+ parsePeriodExpr',+ nulldatespan,+ emptydatespan,+ datesepchar,+ datesepchars,+ isDateSepChar,+ spanStart,+ spanEnd,+ spanStartYear,+ spanEndYear,+ spanYears,+ spansSpan,+ spanIntersect,+ spansIntersect,+ spanDefaultsFrom,+ spanValidDefaultsFrom,+ spanExtend,+ spanUnion,+ spansUnion,+ daysSpan,+ latestSpanContaining,+ smartdate,+ groupByDateSpan,+ fixSmartDate,+ fixSmartDateStr,+ fixSmartDateStrEither,+ fixSmartDateStrEither',+ yearp,+ daysInSpan,++ -- Temp exports+ startofyear,+ startofquarter,+ startofmonth,+ startofweek,+ nextday,+ nextweek,+ nextmonthandday,+ nextnthdayofmonth,+ prevNthWeekdayOfMonth,+ nthdayofweekcontaining,+ addGregorianMonthsToMonthday,+ advanceToNthWeekday,+ nextNthWeekdayOfMonth,+ isEmptySpan+) where++import Prelude hiding (Applicative(..))+import Control.Applicative (Applicative(..))+import Control.Applicative.Permutations+import Control.Monad (guard, unless, when)+import Control.Monad.Fail qualified as Fail (MonadFail, fail)+import Data.Char (digitToInt, isDigit)+import Data.Default (def)+import Data.Foldable (asum)+import Data.Function (on)+import Data.Functor (($>))+import Data.List (elemIndex, group, sort, sortBy)+import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe)+import Data.Ord (comparing)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Format hiding (months)+import Data.Time.Calendar+ (Day, addDays, addGregorianYearsClip, addGregorianMonthsClip, diffDays,+ fromGregorian, fromGregorianValid, toGregorian)+import Data.Time.Calendar.OrdinalDate (fromMondayStartWeek, mondayStartWeek)+import Data.Time.Clock (UTCTime, diffUTCTime)+import Data.Time.LocalTime (getZonedTime, localDay, zonedTimeToLocalTime)+import Safe (headErr, headMay, lastMay, maximumMay, minimumMay)+import Text.Megaparsec+import Text.Megaparsec.Char (char, char', digitChar, string, string')+import Text.Megaparsec.Char.Lexer (decimal, signed)+import Text.Printf (printf)++import Hledger.Data.Types+import Hledger.Data.Period+import Hledger.Utils+++-- Help ppShow parse and line-wrap DateSpans better in debug output.+instance Show DateSpan where+ show s = "DateSpan " ++ T.unpack (showDateSpan s)++showDate :: Day -> Text+showDate = T.pack . show++showEFDate :: EFDay -> Text+showEFDate = showDate . fromEFDay++-- | Render a datespan as a display string, abbreviating into a+-- compact form if possible.+-- Warning, hides whether dates are Exact or Flex.+showDateSpan :: DateSpan -> Text+showDateSpan = showPeriod . dateSpanAsPeriod++-- | Show a DateSpan with its begin/end dates, exact or flex.+showDateSpanDebug :: DateSpan -> String+showDateSpanDebug (DateSpan b e)= "DateSpan (" <> show b <> ") (" <> show e <> ")"++-- | Like showDateSpan, but show month spans as just the abbreviated month name+-- in the current locale.+showDateSpanAbbrev :: DateSpan -> Text+showDateSpanAbbrev = showPeriodAbbrev . dateSpanAsPeriod++-- | Like showDateSpanAbbrev, but take the month names from this time locale.+showDateSpanAbbrevWith :: TimeLocale -> DateSpan -> Text+showDateSpanAbbrevWith loc = showPeriodAbbrevWith loc . dateSpanAsPeriod++-- | Render a datespan as a full ISO date range "YYYY-MM-DD..YYYY-MM-DD"+-- (inclusive end), regardless of whether it represents a standard+-- calendar period. Open ends are shown as just "..".+showDateSpanFull :: DateSpan -> Text+showDateSpanFull (DateSpan mb me) =+ T.pack $ start <> ".." <> end+ where+ start = maybe "" (formatTime defaultTimeLocale "%F" . fromEFDay) mb+ end = maybe "" (formatTime defaultTimeLocale "%F" . addDays (-1) . fromEFDay) me++-- | Render a datespan as a period expression that parses back to the+-- same span, for a date: query term or a period parameter. Standard+-- calendar periods take their compact form (2025, 2025Q1, 2025-01,+-- 2025-01-15); any other span is written out with its exclusive end+-- date, which is how the period expression syntax reads one+-- (2025-01-13..2025-01-20); open ends stay open (2025-01-01..,+-- ..2025-02-01); the unbounded span is "".+--+-- 'showDateSpan' is for display: it prints inclusive end dates and ISO+-- week names, which a query would read as a day short or not at all.+--+-- >>> showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) (Just $ Exact $ fromGregorian 2026 1 1)+-- "2025"+-- >>> showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 13) (Just $ Exact $ fromGregorian 2025 1 20)+-- "2025-01-13..2025-01-20"+-- >>> showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 15) (Just $ Exact $ fromGregorian 2025 2 15)+-- "2025-01-15..2025-02-15"+-- >>> showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing+-- "2025-01-01.."+-- >>> showDateSpanForQuery $ DateSpan Nothing (Just $ Exact $ fromGregorian 2025 2 1)+-- "..2025-02-01"+-- >>> showDateSpanForQuery nulldatespan+-- ""+showDateSpanForQuery :: DateSpan -> Text+showDateSpanForQuery spn = case dateSpanAsPeriod spn of+ WeekPeriod b -> T.pack $ iso b <> ".." <> iso (addDays 7 b)+ PeriodBetween b e -> T.pack $ iso b <> ".." <> iso e+ PeriodTo e -> T.pack $ ".." <> iso e+ PeriodAll -> ""+ p -> showPeriod p -- a day, month, quarter, or year, or an open end+ where iso = formatTime defaultTimeLocale "%F"++-- | Get the current local date.+getCurrentDay :: IO Day+getCurrentDay = localDay . zonedTimeToLocalTime <$> getZonedTime++-- | Get the current local month number.+getCurrentMonth :: IO Int+getCurrentMonth = second3 . toGregorian <$> getCurrentDay++-- | Get the current local year.+getCurrentYear :: IO Integer+getCurrentYear = first3 . toGregorian <$> getCurrentDay++elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a+elapsedSeconds t1 = realToFrac . diffUTCTime t1++spanStart :: DateSpan -> Maybe Day+spanStart (DateSpan d _) = fromEFDay <$> d++spanEnd :: DateSpan -> Maybe Day+spanEnd (DateSpan _ d) = fromEFDay <$> d++spanStartDate :: DateSpan -> Maybe EFDay+spanStartDate (DateSpan d _) = d++spanEndDate :: DateSpan -> Maybe EFDay+spanEndDate (DateSpan _ d) = d++spanStartYear :: DateSpan -> Maybe Year+spanStartYear (DateSpan d _) = fmap (first3 . toGregorian . fromEFDay) d++spanEndYear :: DateSpan -> Maybe Year+spanEndYear (DateSpan d _) = fmap (first3 . toGregorian. fromEFDay) d++-- | Get the 0-2 years mentioned explicitly in a DateSpan.+spanYears :: DateSpan -> [Year]+spanYears (DateSpan ma mb) = mapMaybe (fmap (first3 . toGregorian. fromEFDay)) [ma,mb]++-- might be useful later: http://en.wikipedia.org/wiki/Allen%27s_interval_algebra++-- | Get overall span enclosing multiple sequentially ordered spans.+-- The start and end date will be exact or flexible depending on+-- the first span's start date and last span's end date.+spansSpan :: [DateSpan] -> DateSpan+spansSpan spans = DateSpan (spanStartDate =<< headMay spans) (spanEndDate =<< lastMay spans)++-- Like addGregorianMonthsClip, add one month to the given date, clipping when needed+-- to fit it within the next month's length. But also, keep a target day of month in mind,+-- and revert to that or as close to it as possible in subsequent longer months.+-- Eg, using it to step through 31sts gives 1/31, 2/28, 3/31, 4/30, 5/31..+addGregorianMonthsToMonthday :: MonthDay -> Integer -> Day -> Day+addGregorianMonthsToMonthday dom n d =+ let (y,m,_) = toGregorian $ addGregorianMonthsClip n d+ in fromGregorian y m dom++-- | Count the days in a DateSpan, or if it is open-ended return Nothing.+daysInSpan :: DateSpan -> Maybe Integer+daysInSpan (DateSpan (Just d1) (Just d2)) = Just $ diffDays (fromEFDay d2) (fromEFDay d1)+daysInSpan _ = Nothing++-- | Is this an empty span, ie closed with the end date on or before the start date ?+isEmptySpan :: DateSpan -> Bool+isEmptySpan (DateSpan (Just s) (Just e)) = e <= s+isEmptySpan _ = False++-- | Does the span include the given date ?+spanContainsDate :: DateSpan -> Day -> Bool+spanContainsDate (DateSpan Nothing Nothing) _ = True+spanContainsDate (DateSpan Nothing (Just e)) d = d < fromEFDay e+spanContainsDate (DateSpan (Just b) Nothing) d = d >= fromEFDay b+spanContainsDate (DateSpan (Just b) (Just e)) d = d >= fromEFDay b && d < fromEFDay e++-- | Does the period include the given date ?+-- (Here to avoid import cycle).+periodContainsDate :: Period -> Day -> Bool+periodContainsDate p = spanContainsDate (periodAsDateSpan p)++-- | Group elements based on where they fall in a list of 'DateSpan's without+-- gaps. The precondition is not checked.+groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])]+groupByDateSpan showempty date colspans =+ groupByCols colspans+ . dropWhile (beforeStart . fst)+ . sortBy (comparing fst)+ . map (\x -> (date x, x))+ where+ groupByCols [] _ = []+ groupByCols (c:cs) [] = if showempty then (c, []) : groupByCols cs [] else []+ groupByCols (c:cs) ps = (c, map snd colps) : groupByCols cs laterps+ where (colps, laterps) = span ((spanEnd c >) . Just . fst) ps++ beforeStart = maybe (const False) (>) $ spanStart =<< headMay colspans++-- | Calculate the intersection of a number of datespans.+spansIntersect [] = nulldatespan+spansIntersect [d] = d+spansIntersect (d:ds) = d `spanIntersect` (spansIntersect ds)++-- | Calculate the union of a number of datespans.+spansUnion [] = nulldatespan+spansUnion [d] = d+spansUnion (d:ds) = d `spanUnion` (spansUnion ds)++-- | Calculate the intersection of two datespans.+--+-- For non-intersecting spans, gives an empty span beginning on the second's start date:+-- >>> DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03) `spanIntersect` DateSpan (Just $ Flex $ fromGregorian 2018 01 03) (Just $ Flex $ fromGregorian 2018 01 05)+-- DateSpan 2018-01-03..2018-01-02+spanIntersect (DateSpan b1 e1) (DateSpan b2 e2) = DateSpan (laterDefinite b1 b2) (earlierDefinite e1 e2)++-- | Fill any unspecified dates in the first span with the dates from+-- the second one (if specified there). Sort of a one-way spanIntersect.+-- This one can create an invalid span that'll always be empty.+--+-- >>> :{+-- DateSpan (Just $ Exact $ fromGregorian 2024 1 1) Nothing+-- `spanDefaultsFrom`+-- DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)+-- :}+-- DateSpan 2024-01-01+--+-- >>> :{+-- DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing+-- `spanDefaultsFrom`+-- DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)+-- :}+-- DateSpan 2025-01-01..2024-01-01+--+spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan+spanDefaultsFrom (DateSpan a1 b1) (DateSpan a2 b2) = DateSpan a b+ where a = if isJust a1 then a1 else a2+ b = if isJust b1 then b1 else b2++-- | A smarter version of spanDefaultsFrom that avoids creating invalid+-- spans ending before they begin. Kept separate for now to reduce risk.+--+-- >>> :{+-- DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing+-- `spanValidDefaultsFrom`+-- DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)+-- :}+-- DateSpan 2025-01-01..+--+spanValidDefaultsFrom :: DateSpan -> DateSpan -> DateSpan+spanValidDefaultsFrom s1 s2 =+ case s1 `spanDefaultsFrom` s2 of+ DateSpan b e | b >= e -> s1+ s -> s++-- | Calculate the union of two datespans.+-- If either span is open-ended, the union will be too.+--+-- >>> ys2024 = fromGregorian 2024 01 01+-- >>> ys2025 = fromGregorian 2025 01 01+-- >>> to2024 = DateSpan Nothing (Just $ Exact ys2024)+-- >>> in2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)+-- >>> spanUnion to2024 in2024+-- DateSpan ..2024-12-31+-- >>> spanUnion in2024 to2024+-- DateSpan ..2024-12-31+spanUnion (DateSpan b1 e1) (DateSpan b2 e2) = DateSpan (earlier b1 b2) (later e1 e2)++-- | Extend the definite start/end dates of the first span, if needed,+-- to include the definite start/end dates of the second span.+-- And/or, replace open start/end dates in the first span with+-- definite start/end dates from the second.+-- Unlike spanUnion, open start/end dates in the second are ignored.+--+-- >>> ys2024 = fromGregorian 2024 01 01+-- >>> ys2025 = fromGregorian 2025 01 01+-- >>> to2024 = DateSpan Nothing (Just $ Exact ys2024)+-- >>> all2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)+-- >>> partof2024 = DateSpan (Just $ Exact $ fromGregorian 2024 03 01) (Just $ Exact $ fromGregorian 2024 09 01)+-- >>> spanExtend to2024 all2024+-- DateSpan 2024+-- >>> spanExtend all2024 to2024+-- DateSpan 2024+-- >>> spanExtend partof2024 all2024+-- DateSpan 2024+-- >>> spanExtend all2024 partof2024+-- DateSpan 2024+--+spanExtend (DateSpan b1 e1) (DateSpan b2 e2) = DateSpan (earlierDefinite b1 b2) (laterDefinite e1 e2)++-- | Pick the earlier of two DateSpan starts, treating Nothing as infinitely early.+-- An Exact and Flex with the same date are considered equal; the first argument wins.+earlier :: Maybe EFDay -> Maybe EFDay -> Maybe EFDay+earlier = min++-- | Pick the later of two DateSpan starts, treating Nothing as infinitely late.+-- An Exact and Flex with the same date are considered equal; the second argument wins.+later :: Maybe EFDay -> Maybe EFDay -> Maybe EFDay+later _ Nothing = Nothing+later Nothing _ = Nothing+later d1 d2 = max d1 d2++-- | Pick the earlier of two DateSpan ends that is a definite date (if any).+-- An Exact and Flex with the same date are considered equal; the first argument wins.+earlierDefinite :: Maybe EFDay -> Maybe EFDay -> Maybe EFDay+earlierDefinite d1 Nothing = d1+earlierDefinite Nothing d2 = d2+earlierDefinite d1 d2 = min d1 d2++-- | Pick the later of two DateSpan ends that is a definite date (if any).+-- An Exact and Flex with the same date are considered equal; the second argument wins.+laterDefinite :: Maybe EFDay -> Maybe EFDay -> Maybe EFDay+laterDefinite d1 Nothing = d1+laterDefinite Nothing d2 = d2+laterDefinite d1 d2 = max d1 d2++-- | Calculate the minimal DateSpan containing all of the given Days (in the+-- usual exclusive-end-date sense: beginning on the earliest, and ending on+-- the day after the latest).+daysSpan :: [Day] -> DateSpan+daysSpan ds = DateSpan (Exact <$> minimumMay ds) (Exact . addDays 1 <$> maximumMay ds)++-- | Select the DateSpan containing a given Day, if any, from a given list of+-- DateSpans.+--+-- If the DateSpans are non-overlapping, this returns the unique containing+-- DateSpan, if it exists. If the DateSpans are overlapping, it will return the+-- containing DateSpan with the latest start date, and then latest end date.++-- Note: This will currently return `DateSpan (Just s) (Just e)` before it will+-- return `DateSpan (Just s) Nothing`. It's unclear which behaviour is desired.+-- This is irrelevant at the moment as it's never applied to any list with+-- overlapping DateSpans.+latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan+latestSpanContaining datespans = go+ where+ go day = do+ spn <- Set.lookupLT supSpan spanSet+ guard $ spanContainsDate spn day+ return spn+ where+ -- The smallest DateSpan larger than any DateSpan containing day.+ supSpan = DateSpan (Just $ Exact $ addDays 1 day) Nothing++ spanSet = Set.fromList $ filter (not . isEmptySpan) datespans++-- | Parse a period expression to an Interval and overall DateSpan using+-- the provided reference date, or return a parse error.+parsePeriodExpr+ :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan)+parsePeriodExpr refdate s = parsewith (periodexprp refdate <* eof) (T.toLower s)++-- | Like parsePeriodExpr, but call error' on failure.+parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan)+parsePeriodExpr' refdate s =+ either (error' . ("failed to parse:" ++) . customErrorBundlePretty) id $ -- PARTIAL:+ parsePeriodExpr refdate s++-- | Show a DateSpan as a human-readable pseudo-period-expression string.+-- dateSpanAsText :: DateSpan -> String+-- dateSpanAsText (DateSpan Nothing Nothing) = "all"+-- dateSpanAsText (DateSpan Nothing (Just e)) = printf "to %s" (show e)+-- dateSpanAsText (DateSpan (Just b) Nothing) = printf "from %s" (show b)+-- dateSpanAsText (DateSpan (Just b) (Just e)) = printf "%s to %s" (show b) (show e)++-- | Convert a single smart date string to a date span using the provided+-- reference date, or raise an error.+-- spanFromSmartDateString :: Day -> String -> DateSpan+-- spanFromSmartDateString refdate s = spanFromSmartDate refdate sdate+-- where+-- sdate = fromparse $ parsewith smartdateonly s++spanFromSmartDate :: Day -> SmartDate -> DateSpan+spanFromSmartDate refdate sdate = DateSpan (Just b) (Just e)+ where+ (ry,rm,_) = toGregorian refdate+ (b,e) = span' sdate+ where+ span' :: SmartDate -> (EFDay, EFDay)+ span' (SmartCompleteDate day) = (Exact day, Exact $ nextday day)+ span' (SmartAssumeStart y Nothing) = (Flex $ startofyear day, Flex $ nextyear day) where day = fromGregorian y 1 1+ span' (SmartAssumeStart y (Just m)) = (Flex $ startofmonth day, Flex $ nextmonth day) where day = fromGregorian y m 1+ span' (SmartFromReference m d) = (Exact day, Exact $ nextday day) where day = fromGregorian ry (fromMaybe rm m) d+ span' (SmartMonth m) = (Flex $ startofmonth day, Flex $ nextmonth day) where day = fromGregorian ry m 1+ span' (SmartRelative n Day) = (Exact $ addDays n refdate, Exact $ addDays (n+1) refdate)+ span' (SmartRelative n Week) = (Flex $ addDays (7*n) d, Flex $ addDays (7*n+7) d) where d = thisweek refdate+ span' (SmartRelative n Month) = (Flex $ addGregorianMonthsClip n d, Flex $ addGregorianMonthsClip (n+1) d) where d = thismonth refdate+ span' (SmartRelative n Quarter) = (Flex $ addGregorianMonthsClip (3*n) d, Flex $ addGregorianMonthsClip (3*n+3) d) where d = thisquarter refdate+ span' (SmartRelative n Year) = (Flex $ addGregorianYearsClip n d, Flex $ addGregorianYearsClip (n+1) d) where d = thisyear refdate+ span' (SmartRelativeMonth LT m) = (Flex d, Flex $ nextmonth d) where d = prevnamedmonth m refdate+ span' (SmartRelativeMonth EQ m) = (Flex d, Flex $ nextmonth d) where d = thisnamedmonth m refdate+ span' (SmartRelativeMonth GT m) = (Flex d, Flex $ nextmonth d) where d = nextnamedmonth m refdate+ span' (SmartRelativeWeekDay LT wd) = (Exact d, Exact $ nextday d) where d = prevnamedweekday wd refdate+ span' (SmartRelativeWeekDay EQ wd) = (Exact d, Exact $ nextday d) where d = thisnamedweekday wd refdate+ span' (SmartRelativeWeekDay GT wd) = (Exact d, Exact $ nextday d) where d = nextnamedweekday wd refdate++-- showDay :: Day -> String+-- showDay day = printf "%04d/%02d/%02d" y m d where (y,m,d) = toGregorian day++-- | Convert a smart date string to an explicit yyyy\/mm\/dd string using+-- the provided reference date, or raise an error.+fixSmartDateStr :: Day -> Text -> Text+fixSmartDateStr d s =+ either (error' . printf "could not parse date %s %s" (show s) . show) id $ -- PARTIAL:+ (fixSmartDateStrEither d s :: Either HledgerParseErrors Text)++-- | A safe version of fixSmartDateStr.+fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text+fixSmartDateStrEither d = fmap showEFDate . fixSmartDateStrEither' d++fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay+fixSmartDateStrEither' d s = case parsewith smartdateonly (T.toLower s) of+ Right sd -> Right $ fixSmartDate d sd+ Left e -> Left e++-- | Convert a SmartDate to a specific date using the provided reference date.+-- This date will be exact or flexible depending on whether the day was+-- specified exactly. (Missing least-significant parts produces a flex date.)+--+-- ==== Examples:+-- >>> :set -XOverloadedStrings+-- >>> let t = fixSmartDateStr (fromGregorian 2008 11 26)+-- >>> t "0000-01-01"+-- "0000-01-01"+-- >>> t "1999-12-02"+-- "1999-12-02"+-- >>> t "1999.12.02"+-- "1999-12-02"+-- >>> t "1999/3/2"+-- "1999-03-02"+-- >>> t "19990302"+-- "1999-03-02"+-- >>> t "2008/2"+-- "2008-02-01"+-- >>> t "0020/2"+-- "0020-02-01"+-- >>> t "1000"+-- "1000-01-01"+-- >>> t "4/2"+-- "2008-04-02"+-- >>> t "2"+-- "2008-11-02"+-- >>> t "January"+-- "2008-01-01"+-- >>> t "feb"+-- "2008-02-01"+-- >>> t "today"+-- "2008-11-26"+-- >>> t "yesterday"+-- "2008-11-25"+-- >>> t "tomorrow"+-- "2008-11-27"+-- >>> t "this day"+-- "2008-11-26"+-- >>> t "last day"+-- "2008-11-25"+-- >>> t "next day"+-- "2008-11-27"+-- >>> t "this week" -- last monday+-- "2008-11-24"+-- >>> t "last week" -- previous monday+-- "2008-11-17"+-- >>> t "next week" -- next monday+-- "2008-12-01"+-- >>> t "this month"+-- "2008-11-01"+-- >>> t "last month"+-- "2008-10-01"+-- >>> t "next month"+-- "2008-12-01"+-- >>> t "this quarter"+-- "2008-10-01"+-- >>> t "last quarter"+-- "2008-07-01"+-- >>> t "next quarter"+-- "2009-01-01"+-- >>> t "this year"+-- "2008-01-01"+-- >>> t "last year"+-- "2007-01-01"+-- >>> t "next year"+-- "2009-01-01"+--+-- refdate is Wednesday, 2008-11-26+-- >>> t "last wednesday"+-- "2008-11-19"+-- >>> t "this wednesday"+-- "2008-12-03"+-- >>> t "next wednesday"+-- "2008-12-03"+-- >>> t "last january"+-- "2008-01-01"+-- >>> t "this january"+-- "2009-01-01"+-- >>> t "next january"+-- "2009-01-01"+-- >>> t "last november"+-- "2007-11-01"+-- >>> t "this november"+-- "2009-11-01"+-- >>> t "next november"+-- "2009-11-01"+--+-- >>> t "in 5 days"+-- "2008-12-01"+-- >>> t "in 7 months"+-- "2009-06-01"+-- >>> t "in -2 weeks"+-- "2008-11-10"+-- >>> t "1 quarter ago"+-- "2008-07-01"+-- >>> t "1 week ahead"+-- "2008-12-01"+fixSmartDate :: Day -> SmartDate -> EFDay+fixSmartDate refdate = fix+ where+ fix :: SmartDate -> EFDay+ fix (SmartCompleteDate d) = Exact d+ fix (SmartAssumeStart y m) = Flex $ fromGregorian y (fromMaybe 1 m) 1+ fix (SmartFromReference m d) = Exact $ fromGregorian ry (fromMaybe rm m) d+ fix (SmartMonth m) = Flex $ fromGregorian ry m 1+ fix (SmartRelative n Day) = Exact $ addDays n refdate+ fix (SmartRelative n Week) = Flex $ addDays (7*n) $ thisweek refdate+ fix (SmartRelative n Month) = Flex $ addGregorianMonthsClip n $ thismonth refdate+ fix (SmartRelative n Quarter) = Flex $ addGregorianMonthsClip (3*n) $ thisquarter refdate+ fix (SmartRelative n Year) = Flex $ addGregorianYearsClip n $ thisyear refdate+ fix (SmartRelativeMonth LT m) = Flex $ prevnamedmonth m refdate+ fix (SmartRelativeMonth EQ m) = Flex $ thisnamedmonth m refdate+ fix (SmartRelativeMonth GT m) = Flex $ nextnamedmonth m refdate+ fix (SmartRelativeWeekDay LT wd) = Exact $ prevnamedweekday wd refdate+ fix (SmartRelativeWeekDay EQ wd) = Exact $ thisnamedweekday wd refdate+ fix (SmartRelativeWeekDay GT wd) = Exact $ nextnamedweekday wd refdate+ (ry, rm, _) = toGregorian refdate++prevday :: Day -> Day+prevday = addDays (-1)+nextday = addDays 1++thisweek = startofweek+prevweek = startofweek . addDays (-7)+nextweek = startofweek . addDays 7+startofweek day = fromMondayStartWeek y w 1+ where+ (y,_,_) = toGregorian day+ (w,_) = mondayStartWeek day++thismonth = startofmonth+prevmonth = startofmonth . addGregorianMonthsClip (-1)+nextmonth = startofmonth . addGregorianMonthsClip 1+startofmonth day = fromGregorian y m 1 where (y,m,_) = toGregorian day+nthdayofmonth d day = fromGregorian y m d where (y,m,_) = toGregorian day++prevnamedmonth :: Month -> Day -> Day+prevnamedmonth targetmonth refdate = fromGregorian y' targetmonth 1+ where+ (y, m, _) = toGregorian refdate+ y' = if targetmonth < m then y else y - 1++nextnamedmonth :: Month -> Day -> Day+nextnamedmonth targetmonth refdate = fromGregorian y' targetmonth 1+ where+ (y, m, _) = toGregorian refdate+ y' = if targetmonth > m then y else y + 1++thisnamedmonth :: Month -> Day -> Day+thisnamedmonth = nextnamedmonth -- "this" and "next" both mean next occurrence after current month++prevnamedweekday :: WeekDay -> Day -> Day+prevnamedweekday targetwd refdate = addDays (negate $ fromIntegral daysback) refdate+ where+ (_, curwd) = mondayStartWeek refdate+ daysback = 1 + (curwd - targetwd - 1) `mod` 7++nextnamedweekday :: WeekDay -> Day -> Day+nextnamedweekday targetwd refdate = addDays (fromIntegral daysforward) refdate+ where+ (_, curwd) = mondayStartWeek refdate+ daysforward = 1 + (targetwd - curwd - 1) `mod` 7++thisnamedweekday :: WeekDay -> Day -> Day+thisnamedweekday = nextnamedweekday -- "this" and "next" both mean next occurrence after today++thisquarter = startofquarter+startofquarter day = fromGregorian y (firstmonthofquarter m) 1+ where+ (y,m,_) = toGregorian day+ firstmonthofquarter m2 = ((m2-1) `div` 3) * 3 + 1++thisyear = startofyear+-- prevyear = startofyear . addGregorianYearsClip (-1)+nextyear = startofyear . addGregorianYearsClip 1+startofyear day = fromGregorian y 1 1 where (y,_,_) = toGregorian day++-- | Find the next occurrence of the specified month and day of month, on or after the given date.+-- The month should be 1-12 and the day of month should be 1-31, or an error will be raised.+--+-- >>> let wed22nd = fromGregorian 2017 11 22+-- >>> nextmonthandday 11 21 wed22nd+-- 2018-11-21+-- >>> nextmonthandday 11 22 wed22nd+-- 2017-11-22+-- >>> nextmonthandday 11 23 wed22nd+-- 2017-11-23+nextmonthandday :: Month -> MonthDay -> Day -> Day+nextmonthandday m n date+ -- PARTIAL:+ | not (validMonth m) = error' $ "nextmonthandday: month should be 1..12, not "++show m+ | not (validDay n) = error' $ "nextmonthandday: day should be 1..31, not " ++show n+ | mdthisyear >= date = mdthisyear+ | otherwise = mdnextyear+ where+ s = startofyear date+ advancetomonth = applyN (m-1) nextmonth+ advancetoday = addDays (toInteger n-1)+ mdthisyear = advancetoday $ advancetomonth s+ mdnextyear = advancetoday $ advancetomonth $ nextyear s++-- | Find the next occurrence of the specified day of month, on or after the given date.+-- The day of month should be 1-31, or an error will be raised.+--+-- >>> let wed22nd = fromGregorian 2017 11 22+-- >>> nextnthdayofmonth 21 wed22nd+-- 2017-12-21+-- >>> nextnthdayofmonth 22 wed22nd+-- 2017-11-22+-- >>> nextnthdayofmonth 23 wed22nd+-- 2017-11-23+nextnthdayofmonth :: MonthDay -> Day -> Day+nextnthdayofmonth n date+ -- PARTIAL:+ | not (validDay n) = error' $ "nextnthdayofmonth: day should be 1..31, not " ++show n+ | nthofthismonth >= date = nthofthismonth+ | otherwise = nthofnextmonth+ where+ s = startofmonth date+ nthofthismonth = nthdayofmonth n s+ nthofnextmonth = nthdayofmonth n $ nextmonth s++-- | For given date d find week-long interval that starts on nth day of week+-- and covers it.+--+-- Examples: 2017-11-22 is Wed. Week-long intervals that cover it and+-- start on Mon, Tue or Wed will start in the same week. However+-- intervals that start on Thu or Fri should start in prev week:+-- >>> let wed22nd = fromGregorian 2017 11 22+-- >>> nthdayofweekcontaining 1 wed22nd+-- 2017-11-20+-- >>> nthdayofweekcontaining 2 wed22nd+-- 2017-11-21+-- >>> nthdayofweekcontaining 3 wed22nd+-- 2017-11-22+-- >>> nthdayofweekcontaining 4 wed22nd+-- 2017-11-16+-- >>> nthdayofweekcontaining 5 wed22nd+-- 2017-11-17+nthdayofweekcontaining :: WeekDay -> Day -> Day+nthdayofweekcontaining n d | nthOfSameWeek <= d = nthOfSameWeek+ | otherwise = nthOfPrevWeek+ where nthOfSameWeek = addDays (toInteger n-1) s+ nthOfPrevWeek = addDays (toInteger n-1) $ prevweek s+ s = startofweek d++-- -- | Find the next occurrence of some weekday, on or after the given date d.+-- --+-- -- >>> let wed22nd = fromGregorian 2017 11 22+-- -- >>> nextnthdayofweek 1 wed22nd+-- -- 2017-11-20+-- -- >>> nextnthdayofweek 2 wed22nd+-- -- 2017-11-21+-- -- >>> nextnthdayofweek 3 wed22nd+-- -- 2017-11-22+-- -- >>> nextnthdayofweek 4 wed22nd+-- -- 2017-11-16+-- -- >>> nextnthdayofweek 5 wed22nd+-- -- 2017-11-17+-- nextdayofweek :: WeekDay -> Day -> Day+-- nextdayofweek n d | nthOfSameWeek <= d = nthOfSameWeek+-- | otherwise = nthOfPrevWeek+-- where nthOfSameWeek = addDays (toInteger n-1) s+-- nthOfPrevWeek = addDays (toInteger n-1) $ prevweek s+-- s = startofweek d++-- | Find the next occurrence of some nth weekday of a month, on or after the given date d.+--+-- >>> let wed22nd = fromGregorian 2017 11 22+-- >>> nextNthWeekdayOfMonth 3 3 wed22nd -- next third wednesday+-- 2017-12-20+-- >>> nextNthWeekdayOfMonth 4 3 wed22nd -- next fourth wednesday+-- 2017-11-22+-- >>> nextNthWeekdayOfMonth 5 3 wed22nd -- next fifth wednesday+-- 2017-11-29+nextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day+nextNthWeekdayOfMonth n wd d+ | nthweekdaythismonth >= d = nthweekdaythismonth+ | otherwise = nthweekdaynextmonth+ where+ nthweekdaythismonth = advanceToNthWeekday n wd $ startofmonth d+ nthweekdaynextmonth = advanceToNthWeekday n wd $ nextmonth d++-- | Find the previous occurrence of some nth weekday of a month, on or before the given date d.+--+-- >>> let wed22nd = fromGregorian 2017 11 22+-- >>> prevNthWeekdayOfMonth 4 3 wed22nd+-- 2017-11-22+-- >>> prevNthWeekdayOfMonth 5 2 wed22nd+-- 2017-10-31+prevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day+prevNthWeekdayOfMonth n wd d+ | nthweekdaythismonth <= d = nthweekdaythismonth+ | otherwise = nthweekdayprevmonth+ where+ nthweekdaythismonth = advanceToNthWeekday n wd $ startofmonth d+ nthweekdayprevmonth = advanceToNthWeekday n wd $ prevmonth d++-- | Advance to the nth occurrence of the given weekday, on or after the given date.+-- Can call error.+advanceToNthWeekday :: Int -> WeekDay -> Day -> Day+advanceToNthWeekday n wd s =+ -- PARTIAL:+ maybe err (addWeeks (n-1)) $ firstMatch (>=s) $ iterate (addWeeks 1) $ firstweekday s+ where+ err = error' "advanceToNthWeekday: should not happen"+ addWeeks k = addDays (7 * toInteger k)+ firstMatch p = headMay . dropWhile (not . p)+ firstweekday = addDays (toInteger wd-1) . startofweek++----------------------------------------------------------------------+-- parsing++-- -- | Parse a couple of date-time string formats to a time type.+-- parsedatetime :: String -> Maybe LocalTime+-- parsedatetime s = asum [+-- parseTimeM TruedefaultTimeLocale "%Y/%m/%d %H:%M:%S" s,+-- parseTimeM TruedefaultTimeLocale "%Y-%m-%d %H:%M:%S" s+-- ]++-- | A simple date parsing helper: parses these YMD date string formats:+-- `YYYY-MM-DD`, `YYYY/MM/DD`, `YYYY.MM.DD` or `YYYYMMDD`,+-- where the month and day each have two digits and the year has one or more.+--+-- This is different from the Smart Dates of the CLI and period expressions ("smartdate", below)+-- and not quite the same as the Simple Dates of the journal ("datep", in Hledger.Read.Common).+-- It's mainly for internal or interactive use, eg when debugging - +-- but currently is also used in a few user-facing places, such as:+-- parsing --value's argument, +-- parsing .latest files,+-- and parsing hledger's --version output (which uses unseparated dates).+--+-- Unseparated dates were added in 2025 for convenience.+-- Note it means many integers will now parse successfully.+--+-- >>> parsedate "2008/02/03"+-- Just 2008-02-03+-- >>> parsedate "2008/02/03/"+-- Nothing+-- >>> parsedate "2008/02/30"+-- Nothing+-- >>> parsedate "2025-01-01"+-- Just 2025-01-01+-- >>> parsedate "2025.01.01"+-- Just 2025-01-01+-- >>> parsedate "20250101"+-- Just 2025-01-01+-- >>> parsedate "00101"+-- Just 0000-01-01+parsedate :: String -> Maybe Day+parsedate s = asum [+ parseTimeM True defaultTimeLocale "%Y-%m-%d" s,+ parseTimeM True defaultTimeLocale "%Y/%m/%d" s,+ parseTimeM True defaultTimeLocale "%Y.%m.%d" s,+ parseTimeM True defaultTimeLocale "%Y%m%d" s+ ]++{-|+Parse a date in any of the formats allowed in Ledger's period expressions, and some others.+Assumes any text in the parse stream has been lowercased.+Returns a SmartDate, to be converted to a full date later (see fixSmartDate).++Examples:++> 2004 (start of year, which must have 4+ digits)+> 2004/10 (start of month, which must be 1-12)+> 2004/10/1 (exact date, day must be 1-31)+> 10/1 (month and day in current year)+> 21 (day in current month)+> october, oct (start of month in current year)+> 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 monday/mon (the previous or next named weekday; this=next)+> last/next january/jan (previous or next start of named month; this disallowed to avoid confusion)+> in n days/weeks/months/quarters/years (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)++Note malformed digit sequences might give surprising results:++> 201813 (6 digits with an invalid month is parsed as start of 6-digit year)+> 20181301 (8 digits with an invalid month is parsed as start of 8-digit year)+> 20181232 (8 digits with an invalid day gives an error)+> 201801012 (9+ digits beginning with a valid YYYYMMDD gives an error)++Eg:++YYYYMMDD is parsed as year-month-date if those parts are valid+(>=4 digits, 1-12, and 1-31 respectively):+>>> parsewith (smartdate <* eof) "20181201"+Right (SmartCompleteDate 2018-12-01)++YYYYMM is parsed as year-month-01 if year and month are valid:+>>> parsewith (smartdate <* eof) "201804"+Right (SmartAssumeStart 2018 (Just 4))++With an invalid month, it's parsed as a year:+>>> parsewith (smartdate <* eof) "201813"+Right (SmartAssumeStart 201813 Nothing)++A 9+ digit number beginning with valid YYYYMMDD gives an error:+>>> parsewith (smartdate <* eof) "201801012"+Left (...)++Big numbers not beginning with a valid YYYYMMDD are parsed as a year:+>>> parsewith (smartdate <* eof) "201813012"+Right (SmartAssumeStart 201813012 Nothing)++-}+smartdate :: TextParser m SmartDate+smartdate = choice'+ -- XXX maybe obscures date errors ? see ledgerdate+ [ relativeinterval+ , relativemonth+ , relativeweekday+ , yyyymmdd+ , ymd+ , (\(m,d) -> SmartFromReference (Just m) d) <$> md+ , failIfInvalidDate . SmartFromReference Nothing =<< decimal+ , SmartMonth <$> (month <|> mon)+ , SmartRelative (-1) Day <$ string' "yesterday"+ , SmartRelative 0 Day <$ string' "today"+ , SmartRelative 1 Day <$ string' "tomorrow"+ ]+ where+ relativeinterval = do+ optional $ string' "in" <* skipNonNewlineSpaces+ num <- relativenump <* skipNonNewlineSpaces+ interval <- intervalp <* skipNonNewlineSpaces+ sign <- choice [negate <$ string' "ago", id <$ string' "ahead", pure id]+ return $ SmartRelative (sign num) interval+ where+ relativenump = choice [ 0 <$ string' "this", -1 <$ string' "last", 1 <$ string' "next", signed skipNonNewlineSpaces decimal ]+ intervalp = choice [ Day <$ string' "day", Week <$ string' "week", Month <$ string' "month"+ , Quarter <$ string' "quarter", Year <$ string' "year" ] <* optional (char' 's')+ relativemonth = do+ dir <- choice [LT <$ string' "last", EQ <$ string' "this", GT <$ string' "next"]+ skipNonNewlineSpaces+ m <- (month <|> mon)+ return $ SmartRelativeMonth dir m+ relativeweekday = do+ dir <- choice [LT <$ string' "last", EQ <$ string' "this", GT <$ string' "next"]+ skipNonNewlineSpaces+ w <- weekday+ return $ SmartRelativeWeekDay dir w++-- | Like smartdate, but there must be nothing other than whitespace after the date.+smartdateonly :: TextParser m SmartDate+smartdateonly = smartdate <* skipNonNewlineSpaces <* eof++datesepchars :: String+datesepchars = "/-."++datesepchar :: TextParser m Char+datesepchar = satisfy isDateSepChar++isDateSepChar :: Char -> Bool+isDateSepChar c = c == '-' || c == '/' || c == '.'++validMonth, validDay :: Int -> Bool+validMonth n = n >= 1 && n <= 12+validDay n = n >= 1 && n <= 31++failIfInvalidDate :: Fail.MonadFail m => SmartDate -> m SmartDate+failIfInvalidDate s = unless isValid (Fail.fail $ "bad smart date: " ++ show s) $> s+ where isValid = case s of+ SmartAssumeStart _ (Just m) -> validMonth m+ SmartFromReference mm d -> isJust $ fromGregorianValid 2004 (fromMaybe 1 mm) d+ SmartMonth m -> validMonth m+ _ -> True++showBadDate :: Integer -> Int -> Int -> String+showBadDate y m d = "bad smart date: " ++ show y ++ "-" ++ show m ++ "-" ++ show d++yyyymmdd :: TextParser m SmartDate+yyyymmdd = do+ y <- read <$> count 4 digitChar+ m <- read <$> count 2 digitChar+ mdy <- optional $ read <$> count 2 digitChar+ case mdy of+ Nothing -> failIfInvalidDate $ SmartAssumeStart y (Just m)+ Just d -> maybe (Fail.fail $ showBadDate y m d) (return . SmartCompleteDate) $+ fromGregorianValid y m d++ymd :: TextParser m SmartDate+ymd = do+ y <- yearp+ emd <- optional . try $ do+ sep <- datesepchar+ m <- decimal+ unless (validMonth m) $ Fail.fail ("Bad month " <> show m)+ option (Left m) . try $ Right <$> do+ _ <- char sep+ d <- decimal+ maybe (Fail.fail $ showBadDate y m d) return $ fromGregorianValid y m d+ return $ case emd of+ Nothing -> SmartAssumeStart y Nothing+ Just (Left m) -> SmartAssumeStart y (Just m)+ Just (Right day) -> SmartCompleteDate day++md :: TextParser m (Month, MonthDay)+md = do+ m <- decimal+ datesepchar+ d <- decimal+ _ <- failIfInvalidDate $ SmartFromReference (Just m) d+ return (m, d)++-- | Parse a year number from a Text, making sure that at least four digits are+-- used.+yearp :: TextParser m Integer+yearp = do+ year <- takeWhile1P (Just "year") isDigit+ unless (T.length year >= 4) . Fail.fail $ "Year must contain at least 4 digits: " <> T.unpack year+ return $ readDecimal year++-- These are compared case insensitively, and should all be kept lower case.+months = ["january","february","march","april","may","june",+ "july","august","september","october","november","december"]+monthabbrevs = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]+weekdays = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]+weekdayabbrevs = ["mon","tue","wed","thu","fri","sat","sun"]++month, mon :: TextParser m Month+month = choice $ zipWith (\i m -> i <$ string' m) [1..12] months+mon = choice $ zipWith (\i m -> i <$ string' m) [1..12] monthabbrevs++weekday :: TextParser m Int+weekday = do+ wday <- T.toLower <$> (choice . map string' $ weekdays ++ weekdayabbrevs)+ case catMaybes $ [wday `elemIndex` weekdays, wday `elemIndex` weekdayabbrevs] of+ (i:_) -> return (i+1)+ [] -> Fail.fail $ "weekday: should not happen: attempted to find " <>+ show wday <> " in " <> show (weekdays ++ weekdayabbrevs)++weekdaysp :: TextParser m [Int]+weekdaysp = fmap headErr . group . sort <$> sepBy1 weekday (string' ",") -- PARTIAL headErr will succeed because of sepBy1++-- | Parse a period expression, specifying a date span and optionally+-- a reporting interval. Requires a reference "today" date for+-- resolving any relative start/end dates (only; it is not needed for+-- parsing the reporting interval).+--+-- >>> let p = parsePeriodExpr (fromGregorian 2008 11 26)+-- >>> p "from Aug to Oct"+-- Right (NoInterval,DateSpan 2008-08-01..2008-09-30)+-- >>> p "aug to oct"+-- Right (NoInterval,DateSpan 2008-08-01..2008-09-30)+-- >>> p "2009q2"+-- Right (NoInterval,DateSpan 2009Q2)+-- >>> p "Q3"+-- Right (NoInterval,DateSpan 2008Q3)+-- >>> p "every 3 days in Aug"+-- Right (Days 3,DateSpan 2008-08)+-- >>> p "daily from aug"+-- Right (Days 1,DateSpan 2008-08-01..)+-- >>> p "every week to 2009"+-- Right (Weeks 1,DateSpan ..2008-12-31)+-- >>> p "every 2nd day of month"+-- Right (MonthDay 2,DateSpan ..)+-- >>> p "every 2nd day"+-- Right (MonthDay 2,DateSpan ..)+-- >>> p "every 2nd day 2009.."+-- Right (MonthDay 2,DateSpan 2009-01-01..)+-- >>> p "every 2nd day 2009-"+-- Right (MonthDay 2,DateSpan 2009-01-01..)+-- >>> p "every 29th Nov"+-- Right (MonthAndDay 11 29,DateSpan ..)+-- >>> p "every 29th nov ..2009"+-- Right (MonthAndDay 11 29,DateSpan ..2008-12-31)+-- >>> p "every nov 29th"+-- Right (MonthAndDay 11 29,DateSpan ..)+-- >>> p "every Nov 29th 2009.."+-- Right (MonthAndDay 11 29,DateSpan 2009-01-01..)+-- >>> p "every 11/29 from 2009"+-- Right (MonthAndDay 11 29,DateSpan 2009-01-01..)+-- >>> p "every 11/29 since 2009"+-- Right (MonthAndDay 11 29,DateSpan 2009-01-01..)+-- >>> p "every 2nd Thursday of month to 2009"+-- Right (NthWeekdayOfMonth 2 4,DateSpan ..2008-12-31)+-- >>> p "every 1st monday of month to 2009"+-- Right (NthWeekdayOfMonth 1 1,DateSpan ..2008-12-31)+-- >>> p "every tue"+-- Right (DaysOfWeek [2],DateSpan ..)+-- >>> p "every 2nd day of week"+-- Right (DaysOfWeek [2],DateSpan ..)+-- >>> p "every 2nd day of month"+-- Right (MonthDay 2,DateSpan ..)+-- >>> p "every 2nd day"+-- Right (MonthDay 2,DateSpan ..)+-- >>> p "every 2nd day 2009.."+-- Right (MonthDay 2,DateSpan 2009-01-01..)+-- >>> p "every 2nd day of month 2009.."+-- Right (MonthDay 2,DateSpan 2009-01-01..)+periodexprp :: Day -> TextParser m (Interval, DateSpan)+periodexprp rdate = do+ skipNonNewlineSpaces+ choice' [ intervalanddateperiodexprp rdate+ , (,) NoInterval <$> periodexprdatespanp rdate+ ]++-- Parse a reporting interval and a date span.+intervalanddateperiodexprp :: Day -> TextParser m (Interval, DateSpan)+intervalanddateperiodexprp rdate = do+ i <- reportingintervalp+ s <- option def . try $ do+ skipNonNewlineSpaces+ periodexprdatespanp rdate+ return (i,s)++-- Parse a reporting interval.+reportingintervalp :: TextParser m Interval+reportingintervalp = choice'+ [ tryinterval "day" "daily" Days+ , tryinterval "month" "monthly" Months+ , tryinterval "quarter" "quarterly" Quarters+ , tryinterval "year" "yearly" Years+ , Weeks 2 <$ string' "biweekly"+ , Weeks 2 <$ string' "fortnightly"+ , Months 2 <$ string' "bimonthly"+ , string' "every" *> skipNonNewlineSpaces *> choice'+ [ DaysOfWeek . pure <$> (nth <* skipNonNewlineSpaces <* string' "day" <* of_ "week")+ , MonthDay <$> (nth <* skipNonNewlineSpaces <* string' "day" <* optOf_ "month")+ , liftA2 NthWeekdayOfMonth nth $ skipNonNewlineSpaces *> weekday <* optOf_ "month"+ , uncurry MonthAndDay <$> (md <* optOf_ "year")+ , DaysOfWeek <$> weekdaysp+ , DaysOfWeek [1..5] <$ string' "weekday"+ , DaysOfWeek [6..7] <$ string' "weekendday"+ , d_o_y <* optOf_ "year"+ ]+ -- NB: the ordering is important here since the parse for `every weekday`+ -- would match the `tryinterval` first and then error on `d`. Perhaps it+ -- would be clearer to factor some of this into the `every` choice or other+ -- left-factorings.+ , tryinterval "week" "weekly" Weeks+ ]+ where+ of_ period =+ skipNonNewlineSpaces *> string' "of" *> skipNonNewlineSpaces *> string' period++ optOf_ period = optional . try $ of_ period++ nth = decimal <* choice (map string' ["st","nd","rd","th"])+ d_o_y = runPermutation $ liftA2 MonthAndDay (toPermutation $ (month <|> mon) <* skipNonNewlineSpaces)+ (toPermutation $ nth <* skipNonNewlineSpaces)++ -- Parse any of several variants of a basic interval, eg "daily", "every day", "every N days".+ tryinterval :: Text -> Text -> (Int -> Interval) -> TextParser m Interval+ tryinterval singular compact intcons = intcons <$> choice'+ [ 1 <$ string' compact+ , string' "every" *> skipNonNewlineSpaces *> choice+ [ 1 <$ string' singular+ , decimal <* skipNonNewlineSpaces <* string' (singular <> "s")+ ]+ ]++periodexprdatespanp :: Day -> TextParser m DateSpan+periodexprdatespanp rdate = choice' [+ doubledatespanp rdate,+ fromdatespanp rdate,+ todatespanp rdate,+ indatespanp rdate+ ]++-- |+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "20180101-201804"+-- Right DateSpan 2018Q1+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2017..2018"+-- Right DateSpan 2017+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2017-2018"+-- Right DateSpan 2017+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2017-01-2018"+-- Right DateSpan 2017+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2017-01-01-2018"+-- Right DateSpan 2017+--+-- A single number after an unspaced - is not accepted as the end date (a day of the current month),+-- since eg 2008-13 is more likely a mistyped date than "2008 to the 13th":+--+-- >>> either (const "parse error") show $ parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2008-13"+-- "parse error"+-- >>> parsewith (doubledatespanp (fromGregorian 2018 01 01) <* eof) "2008..13"+-- Right DateSpan 2008-01-01..2018-01-12+doubledatespanp :: Day -> TextParser m DateSpan+doubledatespanp rdate = do+ b <- optional ((string' "from" <|> string' "since") *> skipNonNewlineSpaces) *> smartdateorquarterstartp rdate+ spacedbefore <- skipNonNewlineSpaces'+ sep <- choice [string' "to", string "..", string "-"]+ spacedafter <- skipNonNewlineSpaces'+ e <- smartdateorquarterstartp rdate+ when (sep == "-" && not spacedbefore && not spacedafter && isDayOfMonth e) $+ Fail.fail $ "a single number after - is ambiguous here;"+ ++ " to mean a day of the current month, write .. or to instead of -"+ return $ fromToSpan b e+ where+ fromToSpan = DateSpan `on` (Just . fixSmartDate rdate)+ isDayOfMonth (SmartFromReference Nothing _) = True+ isDayOfMonth _ = False++-- |+-- >>> let p = parsewith (fromdatespanp (fromGregorian 2024 02 02) <* eof)+-- >>> p "2025-01-01.."+-- Right DateSpan 2025-01-01..+-- >>> p "2025Q1.."+-- Right DateSpan 2025-01-01..+-- >>> p "from q2"+-- Right DateSpan 2024-04-01..+fromdatespanp :: Day -> TextParser m DateSpan+fromdatespanp rdate = fromSpan <$> choice+ [ (string' "from" <|> string' "since") *> skipNonNewlineSpaces *> smartdateorquarterstartp rdate+ , smartdateorquarterstartp rdate <* choice [string "..", string "-" <* notFollowedBy digitChar]+ ]+ where+ fromSpan b = DateSpan (Just $ fixSmartDate rdate b) Nothing++-- |+-- >>> let p = parsewith (todatespanp (fromGregorian 2024 02 02) <* eof)+-- >>> p "..2025-01-01"+-- Right DateSpan ..2024-12-31+-- >>> p "..2025Q1"+-- Right DateSpan ..2024-12-31+-- >>> p "to q2"+-- Right DateSpan ..2024-03-31+todatespanp :: Day -> TextParser m DateSpan+todatespanp rdate =+ choice [string' "to", string' "until", string "..", string "-"]+ *> skipNonNewlineSpaces+ *> (DateSpan Nothing . Just . fixSmartDate rdate <$> smartdateorquarterstartp rdate)++-- |j+-- >>> let p = parsewith (indatespanp (fromGregorian 2024 02 02) <* eof)+-- >>> p "2025-01-01"+-- Right DateSpan 2025-01-01+-- >>> p "2025q1"+-- Right DateSpan 2025Q1+-- >>> p "in Q2"+-- Right DateSpan 2024Q2+indatespanp :: Day -> TextParser m DateSpan+indatespanp rdate =+ optional (string' "in" *> skipNonNewlineSpaces)+ *> choice' [+ quarterspanp rdate,+ spanFromSmartDate rdate <$> smartdate+ ]++-- Helper: parse a quarter number, optionally preceded by a year.+quarterp :: Day -> TextParser m (Year, Int)+quarterp rdate = do+ y <- yearp <|> pure (first3 $ toGregorian rdate)+ n <- char' 'q' *> satisfy (`elem` ['1' .. '4']) >>= return . digitToInt+ return (y, n)++-- | Parse a single quarter (YYYYqN or qN, case insensitive q) as a date span.+--+-- >>> parsewith (quarterspanp (fromGregorian 2018 01 01) <* eof) "q1"+-- Right DateSpan 2018Q1+-- >>> parsewith (quarterspanp (fromGregorian 2018 01 01) <* eof) "Q1"+-- Right DateSpan 2018Q1+-- >>> parsewith (quarterspanp (fromGregorian 2018 01 01) <* eof) "2020q4"+-- Right DateSpan 2020Q4+quarterspanp :: Day -> TextParser m DateSpan+quarterspanp rdate = do+ (y,q) <- quarterp rdate+ return . periodAsDateSpan $ QuarterPeriod y q++-- | Parse a quarter (YYYYqN or qN, case insensitive q) as its start date.+--+-- >>> parsewith (quarterstartp (fromGregorian 2025 02 02) <* eof) "q1"+-- Right 2025-01-01+-- >>> parsewith (quarterstartp (fromGregorian 2025 02 02) <* eof) "Q2"+-- Right 2025-04-01+-- >>> parsewith (quarterstartp (fromGregorian 2025 02 02) <* eof) "2025q4"+-- Right 2025-10-01+quarterstartp :: Day -> TextParser m Day+quarterstartp rdate = do+ (y,q) <- quarterp rdate+ return $+ fromMaybe (error' "Hledger.Data.Dates.quarterstartp: invalid date found") $ -- PARTIAL, shouldn't happen+ periodStart $ QuarterPeriod y q++smartdateorquarterstartp :: Day -> TextParser m SmartDate+smartdateorquarterstartp rdate = choice' [SmartCompleteDate <$> quarterstartp rdate, smartdate]++nulldatespan :: DateSpan+nulldatespan = DateSpan Nothing Nothing++-- | An exact datespan of zero length, that matches no date.+emptydatespan :: DateSpan+emptydatespan = DateSpan (Just $ Exact $ addDays 1 nulldate) (Just $ Exact nulldate)++nulldate :: Day+nulldate = fromGregorian 0 1 1
+ Hledger/Data/DayPartition.hs view
@@ -0,0 +1,343 @@+{-# LANGUAGE CPP #-}+{-|+A partition of time into contiguous spans, for defining reporting periods.+-}+module Hledger.Data.DayPartition+( DayPartition+-- * constructors+, boundariesToDayPartition+, boundariesToMaybeDayPartition+-- * conversions+, dayPartitionToNonEmpty+, dayPartitionToList+, dayPartitionToDateSpans+, dayPartitionToPeriodData+, maybeDayPartitionToDateSpans+-- * operations+, unionDayPartitions+, dayPartitionStartEnd+, dayPartitionFind+, splitSpan+, splitSpanToDateSpans+, splitSpanStartEnd+, intervalBoundaryBefore+-- * tests+, tests_DayPartition+) where++#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List (sort)+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.List.NonEmpty as NE+import Data.Map qualified as M+import Data.Time (Day (..), addDays, addGregorianMonthsClip, addGregorianYearsClip, fromGregorian)++import Hledger.Data.Dates+import Hledger.Data.PeriodData+import Hledger.Data.Types+import Hledger.Utils+++-- | A partition of time into one or more contiguous periods,+-- plus a historical period that precedes them.+-- Note 'DayPartition' does not store per-period data - only the periods' start/end dates.++-- Each period is at least one day in length.+-- The historical period is open ended, with no start date.+-- The last period has an end date, but note some queries (like 'dayPartitionFind') ignore that, acting as if the last period is open ended.+-- Only smart constructors are exported, so that a DayPartition always satisfies these invariants.+--+-- This is implemented as a newtype wrapper around 'PeriodData Day', which is a map from date to date.+-- The map's keys are the period start dates, and the values are the corresponding period end dates.+-- Note unlike 'DateSpan', which stores exclusive end dates ( @[start, end)@ ),+-- here both start and end dates are inclusive ( @[start, end]@ ).+--+newtype DayPartition = DayPartition { dayPartitionToPeriodData :: PeriodData Day } deriving (Eq, Ord, Show)+++-- constructors:++-- | Construct a 'DayPartition' from a non-empty list of period boundary dates (start dates plus a final exclusive end date).+--+-- >>> boundariesToDayPartition (fromGregorian 2025 01 01 :| [fromGregorian 2025 02 01])+-- DayPartition {dayPartitionToPeriodData = PeriodData{ pdpre = 2024-12-31, pdperiods = fromList [(2025-01-01,2025-01-31)]}}+--+boundariesToDayPartition :: NonEmpty Day -> DayPartition+boundariesToDayPartition xs = DayPartition . periodDataFromList (addDays (-1) b) $ case bs of+ [] -> [(b, b)] -- If only one boundary is supplied, it ends on the same day+ _:_ -> zip (b:bs) $ map (addDays (-1)) bs -- Guaranteed non-empty+ where b:|bs = NE.map NE.head . NE.group1 $ NE.sort xs -- dedupe adjacent (not nub, which is quadratic)++-- | Construct a 'DayPartition' from a list of period boundary dates (start dates plus a final exclusive end date),+-- if it's a non-empty list.+boundariesToMaybeDayPartition :: [Day] -> Maybe DayPartition+boundariesToMaybeDayPartition = fmap boundariesToDayPartition . NE.nonEmpty+++-- conversions:++-- | Convert 'DayPartition' to a non-empty list of period start and end dates (both inclusive).+-- Each end date will be one day before the next period's start date.+dayPartitionToNonEmpty :: DayPartition -> NonEmpty (Day, Day)+dayPartitionToNonEmpty (DayPartition xs) = NE.fromList . snd $ periodDataToList xs -- Constructors guarantee this is non-empty++-- | Convert 'DayPartition' to a list (which will always be non-empty) of period start and end dates (both inclusive).+-- Each end date will be one day before the next period's start date.+dayPartitionToList :: DayPartition -> [(Day, Day)]+dayPartitionToList = NE.toList . dayPartitionToNonEmpty++-- | Convert 'DayPartition' to a list of 'DateSpan's.+-- Each span will end one day before the next span begins+-- (the span's exclusive end date will be equal to the next span's start date).+dayPartitionToDateSpans :: DayPartition -> [DateSpan]+dayPartitionToDateSpans = map toDateSpan . dayPartitionToList+ where+ toDateSpan (s, e) = DateSpan (toEFDay s) (toEFDay $ addDays 1 e)+ toEFDay = Just . Exact++-- Convert a 'Maybe DayPartition' to a list of one or more 'DateSpans'.+-- Each span will end one day before the next span begins+-- (the span's exclusive end date will be equal to the next span's start date).+-- If given Nothing, it returns a single open-ended span.+maybeDayPartitionToDateSpans :: Maybe DayPartition -> [DateSpan]+maybeDayPartitionToDateSpans = maybe [DateSpan Nothing Nothing] dayPartitionToDateSpans+++-- operations:++-- | Check that a DayPartition has been constructed correctly,+-- with internal invariants satisfied, as well as the external ones described in 'DayPartition'.+-- Internally, all constructors must guarantee:+-- 1. The pdperiods map contains at least one key and value.+-- 2. The value stored in pdpre is one day before pdperiods' smallest key.+-- 3. Each value stored in pdperiods is one day before the next largest key,+-- (except for the value associated with the largest key).+isValidDayPartition :: DayPartition -> Bool+isValidDayPartition (DayPartition pd) = case ds of+ [] -> False+ xs -> and $ zipWith isContiguous ((nulldate, h) : xs) xs+ where+ (h, ds) = periodDataToList pd+ isContiguous (_, e) (s, _) = addDays 1 e == s++-- | Return the union of two 'DayPartition's if that is a valid 'DayPartition',+-- or 'Nothing' otherwise.+unionDayPartitions :: DayPartition -> DayPartition -> Maybe DayPartition+unionDayPartitions (DayPartition (PeriodData h as)) (DayPartition (PeriodData h' as')) =+ if equalIntersection as as' && isValidDayPartition union then Just union else Nothing+ where+ union = DayPartition . PeriodData (min h h') $ as <> as'+ equalIntersection x y = and $ M.intersectionWith (==) x y++-- | Get this DayPartition's overall start date and end date (both inclusive).+dayPartitionStartEnd :: DayPartition -> (Day, Day)+dayPartitionStartEnd (DayPartition (PeriodData _ ds)) =+ -- Guaranteed not to error because the IntMap is non-empty.+ (fst $ M.findMin ds, snd $ M.findMax ds)++-- | Find the start and end dates of the period within a 'DayPartition' which contains a given day.+-- If the day is after the end of the last period, it is assumed to be within the last period.+-- If the day is before the start of the first period (ie, in the historical period),+-- only the historical period's end date is returned.+dayPartitionFind :: Day -> DayPartition -> (Maybe Day, Day)+dayPartitionFind d (DayPartition xs) = lookupPeriodDataOrHistorical d xs++-- | Split a 'DateSpan' into a 'DayPartition' consisting of consecutive exact+-- spans of the specified Interval, or `Nothing` if the span is invalid.+-- If no interval is specified, the original span is returned.+-- If the original span is the null date span, ie unbounded, `Nothing` is returned.+-- If the original span is empty, eg if the end date is <= the start date, `Nothing` is returned.+--+-- ==== Date adjustment+-- Some intervals respect the "adjust" flag (years, quarters, months, weeks, every Nth weekday+-- of month seem to be the ones that need it). This will move the start date earlier, if needed,+-- to the previous natural interval boundary (first of year, first of quarter, first of month,+-- monday, previous Nth weekday of month). Related: #1982 #2218+--+-- The end date is always moved later if needed to the next natural interval boundary,+-- so that the last period is the same length as the others.+--+-- ==== Examples+-- >>> let t i y1 m1 d1 y2 m2 d2 = fmap dayPartitionToNonEmpty . splitSpan True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)+-- >>> t NoInterval 2008 01 01 2009 01 01+-- Just ((2008-01-01,2008-12-31) :| [])+-- >>> t (Quarters 1) 2008 01 01 2009 01 01+-- Just ((2008-01-01,2008-03-31) :| [(2008-04-01,2008-06-30),(2008-07-01,2008-09-30),(2008-10-01,2008-12-31)])+-- >>> splitSpan True (Quarters 1) nulldatespan+-- Nothing+-- >>> t (Days 1) 2008 01 01 2008 01 01 -- an empty datespan+-- Nothing+-- >>> t (Quarters 1) 2008 01 01 2008 01 01+-- Nothing+-- >>> t (Months 1) 2008 01 01 2008 04 01+-- Just ((2008-01-01,2008-01-31) :| [(2008-02-01,2008-02-29),(2008-03-01,2008-03-31)])+-- >>> t (Months 2) 2008 01 01 2008 04 01+-- Just ((2008-01-01,2008-02-29) :| [(2008-03-01,2008-04-30)])+-- >>> t (Weeks 1) 2008 01 01 2008 01 15+-- Just ((2007-12-31,2008-01-06) :| [(2008-01-07,2008-01-13),(2008-01-14,2008-01-20)])+-- >>> t (Weeks 2) 2008 01 01 2008 01 15+-- Just ((2007-12-31,2008-01-13) :| [(2008-01-14,2008-01-27)])+-- >>> t (MonthDay 2) 2008 01 01 2008 04 01+-- Just ((2008-01-02,2008-02-01) :| [(2008-02-02,2008-03-01),(2008-03-02,2008-04-01)])+-- >>> t (NthWeekdayOfMonth 2 4) 2011 01 01 2011 02 15+-- Just ((2010-12-09,2011-01-12) :| [(2011-01-13,2011-02-09),(2011-02-10,2011-03-09)])+-- >>> t (DaysOfWeek [2]) 2011 01 01 2011 01 15+-- Just ((2010-12-28,2011-01-03) :| [(2011-01-04,2011-01-10),(2011-01-11,2011-01-17)])+-- >>> t (MonthAndDay 11 29) 2012 10 01 2013 10 15+-- Just ((2012-11-29,2013-11-28) :| [])+splitSpan :: Bool -> Interval -> DateSpan -> Maybe DayPartition+splitSpan adjust i ds = uncurry spansFromBoundaries =<< splitSpanBoundaries adjust i ds++-- | Like 'splitSpan', but returns the periods as a lazily generated list of 'DateSpan's+-- (each ending where the next begins), without building a 'DayPartition'.+-- Consuming this list once uses constant memory however many periods there are,+-- which matters for reports over very long spans with short intervals (#1683).+-- The list is empty when 'splitSpan' would return Nothing.+--+-- >>> let t i y1 m1 d1 y2 m2 d2 = splitSpanToDateSpans True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)+-- >>> t (Months 1) 2008 01 01 2008 04 01+-- [DateSpan 2008-01,DateSpan 2008-02,DateSpan 2008-03]+-- >>> t (Days 1) 2008 01 01 2008 01 01+-- []+splitSpanToDateSpans :: Bool -> Interval -> DateSpan -> [DateSpan]+splitSpanToDateSpans adjust i ds = case splitSpanBoundaries adjust i ds of+ Just (e, b:bs) | b < e -> zipWith mkspan bdrys (drop 1 bdrys)+ where bdrys = dedupeAdjacent $ takeUntilFails (<e) (b:bs)+ _ -> []+ where+ mkspan s e = DateSpan (Just $ Exact s) (Just $ Exact e)++-- | The start date and exclusive end date of the periods 'splitSpan' would produce+-- (ie the first boundary, and the first boundary not before the span's end),+-- found in constant memory. Nothing if 'splitSpan' would return Nothing.+splitSpanStartEnd :: Bool -> Interval -> DateSpan -> Maybe (Day, Day)+splitSpanStartEnd adjust i ds = case splitSpanBoundaries adjust i ds of+ Just (e, b:bs) | b < e -> Just (b, foldl' (\_ x -> x) b $ takeUntilFails (<e) bs)+ _ -> Nothing++-- | Remove adjacent duplicates from a list. Lazy, so it works on infinite lists.+dedupeAdjacent :: Eq a => [a] -> [a]+dedupeAdjacent = map NE.head . NE.group++-- | The ingredients of 'splitSpan': the exclusive end date of the range to be covered,+-- and the increasing, lazily generated (usually infinite) list of period boundary dates,+-- starting at or before the span's start date. Nothing if the span can't be split.+splitSpanBoundaries :: Bool -> Interval -> DateSpan -> Maybe (Day, [Day])+splitSpanBoundaries _ _ (DateSpan Nothing Nothing) = Nothing+splitSpanBoundaries _ _ ds | isEmptySpan ds = Nothing+splitSpanBoundaries _ NoInterval (DateSpan (Just s) (Just e)) = Just (fromEFDay e, [fromEFDay s, fromEFDay e])+splitSpanBoundaries _ NoInterval _ = Nothing+splitSpanBoundaries _ (Days n) ds = boundaries id addDays n ds+splitSpanBoundaries adjust (Weeks n) ds = boundaries (if adjust then startofweek else id) addDays (7*n) ds+splitSpanBoundaries adjust (Months n) ds = boundaries (if adjust then startofmonth else id) addGregorianMonthsClip n ds+splitSpanBoundaries adjust (Quarters n) ds = boundaries (if adjust then startofquarter else id) addGregorianMonthsClip (3*n) ds+splitSpanBoundaries adjust (Years n) ds = boundaries (if adjust then startofyear else id) addGregorianYearsClip n ds+splitSpanBoundaries adjust (NthWeekdayOfMonth n wd) ds = boundaries (startWeekdayOfMonth n wd) advancemonths 1 ds+ where+ startWeekdayOfMonth = if adjust then prevNthWeekdayOfMonth else nextNthWeekdayOfMonth+ advancemonths 0 = id+ advancemonths m = advanceToNthWeekday n wd . startofmonth . addGregorianMonthsClip m+splitSpanBoundaries _ (MonthDay dom) ds = boundaries (nextnthdayofmonth dom) (addGregorianMonthsToMonthday dom) 1 ds+splitSpanBoundaries _ (MonthAndDay m d) ds = boundaries (nextmonthandday m d) addGregorianYearsClip 1 ds+splitSpanBoundaries _ (DaysOfWeek []) _ = Nothing+splitSpanBoundaries _ (DaysOfWeek days@(n:_)) ds = do+ (s, e) <- dateSpanSplitLimits (nthdayofweekcontaining n) nextday ds+ let -- The first representative of each weekday, sorted so that the boundaries increase.+ starts = dedupeAdjacent . sort $ map (\d -> addDays (toInteger $ d - n) $ nthdayofweekcontaining n s) days+ -- can't show this when debugging, it'll hang:+ bdrys = concatMap (\d -> map (addDays d) starts) [0,7..]+ Just (e, bdrys)++-- | Fill in missing start/end dates for calculating 'splitSpan'.+dateSpanSplitLimits :: (Day -> Day) -> (Day -> Day) -> DateSpan -> Maybe (Day, Day)+dateSpanSplitLimits _ _ (DateSpan Nothing Nothing) = Nothing+dateSpanSplitLimits _ _ ds | isEmptySpan ds = Nothing+dateSpanSplitLimits start _ (DateSpan (Just s) (Just e)) = Just (start $ fromEFDay s, fromEFDay e)+dateSpanSplitLimits start next (DateSpan (Just s) Nothing) = Just (start $ fromEFDay s, next $ start $ fromEFDay s)+dateSpanSplitLimits start next (DateSpan Nothing (Just e)) = Just (start $ fromEFDay e, next $ start $ fromEFDay e)++-- Generate the period boundaries for splitting the given span, using the provided helper functions:+--+-- 1. The start function is used to adjust the provided span's start date to get the first boundary.+--+-- 2. The next function is used to calculate subsequent boundaries, possibly with stride increased by a multiplier.+-- It should handle spans of varying length, eg when splitting on "every 31st of month",+-- it adjusts to 28/29/30 in short months but returns to 31 in the long months.+--+-- Returns the exclusive end date of the range to cover, and the infinite list of boundaries.+boundaries :: (Day -> Day) -> (Integer -> Day -> Day) -> Int -> DateSpan -> Maybe (Day, [Day])+boundaries start next mult ds = do+ (s, e) <- dateSpanSplitLimits start (next (toInteger mult)) ds+ Just (e, map (\k -> next (toInteger k) (start s)) [0,mult..])++-- | Construct a list of exact 'DateSpan's from a list of boundaries, which fit within a given range.+spansFromBoundaries :: Day -> [Day] -> Maybe DayPartition+spansFromBoundaries _ [] = Nothing+spansFromBoundaries e (x:_) | x >= e = Nothing+spansFromBoundaries e (x:xs) = Just . boundariesToDayPartition $ takeUntilFailsNE (<e) (x:|xs)++-- | Get the natural start for the given interval that falls on or before the given day,+-- when applicable. Works for Weeks, Months, Quarters, Years, eg.+intervalBoundaryBefore :: Interval -> Day -> Day+intervalBoundaryBefore i d =+ case dayPartitionToNonEmpty <$> splitSpan True i (DateSpan (Just $ Exact d) (Just . Exact $ addDays 1 d)) of+ Just ((start, _) :| _ ) -> start+ _ -> d+++-- tests:++tests_DayPartition =+ testGroup "splitSpan" [+ testCase "weekday" $ do+ fmap dayPartitionToNonEmpty (splitSpan False (DaysOfWeek [1..5]) (DateSpan (Just $ Exact $ fromGregorian 2021 07 01) (Just $ Exact $ fromGregorian 2021 07 08)))+ @?= Just ( (fromGregorian 2021 06 28, fromGregorian 2021 06 28) :|+ [ (fromGregorian 2021 06 29, fromGregorian 2021 06 29)+ , (fromGregorian 2021 06 30, fromGregorian 2021 06 30)+ , (fromGregorian 2021 07 01, fromGregorian 2021 07 01)+ , (fromGregorian 2021 07 02, fromGregorian 2021 07 04)+ -- next week+ , (fromGregorian 2021 07 05, fromGregorian 2021 07 05)+ , (fromGregorian 2021 07 06, fromGregorian 2021 07 06)+ , (fromGregorian 2021 07 07, fromGregorian 2021 07 07)+ ])++ fmap dayPartitionToNonEmpty (splitSpan False (DaysOfWeek [1, 5]) (DateSpan (Just $ Exact $ fromGregorian 2021 07 01) (Just $ Exact $ fromGregorian 2021 07 08)))+ @?= Just ( (fromGregorian 2021 06 28, fromGregorian 2021 07 01) :|+ [ (fromGregorian 2021 07 02, fromGregorian 2021 07 04)+ -- next week+ , (fromGregorian 2021 07 05, fromGregorian 2021 07 08)+ ])++ , testCase "match dayOfWeek" $ do+ let dayofweek n ds = uncurry spansFromBoundaries =<< boundaries (nthdayofweekcontaining n) (\w -> (if w == 0 then id else applyN (n-1) nextday . applyN (fromInteger w) nextweek)) 1 ds+ matchdow ds day = splitSpan False (DaysOfWeek [day]) ds @?= dayofweek day ds+ ys2021 = fromGregorian 2021 01 01+ ye2021 = fromGregorian 2021 12 31+ ys2022 = fromGregorian 2022 01 01+ mapM_ (matchdow (DateSpan (Just $ Exact ys2021) (Just $ Exact ye2021))) [1..7]+ mapM_ (matchdow (DateSpan (Just $ Exact ys2021) (Just $ Exact ys2022))) [1..7]+ mapM_ (matchdow (DateSpan (Just $ Exact ye2021) (Just $ Exact ys2022))) [1..7]++ mapM_ (matchdow (DateSpan (Just $ Exact ye2021) Nothing)) [1..7]+ mapM_ (matchdow (DateSpan (Just $ Exact ys2022) Nothing)) [1..7]++ mapM_ (matchdow (DateSpan Nothing (Just $ Exact ye2021))) [1..7]+ mapM_ (matchdow (DateSpan Nothing (Just $ Exact ys2022))) [1..7]++ , testCase "splitSpanToDateSpans and splitSpanStartEnd agree with splitSpan" $ do+ let intervals = [NoInterval, Days 1, Days 3, Weeks 1, Weeks 2, Months 1, Months 5, Quarters 1, Years 1,+ NthWeekdayOfMonth 2 4, NthWeekdayOfMonth 5 7, MonthDay 2, MonthDay 31, MonthAndDay 11 29,+ DaysOfWeek [1..5], DaysOfWeek [5,1], DaysOfWeek [3,3,7]]+ d1 = fromGregorian 2021 01 01; d2 = fromGregorian 2024 03 15+ spans = [DateSpan (Just $ Exact d1) (Just $ Exact d2), DateSpan (Just $ Flex d1) (Just $ Flex d2),+ DateSpan (Just $ Exact d2) (Just $ Exact $ addDays 1 d2), DateSpan (Just $ Exact d1) Nothing,+ DateSpan Nothing (Just $ Exact d2), DateSpan (Just $ Exact d2) (Just $ Exact d1), nulldatespan]+ sequence_+ [ do splitSpanToDateSpans adjust i ds @?= maybe [] dayPartitionToDateSpans partition+ splitSpanStartEnd adjust i ds @?= fmap ((\(s, e) -> (s, addDays 1 e)) . dayPartitionStartEnd) partition+ | adjust <- [False, True], i <- intervals, ds <- spans, let partition = splitSpan adjust i ds ]++ ]
+ Hledger/Data/Errors.hs view
@@ -0,0 +1,285 @@+{-|+Helpers for making error messages.+-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}++module Hledger.Data.Errors (+ decorateExcerpt,+ makeAccountTagErrorExcerpt,+ makeCommodityTagErrorExcerpt,+ makePriceDirectiveErrorExcerpt,+ makeTransactionErrorExcerpt,+ makePostingErrorExcerpt,+ makePostingErrorExcerptByIndex,+ makePostingAccountErrorExcerpt,+ makeBalanceAssertionErrorExcerpt,+ transactionFindPostingIndex,+)+where++import Data.Function ((&))+import Data.List (find)+import Data.Text (Text)+import Data.Text qualified as T++import Hledger.Data.Transaction (showTransaction)+import Hledger.Data.Posting (postingStripCosts)+import Hledger.Data.Types+import Hledger.Utils+import Data.Maybe+import Safe (headMay)+import Hledger.Data.Posting (isVirtual)+import Hledger.Data.Amount (showPriceDirective)+++-- | Given an account name and its account directive, and a problem tag within the latter:+-- render it as a megaparsec-style excerpt, showing the original line number and+-- marked column or region.+-- Returns the file path, line number, column(s) if known,+-- and the rendered excerpt, or as much of these as is possible.+-- The returned columns will be accurate for the rendered error message but not for the original journal data.+makeAccountTagErrorExcerpt :: (AccountName, AccountDeclarationInfo) -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makeAccountTagErrorExcerpt (a, adi) _t = (f, l, merrcols, ex)+ -- XXX findtxnerrorcolumns is awkward, I don't think this is the final form+ where+ SourcePos f pos _ = adisourcepos adi+ l = unPos pos+ txt = showAccountDirective (a, adi) & textChomp & (<>"\n")+ ex = decorateExcerpt l merrcols txt+ -- Calculate columns which will help highlight the region in the excerpt+ -- (but won't exactly match the real data, so won't be shown in the main error line)+ merrcols = Nothing+ -- don't bother for now+ -- Just (col, Just col2)+ -- where+ -- col = undefined -- T.length (showTransactionLineFirstPart t') + 2+ -- col2 = undefined -- col + T.length tagname - 1 ++showAccountDirective (a, AccountDeclarationInfo{..}) =+ showDirectiveWithComment ("account " <> a) " ; " adicomment++-- | Given a commodity and a problem tag within it:+-- render it as a megaparsec-style excerpt, showing the original line number.+-- Returns the file path, line number, column(s) if known, and the rendered excerpt.+makeCommodityTagErrorExcerpt :: Commodity -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makeCommodityTagErrorExcerpt comm _t = (f, l, merrcols, ex)+ where+ SourcePos f pos _ = csourcepos comm+ l = unPos pos+ txt = showCommodityDirective comm & textChomp & (<>"\n")+ ex = decorateExcerpt l merrcols txt+ merrcols = Nothing++showCommodityDirective :: Commodity -> Text+showCommodityDirective Commodity{..} =+ showDirectiveWithComment ("commodity " <> csymbol) " ; " ccomment++-- | Render a directive's first line with its comment:+-- the comment's first line (if not empty) after the given separator on the same line,+-- and any further comment lines indented below it.+showDirectiveWithComment :: Text -> Text -> Text -> Text+showDirectiveWithComment directive sep comment =+ case T.lines comment of+ [] -> directive+ (l:ls) -> T.intercalate "\n" $+ (if T.null l then directive else directive <> sep <> l) : map (" ; " <>) ls++-- | Decorate a data excerpt with megaparsec-style left margin, line number,+-- and marker/underline for the column(s) if known, for inclusion in an error message.+decorateExcerpt :: Int -> Maybe (Int, Maybe Int) -> Text -> Text+decorateExcerpt l mcols txt =+ T.unlines $ ls' <> colmarkerline <> map (lineprefix<>) ms+ where+ (ls,ms) = splitAt 1 $ T.lines txt+ ls' = map ((T.pack (show l) <> " | ") <>) ls+ colmarkerline =+ [lineprefix <> T.replicate (col-1) " " <> T.replicate regionw "^"+ | Just (col, mendcol) <- [mcols]+ , let regionw = maybe 1 (subtract col) mendcol + 1+ ]+ lineprefix = T.replicate marginw " " <> "| "+ where marginw = length (show l) + 1++-- | Given a problem price directive,+-- and maybe a function to calculate the error region's column(s) (currently ignored):+-- generate a megaparsec-style error message with highlighted excerpt.+-- Returns the source file path, line number, column(s) if known, and the rendered excerpt,+-- or as much of these as possible.+-- Columns will be accurate for the rendered error message, not for the original journal entry.+makePriceDirectiveErrorExcerpt :: PriceDirective -> Maybe (PriceDirective -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makePriceDirectiveErrorExcerpt pd _finderrorcolumns = (file, line, merrcols, excerpt)+ where+ SourcePos file pos _ = pdsourcepos pd+ line = unPos pos+ merrcols = Nothing+ excerpt = decorateExcerpt line merrcols $ showPriceDirective pd <> "\n"++-- | Given a problem transaction and a function calculating the best+-- column(s) for marking the error region:+-- render it as a megaparsec-style excerpt, showing the original line number+-- on the transaction line, and a column(s) marker.+-- Returns the file path, line number, column(s) if known,+-- and the rendered excerpt, or as much of these as is possible.+-- The returned columns will be accurate for the rendered error message but not for the original journal data.+-- | Render a transaction for an error excerpt: without its preceding comment lines+-- (which are not part of the entry, and would shift the line numbering), chomped and newline-terminated.+showTransactionForExcerpt :: Transaction -> Text+showTransactionForExcerpt t = showTransaction t{tprecedingcomment=""} & textChomp & (<>"\n")++makeTransactionErrorExcerpt :: Transaction -> (Transaction -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makeTransactionErrorExcerpt t findtxnerrorcolumns = (f, tl, merrcols, ex)+ -- XXX findtxnerrorcolumns is awkward, I don't think this is the final form+ where+ SourcePos f tpos _ = fst $ tsourcepos t+ tl = unPos tpos+ txntxt = showTransactionForExcerpt t+ merrcols = findtxnerrorcolumns t+ ex = decorateTransactionErrorExcerpt tl merrcols txntxt++-- | Add megaparsec-style left margin, line number, and optional column marker(s).+decorateTransactionErrorExcerpt :: Int -> Maybe (Int, Maybe Int) -> Text -> Text+decorateTransactionErrorExcerpt l mcols txt =+ T.unlines $ ls' <> colmarkerline <> map (lineprefix<>) ms+ where+ (ls,ms) = splitAt 1 $ T.lines txt+ ls' = map ((T.pack (show l) <> " | ") <>) ls+ colmarkerline =+ [lineprefix <> T.replicate (col-1) " " <> T.replicate regionw "^"+ | Just (col, mendcol) <- [mcols]+ , let regionw = maybe 1 (subtract col) mendcol + 1+ ]+ lineprefix = T.replicate marginw " " <> "| "+ where marginw = length (show l) + 1++-- | Given a problem posting and a function calculating the best+-- column(s) for marking the error region:+-- look up error info from the parent transaction, and render the transaction+-- as a megaparsec-style excerpt, showing the original line number+-- on the problem posting's line, and a column indicator.+-- Returns the file path, line number, column(s) if known,+-- and the rendered excerpt, or as much of these as is possible.+-- A limitation: columns will be accurate for the rendered error message but not for the original journal data.+makePostingErrorExcerpt :: Posting -> (Posting -> Transaction -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makePostingErrorExcerpt p findpostingerrorcolumns =+ case ptransaction p of+ Nothing -> ("-", 0, Nothing, "")+ Just t -> (f, errabsline, merrcols, ex)+ where+ (SourcePos f tl _) = fst $ tsourcepos t+ -- p had cost removed in balanceTransactionAndCheckAssertionsB,+ -- must remove them from t's postings too (#2083)+ mpindex = transactionFindPostingIndex ((==p).postingStripCosts) t+ errrelline = case mpindex of+ Nothing -> 0+ Just pindex ->+ -- the posting's own comment lines follow it, so count only the earlier postings' lines+ commentExtraLines (tcomment t) ++ sum (map postingLines $ take (pindex - 1) $ tpostings t) + 1+ where+ -- How many lines are used to render this posting ?+ postingLines p' = 1 + commentExtraLines (pcomment p')+ -- How many extra lines does this comment add to a transaction or posting rendering ?+ commentExtraLines c = max 0 (length (T.lines c) - 1)+ errabsline = clampToTransactionLines t $ unPos tl + errrelline+ txntxt = showTransactionForExcerpt t+ merrcols = findpostingerrorcolumns p t txntxt+ ex = decoratePostingErrorExcerpt errabsline errrelline merrcols txntxt++-- | Add megaparsec-style left margin, line number, and optional column marker(s).+decoratePostingErrorExcerpt :: Int -> Int -> Maybe (Int, Maybe Int) -> Text -> Text+decoratePostingErrorExcerpt absline relline mcols txt =+ T.unlines $ js' <> ks' <> colmarkerline <> ms'+ where+ (ls,ms) = splitAt (relline+1) $ T.lines txt+ (js,ks) = splitAt (length ls - 1) ls+ (js',ks') = case ks of+ [k] -> (map (lineprefix<>) js, [T.pack (show absline) <> " | " <> k])+ _ -> ([], [])+ ms' = map (lineprefix<>) ms+ colmarkerline =+ [lineprefix <> T.replicate (col-1) " " <> T.replicate regionw "^"+ | Just (col, mendcol) <- [mcols]+ , let regionw = 1 + maybe 0 (subtract col) mendcol+ ]+ lineprefix = T.replicate marginw " " <> "| "+ where marginw = length (show absline) + 1++-- | Like 'makePostingErrorExcerpt', but identifies the posting by its+-- 0-based index in the transaction rather than by equality search.+-- This avoids false mismatches when postings have been modified after parsing+-- (e.g. by the balancer), and is unambiguous when duplicate postings exist.+-- The optional column tuple, if provided, adds a "^^^^" highlight under the posting.+makePostingErrorExcerptByIndex :: Transaction -> Int -> Maybe (Int, Maybe Int)+ -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makePostingErrorExcerptByIndex t idx mcols = (f, errabsline, mcols, ex)+ where+ (SourcePos f tl _) = fst $ tsourcepos t+ errrelline =+ -- the posting's own comment lines follow it, so count only the earlier postings' lines+ commentExtraLines (tcomment t) ++ sum (map postingLines $ take idx $ tpostings t) + 1+ where+ postingLines p' = 1 + commentExtraLines (pcomment p')+ commentExtraLines c = max 0 (length (T.lines c) - 1)+ errabsline = clampToTransactionLines t $ unPos tl + errrelline+ txntxt = showTransactionForExcerpt t+ ex = decoratePostingErrorExcerpt errabsline errrelline mcols txntxt++-- | Clamp a calculated error line number to this transaction's source line+-- range. Calculated posting line numbers count the lines of the rendered+-- entry, which can have more lines than the source region that produced it+-- (notably with CSV, where a one-line record can produce a many-line entry);+-- don't let them point beyond the entry's recorded source lines.+clampToTransactionLines :: Transaction -> Int -> Int+clampToTransactionLines t = max startline . min lastline+ where+ (SourcePos _ l1 _, SourcePos _ l2 c2) = tsourcepos t+ startline = unPos l1+ -- the end position is usually the start of the line after the entry+ lastline = max startline $ unPos l2 - if unPos c2 == 1 then 1 else 0++-- | Find the 1-based index of the first posting in this transaction+-- satisfying the given predicate.+transactionFindPostingIndex :: (Posting -> Bool) -> Transaction -> Maybe Int+transactionFindPostingIndex ppredicate = + fmap fst . find (ppredicate.snd) . zip [1..] . tpostings++-- | From the given posting, make an error excerpt showing the transaction with+-- this posting's account part highlighted.+makePostingAccountErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makePostingAccountErrorExcerpt p = makePostingErrorExcerpt p finderrcols+ where+ -- Calculate columns suitable for highlighting the synthetic excerpt.+ finderrcols p' _ _ = Just (col, Just col2)+ where+ col = 5 + if isVirtual p' then 1 else 0+ col2 = col + T.length (paccount p') - 1++-- | From the given posting, make an error excerpt showing the transaction with+-- the balance assertion highlighted.+makeBalanceAssertionErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)+makeBalanceAssertionErrorExcerpt p = makePostingErrorExcerpt p finderrcols+ where+ finderrcols p' t trendered = Just (col, Just col2)+ where+ -- Analyse the rendering to find the columns to highlight.+ tlines = dbg5 "tlines" $ max 1 $ length $ T.lines $ tcomment t -- transaction comment can generate extra lines+ (col, col2) =+ let def = (5, maximum (map T.length $ T.lines trendered)) -- fallback: underline whole posting. Shouldn't happen.+ in+ case transactionFindPostingIndex (==p') t of+ Nothing -> def+ Just idx -> fromMaybe def $ do+ let+ beforeps = take (idx-1) $ tpostings t+ beforepslines = dbg5 "beforepslines" $ sum $ map (max 1 . length . T.lines . pcomment) beforeps -- posting comment can generate extra lines (assume only one commodity shown)+ assertionline <- dbg5 "assertionline" $ headMay $ drop (tlines + beforepslines) $ T.lines trendered+ let+ col2' = T.length assertionline+ l = dropWhile (/= '=') $ reverse $ T.unpack assertionline+ l' = dropWhile (`elem` ['=','*']) l+ col' = length l' + 1+ return (col', col2')+
Hledger/Data/Journal.hs view
@@ -1,436 +1,1971 @@-{-|--A 'Journal' is a set of 'Transaction's and related data, usually parsed-from a hledger/ledger journal file or timelog. This is the primary hledger-data object.---}--module Hledger.Data.Journal-where-import Data.List-import Data.Map (findWithDefault, (!))-import Data.Ord-import Data.Time.Calendar-import Data.Time.LocalTime-import Data.Tree-import Safe (headDef)-import System.Time (ClockTime(TOD))-import Test.HUnit-import Text.Printf-import qualified Data.Map as Map--import Hledger.Utils-import Hledger.Data.Types-import Hledger.Data.AccountName-import Hledger.Data.Amount-import Hledger.Data.Commodity (canonicaliseCommodities)-import Hledger.Data.Dates (nulldatespan)-import Hledger.Data.Transaction (journalTransactionWithDate,balanceTransaction)-import Hledger.Data.Posting-import Hledger.Data.TimeLog-import Hledger.Data.Matching---instance Show Journal where- show j = printf "Journal %s with %d transactions, %d accounts: %s"- (journalFilePath j)- (length (jtxns j) +- length (jmodifiertxns j) +- length (jperiodictxns j))- (length accounts)- (show accounts)- -- ++ (show $ journalTransactions l)- where accounts = flatten $ journalAccountNameTree j--showJournalDebug j = unlines [- show j- ,show (jtxns j)- ,show (jmodifiertxns j)- ,show (jperiodictxns j)- ,show $ open_timelog_entries j- ,show $ historical_prices j- ,show $ final_comment_lines j- ,show $ jContext j- ,show $ map fst $ files j- ]--nulljournal :: Journal-nulljournal = Journal { jmodifiertxns = []- , jperiodictxns = []- , jtxns = []- , open_timelog_entries = []- , historical_prices = []- , final_comment_lines = []- , jContext = nullctx- , files = []- , filereadtime = TOD 0 0- }--nullctx :: JournalContext-nullctx = Ctx { ctxYear = Nothing, ctxCommodity = Nothing, ctxAccount = [], ctxAliases = [] }--nullfilterspec :: FilterSpec-nullfilterspec = FilterSpec {- datespan=nulldatespan- ,cleared=Nothing- ,real=False- ,empty=False- ,acctpats=[]- ,descpats=[]- ,depth=Nothing- }--journalFilePath :: Journal -> FilePath-journalFilePath = fst . mainfile--journalFilePaths :: Journal -> [FilePath]-journalFilePaths = map fst . files--mainfile :: Journal -> (FilePath, String)-mainfile = headDef ("", "") . files--addTransaction :: Transaction -> Journal -> Journal-addTransaction t l0 = l0 { jtxns = t : jtxns l0 }--addModifierTransaction :: ModifierTransaction -> Journal -> Journal-addModifierTransaction mt l0 = l0 { jmodifiertxns = mt : jmodifiertxns l0 }--addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal-addPeriodicTransaction pt l0 = l0 { jperiodictxns = pt : jperiodictxns l0 }--addHistoricalPrice :: HistoricalPrice -> Journal -> Journal-addHistoricalPrice h l0 = l0 { historical_prices = h : historical_prices l0 }--addTimeLogEntry :: TimeLogEntry -> Journal -> Journal-addTimeLogEntry tle l0 = l0 { open_timelog_entries = tle : open_timelog_entries l0 }--journalPostings :: Journal -> [Posting]-journalPostings = concatMap tpostings . jtxns--journalAccountNamesUsed :: Journal -> [AccountName]-journalAccountNamesUsed = sort . accountNamesFromPostings . journalPostings--journalAccountNames :: Journal -> [AccountName]-journalAccountNames = sort . expandAccountNames . journalAccountNamesUsed--journalAccountNameTree :: Journal -> Tree AccountName-journalAccountNameTree = accountNameTreeFrom . journalAccountNames---- Various kinds of filtering on journals. We do it differently depending--- on the command.------------------------------------------------------------------------------------ filtering V2---- | Keep only postings matching the query expression.--- This can leave unbalanced transactions.-filterJournalPostings2 :: Matcher -> Journal -> Journal-filterJournalPostings2 m j@Journal{jtxns=ts} = j{jtxns=map filtertransactionpostings ts}- where- filtertransactionpostings t@Transaction{tpostings=ps} = t{tpostings=filter (m `matchesPosting`) ps}---- | Keep only transactions matching the query expression.-filterJournalTransactions2 :: Matcher -> Journal -> Journal-filterJournalTransactions2 m j@Journal{jtxns=ts} = j{jtxns=filter (m `matchesTransaction`) ts}------------------------------------------------------------------------------------ filtering V1---- | Keep only transactions we are interested in, as described by the--- filter specification.-filterJournalTransactions :: FilterSpec -> Journal -> Journal-filterJournalTransactions FilterSpec{datespan=datespan- ,cleared=cleared- -- ,real=real- -- ,empty=empty- ,acctpats=apats- ,descpats=dpats- ,depth=depth- } =- filterJournalTransactionsByClearedStatus cleared .- filterJournalPostingsByDepth depth .- filterJournalTransactionsByAccount apats .- filterJournalTransactionsByDescription dpats .- filterJournalTransactionsByDate datespan---- | Keep only postings we are interested in, as described by the filter--- specification. This can leave unbalanced transactions.-filterJournalPostings :: FilterSpec -> Journal -> Journal-filterJournalPostings FilterSpec{datespan=datespan- ,cleared=cleared- ,real=real- ,empty=empty- ,acctpats=apats- ,descpats=dpats- ,depth=depth- } =- filterJournalPostingsByRealness real .- filterJournalPostingsByClearedStatus cleared .- filterJournalPostingsByEmpty empty .- filterJournalPostingsByDepth depth .- filterJournalPostingsByAccount apats .- filterJournalTransactionsByDescription dpats .- filterJournalTransactionsByDate datespan---- | Keep only transactions whose description matches the description patterns.-filterJournalTransactionsByDescription :: [String] -> Journal -> Journal-filterJournalTransactionsByDescription pats j@Journal{jtxns=ts} = j{jtxns=filter matchdesc ts}- where matchdesc = matchpats pats . tdescription---- | Keep only transactions which fall between begin and end dates.--- We include transactions on the begin date and exclude transactions on the end--- date, like ledger. An empty date string means no restriction.-filterJournalTransactionsByDate :: DateSpan -> Journal -> Journal-filterJournalTransactionsByDate (DateSpan begin end) j@Journal{jtxns=ts} = j{jtxns=filter match ts}- where match t = maybe True (tdate t>=) begin && maybe True (tdate t<) end---- | Keep only transactions which have the requested cleared/uncleared--- status, if there is one.-filterJournalTransactionsByClearedStatus :: Maybe Bool -> Journal -> Journal-filterJournalTransactionsByClearedStatus Nothing j = j-filterJournalTransactionsByClearedStatus (Just val) j@Journal{jtxns=ts} = j{jtxns=filter match ts}- where match = (==val).tstatus---- | Keep only postings which have the requested cleared/uncleared status,--- if there is one.-filterJournalPostingsByClearedStatus :: Maybe Bool -> Journal -> Journal-filterJournalPostingsByClearedStatus Nothing j = j-filterJournalPostingsByClearedStatus (Just c) j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}- where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter ((==c) . postingCleared) ps}---- | Strip out any virtual postings, if the flag is true, otherwise do--- no filtering.-filterJournalPostingsByRealness :: Bool -> Journal -> Journal-filterJournalPostingsByRealness False l = l-filterJournalPostingsByRealness True j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}- where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter isReal ps}---- | Strip out any postings with zero amount, unless the flag is true.-filterJournalPostingsByEmpty :: Bool -> Journal -> Journal-filterJournalPostingsByEmpty True l = l-filterJournalPostingsByEmpty False j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}- where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (not . isEmptyPosting) ps}---- | Keep only transactions which affect accounts deeper than the specified depth.-filterJournalTransactionsByDepth :: Maybe Int -> Journal -> Journal-filterJournalTransactionsByDepth Nothing j = j-filterJournalTransactionsByDepth (Just d) j@Journal{jtxns=ts} =- j{jtxns=(filter (any ((<= d+1) . accountNameLevel . paccount) . tpostings) ts)}---- | Strip out any postings to accounts deeper than the specified depth--- (and any transactions which have no postings as a result).-filterJournalPostingsByDepth :: Maybe Int -> Journal -> Journal-filterJournalPostingsByDepth Nothing j = j-filterJournalPostingsByDepth (Just d) j@Journal{jtxns=ts} =- j{jtxns=filter (not . null . tpostings) $ map filtertxns ts}- where filtertxns t@Transaction{tpostings=ps} =- t{tpostings=filter ((<= d) . accountNameLevel . paccount) ps}---- | Keep only transactions which affect accounts matched by the account patterns.--- More precisely: each positive account pattern excludes transactions--- which do not contain a posting to a matched account, and each negative--- account pattern excludes transactions containing a posting to a matched--- account.-filterJournalTransactionsByAccount :: [String] -> Journal -> Journal-filterJournalTransactionsByAccount apats j@Journal{jtxns=ts} = j{jtxns=filter tmatch ts}- where- tmatch t = (null positives || any positivepmatch ps) && (null negatives || not (any negativepmatch ps)) where ps = tpostings t- positivepmatch p = any (`amatch` a) positives where a = paccount p- negativepmatch p = any (`amatch` a) negatives where a = paccount p- amatch pat a = regexMatchesCI (abspat pat) a- (negatives,positives) = partition isnegativepat apats---- | Keep only postings which affect accounts matched by the account patterns.--- This can leave transactions unbalanced.-filterJournalPostingsByAccount :: [String] -> Journal -> Journal-filterJournalPostingsByAccount apats j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}- where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (matchpats apats . paccount) ps}---- | Convert this journal's transactions' primary date to either the--- actual or effective date.-journalSelectingDate :: WhichDate -> Journal -> Journal-journalSelectingDate ActualDate j = j-journalSelectingDate EffectiveDate j =- j{jtxns=map (journalTransactionWithDate EffectiveDate) $ jtxns j}---- | Apply additional account aliases (eg from the command-line) to all postings in a journal.-journalApplyAliases :: [(AccountName,AccountName)] -> Journal -> Journal-journalApplyAliases aliases j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}- where- fixtransaction t@Transaction{tpostings=ps} = t{tpostings=map fixposting ps}- fixposting p@Posting{paccount=a} = p{paccount=accountNameApplyAliases aliases a}---- | Do post-parse processing on a journal, to make it ready for use.-journalFinalise :: ClockTime -> LocalTime -> FilePath -> String -> JournalContext -> Journal -> Either String Journal-journalFinalise tclock tlocal path txt ctx j@Journal{files=fs} =- journalBalanceTransactions $- journalCanonicaliseAmounts $- journalApplyHistoricalPrices $- journalCloseTimeLogEntries tlocal- j{files=(path,txt):fs, filereadtime=tclock, jContext=ctx}---- | Fill in any missing amounts and check that all journal transactions--- balance, or return an error message. This is done after parsing all--- amounts and working out the canonical commodities, since balancing--- depends on display precision. Reports only the first error encountered.-journalBalanceTransactions :: Journal -> Either String Journal-journalBalanceTransactions j@Journal{jtxns=ts} =- case sequence $ map balance ts of Right ts' -> Right j{jtxns=ts'}- Left e -> Left e- where balance = balanceTransaction (Just $ journalCanonicalCommodities j)---- | Convert all the journal's amounts to their canonical display--- settings. Ie, all amounts in a given commodity will use (a) the--- display settings of the first, and (b) the greatest precision, of the--- amounts in that commodity. Prices are canonicalised as well, so consider--- calling journalApplyHistoricalPrices before this.-journalCanonicaliseAmounts :: Journal -> Journal-journalCanonicaliseAmounts j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}- where- fixtransaction t@Transaction{tpostings=ps} = t{tpostings=map fixposting ps}- fixposting p@Posting{pamount=a} = p{pamount=fixmixedamount a}- fixmixedamount (Mixed as) = Mixed $ map fixamount as- fixamount a@Amount{commodity=c} = a{commodity=fixcommodity c}- fixcommodity c@Commodity{symbol=s} = findWithDefault c s canonicalcommoditymap- canonicalcommoditymap = journalCanonicalCommodities j---- | Apply this journal's historical price records to unpriced amounts where possible.-journalApplyHistoricalPrices :: Journal -> Journal-journalApplyHistoricalPrices j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}- where- fixtransaction t@Transaction{tdate=d, tpostings=ps} = t{tpostings=map fixposting ps}- where- fixposting p@Posting{pamount=a} = p{pamount=fixmixedamount a}- fixmixedamount (Mixed as) = Mixed $ map fixamount as- fixamount = fixprice- fixprice a@Amount{price=Just _} = a- fixprice a@Amount{commodity=c} = a{price=maybe Nothing (Just . UnitPrice) $ journalHistoricalPriceFor j d c}---- | Get the price for a commodity on the specified day from the price database, if known.--- Does only one lookup step, ie will not look up the price of a price.-journalHistoricalPriceFor :: Journal -> Day -> Commodity -> Maybe MixedAmount-journalHistoricalPriceFor j d Commodity{symbol=s} = do- let ps = reverse $ filter ((<= d).hdate) $ filter ((s==).hsymbol) $ sortBy (comparing hdate) $ historical_prices j- case ps of (HistoricalPrice{hamount=a}:_) -> Just a- _ -> Nothing---- | Close any open timelog sessions in this journal using the provided current time.-journalCloseTimeLogEntries :: LocalTime -> Journal -> Journal-journalCloseTimeLogEntries now j@Journal{jtxns=ts, open_timelog_entries=es} =- j{jtxns = ts ++ (timeLogEntriesToTransactions now es), open_timelog_entries = []}---- | Convert all this journal's amounts to cost by applying their prices, if any.-journalConvertAmountsToCost :: Journal -> Journal-journalConvertAmountsToCost j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}- where- -- similar to journalCanonicaliseAmounts- fixtransaction t@Transaction{tpostings=ps} = t{tpostings=map fixposting ps}- fixposting p@Posting{pamount=a} = p{pamount=fixmixedamount a}- fixmixedamount (Mixed as) = Mixed $ map fixamount as- fixamount = canonicaliseAmountCommodity (Just $ journalCanonicalCommodities j) . costOfAmount---- | Get this journal's unique, display-preference-canonicalised commodities, by symbol.-journalCanonicalCommodities :: Journal -> Map.Map String Commodity-journalCanonicalCommodities j = canonicaliseCommodities $ journalAmountCommodities j---- | Get all this journal's amounts' commodities, in the order parsed.-journalAmountCommodities :: Journal -> [Commodity]-journalAmountCommodities = map commodity . concatMap amounts . journalAmounts---- | Get all this journal's amount and price commodities, in the order parsed.-journalAmountAndPriceCommodities :: Journal -> [Commodity]-journalAmountAndPriceCommodities = concatMap amountCommodities . concatMap amounts . journalAmounts---- | Get this amount's commodity and any commodities referenced in its price.-amountCommodities :: Amount -> [Commodity]-amountCommodities Amount{commodity=c,price=p} =- case p of Nothing -> [c]- Just (UnitPrice ma) -> c:(concatMap amountCommodities $ amounts ma)- Just (TotalPrice ma) -> c:(concatMap amountCommodities $ amounts ma)---- | Get all this journal's amounts, in the order parsed.-journalAmounts :: Journal -> [MixedAmount]-journalAmounts = map pamount . journalPostings---- | The (fully specified) date span containing this journal's transactions,--- or DateSpan Nothing Nothing if there are none.-journalDateSpan :: Journal -> DateSpan-journalDateSpan j- | null ts = DateSpan Nothing Nothing- | otherwise = DateSpan (Just $ tdate $ head ts) (Just $ addDays 1 $ tdate $ last ts)- where- ts = sortBy (comparing tdate) $ jtxns j---- | Check if a set of hledger account/description filter patterns matches the--- given account name or entry description. Patterns are case-insensitive--- regular expressions. Prefixed with not:, they become anti-patterns.-matchpats :: [String] -> String -> Bool-matchpats pats str =- (null positives || any match positives) && (null negatives || not (any match negatives))- where- (negatives,positives) = partition isnegativepat pats- match "" = True- match pat = regexMatchesCI (abspat pat) str--negateprefix = "not:"--isnegativepat = (negateprefix `isPrefixOf`)--abspat pat = if isnegativepat pat then drop (length negateprefix) pat else pat---- | Calculate the account tree and all account balances from a journal's--- postings, returning the results for efficient lookup.-journalAccountInfo :: Journal -> (Tree AccountName, Map.Map AccountName Account)-journalAccountInfo j = (ant, amap)- where- (ant, psof, _, inclbalof) = (groupPostings . journalPostings) j- amap = Map.fromList [(a, acctinfo a) | a <- flatten ant]- acctinfo a = Account a (psof a) (inclbalof a)---- | Given a list of postings, return an account name tree and three query--- functions that fetch postings, subaccount-excluding-balance and--- subaccount-including-balance by account name.-groupPostings :: [Posting] -> (Tree AccountName,- (AccountName -> [Posting]),- (AccountName -> MixedAmount),- (AccountName -> MixedAmount))-groupPostings ps = (ant, psof, exclbalof, inclbalof)- where- anames = sort $ nub $ map paccount ps- ant = accountNameTreeFrom $ expandAccountNames anames- allanames = flatten ant- pmap = Map.union (postingsByAccount ps) (Map.fromList [(a,[]) | a <- allanames])- psof = (pmap !)- balmap = Map.fromList $ flatten $ calculateBalances ant psof- exclbalof = fst . (balmap !)- inclbalof = snd . (balmap !)---- | Add subaccount-excluding and subaccount-including balances to a tree--- of account names somewhat efficiently, given a function that looks up--- transactions by account name.-calculateBalances :: Tree AccountName -> (AccountName -> [Posting]) -> Tree (AccountName, (MixedAmount, MixedAmount))-calculateBalances ant psof = addbalances ant- where- addbalances (Node a subs) = Node (a,(bal,bal+subsbal)) subs'- where- bal = sumPostings $ psof a- subsbal = sum $ map (snd . snd . root) subs'- subs' = map addbalances subs---- | Convert a list of postings to a map from account name to that--- account's postings.-postingsByAccount :: [Posting] -> Map.Map AccountName [Posting]-postingsByAccount ps = m'- where- sortedps = sortBy (comparing paccount) ps- groupedps = groupBy (\p1 p2 -> paccount p1 == paccount p2) sortedps- m' = Map.fromList [(paccount $ head g, g) | g <- groupedps]---- debug helpers-traceAmountPrecision a = trace (show $ map (precision . commodity) $ amounts a) a-tracePostingsCommodities ps = trace (show $ map ((map (precision . commodity) . amounts) . pamount) ps) ps--tests_Hledger_Data_Journal = TestList [- ]-+{-# LANGUAGE CPP #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE RecordWildCards #-}++{-|++A 'Journal' is a set of transactions, plus optional related data. This is+hledger's primary data object. It is usually parsed from a journal file or+other data format (see "Hledger.Read").++-}++module Hledger.Data.Journal (+ -- * Parsing helpers+ JournalParser,+ ErroringJournalParser,+ addPriceDirective,+ addTransactionModifier,+ addJournalItem,+ addTransactionItem,+ addPeriodicTransaction,+ addAssertDirective,+ addTransaction,+ journalDbg,+ journalInferMarketPricesFromTransactions,+ journalApplyCommodityAliases,+ CommodityAliases,+ journalCommodityAliases,+ convertAliasAmount,+ commodityAliases,+ commodityRedeclare,+ commodityCombine,+ commoditiesAndAliases,+ journalInferCommodityStyles,+ journalStyleAmounts,+ journalCommodityStyles,+ journalCommodityStylesWith,+ journalToCost,+ journalInferEquityFromCosts,+ journalTagCostsAndEquityAndMaybeInferCosts,+ journalReverse,+ journalSetLastReadTime,+ journalRenumberAccountDeclarations,+ journalPivot,+ journalPostingsAddAccountTags,+ journalPostingsKeepAccountTagsOnly,+ journalPostingsAddCommodityTags,+ journalInferPostingsTransactedCost,+ journalCommodityUsesLots,+ journalAccountUsesNoLots,+ journalAccountLotsTags,+ accountUsesNoLotsWith,+ journalLotfulCommodities,+ journalCommodityLotsMethod,+ postingLotsMethod,+ parseReductionMethod,+ journalCheckLotsTagValues,+-- * Filtering+ filterJournalTransactions,+ filterJournalPostings,+ filterJournalRelatedPostings,+ filterJournalAmounts,+ filterTransactionAmounts,+ filterTransactionPostings,+ filterTransactionPostingsExtra,+ filterTransactionRelatedPostings,+ filterPostingAmount,+ -- * Mapping+ journalMapTransactions,+ journalMapPostings,+ journalMapPostingAmounts,+ -- * Querying+ journalAccountNamesUsed,+ journalAccountNamesImplied,+ journalAccountNamesDeclared,+ journalAccountNamesDeclaredOrUsed,+ journalAccountNamesDeclaredOrImplied,+ journalAccountNames,+ journalLeafAccountNames,+ journalAccountNameTree,+ journalAccountTags,+ journalCommodityTags,+ journalInheritedAccountTags,+ -- journalAmountAndPriceCommodities,+ -- journalAmountStyles,+ -- overJournalAmounts,+ -- traverseJournalAmounts,+ -- journalCanonicalCommodities,+ journalPayeesDeclared,+ journalPayeesUsed,+ journalPayeesDeclaredOrUsed,+ journalTagsDeclared,+ journalTagsUsed,+ journalTagsDeclaredOrUsed,+ journalAmounts,+ journalPostingAmounts,+ journalPostingAndCostAmounts,+ journalCommoditiesDeclared,+ journalCommoditiesUsed,+ journalCommodities,+ journalCommoditiesFromPriceDirectives,+ journalCommoditiesFromTransactions,+ journalBaseCurrency,+ journalBaseCurrencyCode,+ journalDateSpan,+ journalDateSpanBothDates,+ journalStartDate,+ journalEndDate,+ journalLastDay,+ journalDescriptions,+ journalFilePath,+ journalFilePaths,+ journalAllFilePaths,+ journalTransactionAt,+ journalNextTransaction,+ journalPrevTransaction,+ journalPostings,+ showJournalPostingAmountsDebug,+ journalTransactionsSimilarTo,+ -- * Account types+ journalAccountType,+ journalAccountTypes,+ journalAddAccountTypes,+ -- * Conversion accounts+ defaultBaseConversionAccount,+ journalAccountForType,+ journalBaseConversionAccount,+ journalConversionAccounts,+ -- * Gain accounts+ defaultGainAccount,+ journalBaseGainAccount,+ journalGainAccounts,+ -- * Misc+ nulljournal,+ journalConcat,+ journalNumberTransactions,+ journalNumberAndTieTransactions,+ journalTieTransactions,+ journalUntieTransactions,+ journalModifyTransactions,+ journalApplyAliases,+ dbgJournalAcctDeclOrder,+ -- * Tests+ samplejournal,+ samplejournalMaybeExplicit,+ tests_Journal,+ --+)+where++import Control.Applicative ((<|>))+import Control.Monad.Except (ExceptT(..))+import Control.Monad.State.Strict (StateT)+import Data.Char (toUpper, isDigit)+import Data.Containers.ListUtils (nubOrd)+import Data.Decimal (normalizeDecimal)+import Data.Default (Default(..))+import Data.Foldable (toList)+import Data.Function ((&), on)+import Data.List (find, intercalate, minimumBy, sortBy, union, unionBy, (\\))+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List.Extra (nubSort)+import Data.Array qualified as A+import Data.Map.Strict qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybeToList)+import Data.Ord (comparing)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day(..), addDays, diffDays, fromGregorian)+import Data.Time.Clock.POSIX (POSIXTime)+import Data.Tree (Tree (..), flatten)+import Safe (headMay, headDef, maximumMay, minimumMay)+import System.FilePath (takeFileName)+import Text.Printf (printf)+import Text.Megaparsec (ParsecT)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.AccountName+import Hledger.Data.AccountType (accountTypeLotDirection, isEquityType, lotDirectionSign)+import Hledger.Data.Amount+import Hledger.Data.Currency (CurrencyCode, toCurrencyCode)+import Hledger.Data.Errors (makeAccountTagErrorExcerpt, makeCommodityTagErrorExcerpt)+import Hledger.Data.Posting+import Hledger.Data.Transaction+import Hledger.Data.TransactionModifier+import Hledger.Data.Valuation+import Hledger.Query+++-- | A parser of text that runs in some monad, keeping a Journal as state.+type JournalParser m a = StateT Journal (ParsecT HledgerParseErrorData Text m) a++-- | A parser of text that runs in some monad, keeping a Journal as+-- state, that can throw an exception to end parsing, preventing+-- further parser backtracking.+type ErroringJournalParser m a =+ StateT Journal (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a++-- deriving instance Show Journal+instance Show Journal where+ show j+ | debugLevel < 3 = printf "Journal %s with %d transactions, %d accounts"+ (journalFilePath j)+ (length $ jtxns j)+ (length accounts)+ | debugLevel < 6 = printf "Journal %s with %d transactions, %d accounts: %s"+ (journalFilePath j)+ (length $ jtxns j)+ (length accounts)+ (show accounts)+ | otherwise = printf "Journal %s with %d transactions, %d accounts: %s, commodity styles: %s"+ (journalFilePath j)+ (length $ jtxns j)+ (length accounts)+ (show accounts)+ (show $ jinferredcommoditystyles j)+ -- ++ (show $ journalTransactions l)+ where accounts = filter (/= "root") $ flatten $ journalAccountNameTree j++journalDbg j@Journal{..} = chomp $ unlines $+ ("Journal " ++ takeFileName (journalFilePath j)++":") : -- ++ " {"+ map (" "<>) [+ "jparsedefaultyear: " <> shw jparsedefaultyear+ ,"jparseapplyyears: " <> shw jparseapplyyears+ ,"jparsedefaultcommodity: " <> shw jparsedefaultcommodity+ ,"jparsedecimalmark: " <> shw jparsedecimalmark+ ,"jparseparentaccounts: " <> shw jparseparentaccounts+ ,"jparsealiases: " <> shw jparsealiases+ ,"jparseoptaliases: " <> shw jparseoptaliases+ -- ,"jparsetimeclockentries: " <> shw jparsetimeclockentries+ ,"jparseincludefilestack: " <> shw jparseincludefilestack+ ,"jdeclaredpayees: " <> shw jdeclaredpayees+ ,"jdeclaredtags: " <> shw jdeclaredtags+ ,"jdeclaredaccounts: " <> shw jdeclaredaccounts+ ,"jdeclaredaccounttags: " <> shw jdeclaredaccounttags+ ,"jdeclaredaccounttypes: " <> shw jdeclaredaccounttypes+ ,"jaccounttypes: " <> shw jaccounttypes+ ,"jdeclaredcommodities: " <> shw jdeclaredcommodities+ ,"jinferredcommoditystyles: " <> shw jinferredcommoditystyles+ ,"jglobalcommoditystyles: " <> shw jglobalcommoditystyles+ ,"jpricedirectives: " <> shw jpricedirectives+ ,"jinferredmarketprices: " <> shw jinferredmarketprices+ ,"jtxnmodifiers: " <> shw jtxnmodifiers+ -- ,"jperiodictxns: " <> shw jperiodictxns+ ,"jasserts: " <> shw jasserts+ ,"jtxns: " <> shw jtxns+ ,"jitems: " <> shw (length jitems)+ ,"jfiles: " <> shw jfiles+ ,"jauxfiles: " <> shw jauxfiles+ ,"jlastreadtime: " <> shw jlastreadtime+ ]+ -- ++ ["}"]+ where+ shw :: Show a => a -> String+ shw = show+ -- shw = pshow++-- The semigroup instance for Journal is useful for two situations.+--+-- 1. concatenating finalised journals, eg with multiple -f options:+-- FIRST <> SECOND.+--+-- 2. merging a child parsed journal, eg with the include directive:+-- CHILD <> PARENT. A parsed journal's data is in reverse order, so+-- this gives what we want.+--+-- Note that (<>) is right-biased, so nulljournal is only a left identity.+-- In particular, this prevents Journal from being a monoid.+instance Semigroup Journal where j1 <> j2 = j1 `journalConcat` j2++-- | Merge two journals into one.+-- Transaction counts are summed, map fields are combined,+-- the second's list fields are appended to the first's,+-- the second's parse state is kept.+journalConcat :: Journal -> Journal -> Journal+journalConcat j1 j2 =+ let+ f1 = takeFileName $ journalFilePath j1+ f2 = maybe "(unknown)" takeFileName $ fmap fst $ headMay $ jparseincludefilestack j2 -- XXX more accurate than journalFilePath for some reason+ in+ dbgJournalAcctDeclOrder ("journalConcat: " <> f1 <> " <> " <> f2 <> ", acct decls renumbered: ") $+ journalRenumberAccountDeclarations $+ dbgJournalAcctDeclOrder ("journalConcat: " <> f1 <> " <> " <> f2 <> ", acct decls : ") $+ Journal {+ jparsedefaultyear = jparsedefaultyear j2+ ,jparseapplyyears = jparseapplyyears j2+ ,jparsedefaultcommodity = jparsedefaultcommodity j2+ ,jparsedecimalmark = jparsedecimalmark j2+ ,jparseparentaccounts = jparseparentaccounts j2+ ,jparsealiases = jparsealiases j2+ ,jparseoptaliases = jparseoptaliases j2+ -- ,jparsetransactioncount = jparsetransactioncount j1 + jparsetransactioncount j2+ ,jparsetimeclockentries = jparsetimeclockentries j1 <> jparsetimeclockentries j2+ ,jparseincludefilestack = jparseincludefilestack j2+ ,jparsepos = jparsepos j2+ ,jparseamountstyles = jparseamountstyles j2+ ,jparsetexts = jparsetexts j2+ ,jparsefastpathstats = jparsefastpathstats j1 <> jparsefastpathstats j2+ ,jdeclaredpayees = jdeclaredpayees j1 <> jdeclaredpayees j2+ ,jdeclaredtags = jdeclaredtags j1 <> jdeclaredtags j2+ ,jdeclaredaccounts = jdeclaredaccounts j1 <> jdeclaredaccounts j2+ --+ -- The next six fields are Maps, which need to be merged carefully for correct semantics,+ -- especially the first two, which have list values. There may still be room for improvement here.+ --+ -- ,jdeclaredaccounttags :: M.Map AccountName [Tag]+ -- jdeclaredaccounttags can have multiple duplicated/conflicting values for an account's tag.+ ,jdeclaredaccounttags = M.unionWith (<>) (jdeclaredaccounttags j1) (jdeclaredaccounttags j2)+ --+ -- ,jdeclaredaccounttypes :: M.Map AccountType [AccountName]+ -- jdeclaredaccounttypes can have multiple duplicated/conflicting values for an account's type.+ ,jdeclaredaccounttypes = M.unionWith (<>) (jdeclaredaccounttypes j1) (jdeclaredaccounttypes j2)+ --+ -- ,jaccounttypes :: M.Map AccountName AccountType+ -- jaccounttypes has a single type for any given account. When it had multiple type declarations, the last/rightmost wins.+ ,jaccounttypes = M.unionWith (const id) (jaccounttypes j1) (jaccounttypes j2)+ --+ -- ,jglobalcommoditystyles :: M.Map CommoditySymbol AmountStyle+ ,jglobalcommoditystyles = (<>) (jglobalcommoditystyles j1) (jglobalcommoditystyles j2)+ --+ -- ,jdeclaredcommodities :: M.Map CommoditySymbol Commodity+ -- A commodity declared in both is combined, preferring j1's declaration, see commodityCombine.+ -- (When merging an included file, j1 is the included file, whose declarations are the later ones.+ -- Files read with several -f options are combined differently, see Hledger.Read.combineCommodityDeclarations.)+ ,jdeclaredcommodities = M.unionWith commodityCombine (jdeclaredcommodities j1) (jdeclaredcommodities j2)+ --+ -- ,jdeclaredcommoditytags :: M.Map CommoditySymbol [Tag]+ ,jdeclaredcommoditytags = M.unionWith (<>) (jdeclaredcommoditytags j1) (jdeclaredcommoditytags j2)+ --+ -- ,jinferredcommoditystyles :: M.Map CommoditySymbol AmountStyle+ ,jinferredcommoditystyles = (<>) (jinferredcommoditystyles j1) (jinferredcommoditystyles j2)+ --+ --+ ,jpricedirectives = jpricedirectives j1 <> jpricedirectives j2+ ,jinferredmarketprices = jinferredmarketprices j1 <> jinferredmarketprices j2+ ,jtxnmodifiers = jtxnmodifiers j1 <> jtxnmodifiers j2+ ,jperiodictxns = jperiodictxns j1 <> jperiodictxns j2+ ,jasserts = jasserts j1 <> jasserts j2+ ,jtxns = jtxns j1 <> jtxns j2+ ,jitems = jitems j1 <> jitems j2+ ,jfiles = jfiles j1 <> jfiles j2+ ,jauxfiles = jauxfiles j1 <> jauxfiles j2+ ,jlastreadtime = max (jlastreadtime j1) (jlastreadtime j2)+ }++-- | Renumber all the account declarations. This is useful to call when+-- finalising or concatenating Journals, to give account declarations+-- a total order across files.+journalRenumberAccountDeclarations :: Journal -> Journal+journalRenumberAccountDeclarations j = j{jdeclaredaccounts=jdas'}+ where+ jdas' = [(a, adi{adideclarationorder=n}) | (n, (a,adi)) <- zip [1..] $ jdeclaredaccounts j]+ -- the per-file declaration order saved during parsing is discarded,+ -- it seems unneeded except perhaps for debugging++-- | Debug log the ordering of a journal's account declarations+-- (at debug level 7+).+dbgJournalAcctDeclOrder :: String -> Journal -> Journal+dbgJournalAcctDeclOrder prefix =+ dbg7With ((prefix++) . showAcctDeclsSummary . jdeclaredaccounts)+ where+ showAcctDeclsSummary :: [(AccountName,AccountDeclarationInfo)] -> String+ showAcctDeclsSummary adis+ | length adis < (2*n+2) = "[" <> showadis adis <> "]"+ | otherwise =+ "[" <> showadis (take n adis) <> " ... " <> showadis (takelast n adis) <> "]"+ where+ n = 3+ showadis = intercalate ", " . map showadi+ showadi (a,adi) = "("<>show (adideclarationorder adi)<>","<>T.unpack a<>")"+ takelast n' = reverse . take n' . reverse++instance Default Journal where+ def = nulljournal++nulljournal :: Journal+nulljournal = Journal {+ jparsedefaultyear = Nothing+ ,jparseapplyyears = []+ ,jparsedefaultcommodity = Nothing+ ,jparsedecimalmark = Nothing+ ,jparseparentaccounts = []+ ,jparsealiases = []+ ,jparseoptaliases = []+ -- ,jparsetransactioncount = 0+ ,jparsetimeclockentries = []+ ,jparseincludefilestack = []+ ,jparsepos = Nothing+ ,jparseamountstyles = S.empty+ ,jparsetexts = S.empty+ ,jparsefastpathstats = mempty+ ,jdeclaredpayees = []+ ,jdeclaredtags = []+ ,jdeclaredaccounts = []+ ,jdeclaredaccounttags = M.empty+ ,jdeclaredaccounttypes = M.empty+ ,jaccounttypes = M.empty+ ,jglobalcommoditystyles = M.empty+ ,jdeclaredcommodities = M.empty+ ,jdeclaredcommoditytags = M.empty+ ,jinferredcommoditystyles = M.empty+ ,jpricedirectives = []+ ,jinferredmarketprices = []+ ,jtxnmodifiers = []+ ,jperiodictxns = []+ ,jasserts = []+ ,jtxns = []+ ,jitems = []+ ,jfiles = []+ ,jauxfiles = []+ ,jlastreadtime = 0+ }++journalFilePath :: Journal -> FilePath+journalFilePath = jfpath . mainfile++journalFilePaths :: Journal -> [FilePath]+journalFilePaths = map jfpath . jfiles++-- | All the files this journal's data was read from: its data files+-- (journalFilePaths) and any auxiliary files such as CSV rules files (jauxfiles).+-- These are the files to watch for changes when reloading.+-- Each file is listed once, even if it was read more than once+-- (eg a file included twice, or a rules file used by several CSV files).+journalAllFilePaths :: Journal -> [FilePath]+journalAllFilePaths j = nubOrd $ journalFilePaths j <> concatMap snd (jauxfiles j)++mainfile :: Journal -> JournalFile+mainfile = headDef (JournalFile "(unknown)" "" 0) . jfiles++addTransaction :: Transaction -> Journal -> Journal+addTransaction t j@Journal{jtxns=ts} = let ts' = t : ts in ts' `seq` j { jtxns = ts' }++-- | Add a journal item, evaluated first (its fields are strict) so no parse-time thunks are retained.+-- Consecutive blank line items are collapsed into one.+addJournalItem :: JournalItem -> Journal -> Journal+addJournalItem JIBlank j@Journal{jitems=JIBlank:_} = j+addJournalItem i j@Journal{jitems=is} = let is' = i : is in i `seq` is' `seq` j { jitems = is' }++-- | Add a transaction parsed from a journal file, and a placeholder item for it.+-- Any comment lines immediately preceding it (the JIComment items on top of jitems)+-- are moved into the transaction's tprecedingcomment.+addTransactionItem :: Transaction -> Journal -> Journal+addTransactionItem t j@Journal{jitems=is} =+ -- strict pattern matching here, to avoid leaving thunks in jitems+ case span isCommentItem is of+ ([], _) -> addTransactionAndItem t j+ (cs, rest) -> rest `seq` addTransactionAndItem t' j{jitems=rest}+ where t' = txnTieKnot t{tprecedingcomment = T.concat $ reverse [c | JIComment c <- cs]}+ where+ addTransactionAndItem t' = addJournalItem (JITransaction $ fst $ tsourcepos t') . addTransaction t'+ isCommentItem JIComment{} = True+ isCommentItem _ = False++addTransactionModifier :: TransactionModifier -> Journal -> Journal+addTransactionModifier mt j = j { jtxnmodifiers = mt : jtxnmodifiers j }++addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal+addPeriodicTransaction pt j = j { jperiodictxns = pt : jperiodictxns j }++deriving instance Show AssertDirective++addAssertDirective :: AssertDirective -> Journal -> Journal+addAssertDirective ad j = j { jasserts = ad : jasserts j }++addPriceDirective :: PriceDirective -> Journal -> Journal+addPriceDirective h j@Journal{jpricedirectives=hs} = let hs' = h : hs in hs' `seq` j { jpricedirectives = hs' } -- XXX #999 keep sorted++-- | Get the transaction with this index (its 1-based position in the input stream), if any.+journalTransactionAt :: Journal -> Integer -> Maybe Transaction+journalTransactionAt Journal{jtxns=ts} i =+ -- it's probably ts !! (i+1), but we won't assume+ headMay [t | t <- ts, tindex t == i]++-- | Get the transaction that appeared immediately after this one in the input stream, if any.+journalNextTransaction :: Journal -> Transaction -> Maybe Transaction+journalNextTransaction j t = journalTransactionAt j (tindex t + 1)++-- | Get the transaction that appeared immediately before this one in the input stream, if any.+journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction+journalPrevTransaction j t = journalTransactionAt j (tindex t - 1)++-- | All postings from this journal's transactions, in order.+journalPostings :: Journal -> [Posting]+journalPostings = concatMap tpostings . jtxns++-- | All posting amounts from this journal, in order.+journalPostingAmounts :: Journal -> [MixedAmount]+journalPostingAmounts = map pamount . journalPostings++-- | Show the journal posting amounts rendered, suitable for debug logging.+showJournalPostingAmountsDebug :: Journal -> String+showJournalPostingAmountsDebug = show . map showMixedAmountOneLine . journalPostingAmounts++-- | All raw amounts used in this journal's postings and costs,+-- with MixedAmounts flattened, in parse order.+journalPostingAndCostAmounts :: Journal -> [Amount]+journalPostingAndCostAmounts = concatMap getAmounts . concatMap (amountsRaw . pamount) . journalPostings++-- | All raw amounts appearing in this journal, with MixedAmounts flattened, in no particular order.+-- (Including from posting amounts, cost amounts, P directives, and the last D directive.)+journalAmounts :: Journal -> S.Set Amount+journalAmounts = S.fromList . journalStyleInfluencingAmounts True++-- | Sorted unique commodity symbols declared by commodity directives in this journal.+journalCommoditiesDeclared :: Journal -> [CommoditySymbol]+journalCommoditiesDeclared = M.keys . jdeclaredcommodities++-- | Sorted unique commodity symbols used anywhere in this journal, including+-- commodity directives, P directives, the last D directive, posting amounts and cost amounts.+journalCommoditiesUsed :: Journal -> [CommoditySymbol]+journalCommoditiesUsed j = S.elems $+ journalCommoditiesFromPriceDirectives j <>+ (S.fromList $ map acommodity $ journalStyleInfluencingAmounts True j)++-- | Sorted unique commodity symbols mentioned anywhere in this journal.+-- (Including commodity directives, P directives, the last D directive, posting amounts and cost amounts.)+journalCommodities :: Journal -> S.Set CommoditySymbol+journalCommodities j =+ M.keysSet (jdeclaredcommodities j)+ <> journalCommoditiesFromPriceDirectives j+ <> S.fromList (map acommodity $ journalStyleInfluencingAmounts True j)++-- | Sorted unique commodity symbols mentioned in this journal's P directives.+journalCommoditiesFromPriceDirectives :: Journal -> S.Set CommoditySymbol+journalCommoditiesFromPriceDirectives = S.fromList . concatMap pdcomms . jpricedirectives+ where pdcomms pd = [pdcommodity pd, acommodity $ pdamount pd]++-- | Sorted unique commodity symbols used in transactions, in either posting or cost amounts.+journalCommoditiesFromTransactions :: Journal -> S.Set CommoditySymbol+journalCommoditiesFromTransactions j = S.fromList $ map acommodity $ journalPostingAndCostAmounts j++-- | Guess a base currency for this journal: Just the commodity symbol+-- as used in the journal, and its ISO 4217 currency code if one is known+-- (otherwise the symbol again), choosing as follows:+-- 1. The "to" commodity that appears most often in P (price) directives, if any.+-- 2. Otherwise, the commodity that appears most often in posting and cost amounts.+-- 3. Otherwise, Nothing.+-- Commodity symbols are normalised to ISO 4217 codes where possible,+-- so that equivalent symbols are tallied together; the symbol returned+-- is the first-occurring one that normalises to the winning code.+-- Ties are broken by first occurrence order.+journalBaseCurrency :: Journal -> Maybe (CommoditySymbol, CurrencyCode)+journalBaseCurrency j = pick priceTargetComms <|> pick postingAndCostComms+ where+ pick syms = do+ code <- mostFrequent $ map toCurrencyCode syms+ sym <- find ((== code) . toCurrencyCode) syms+ Just (sym, code)+ priceTargetComms = map (acommodity . pdamount) $ jpricedirectives j+ postingAndCostComms = map acommodity $ journalPostingAndCostAmounts j++ -- Most frequent element, ties broken by first-occurrence order.+ -- A single pass for efficiency: each map entry stores (negate count, first index),+ -- so a minimumBy on those tuples picks most-frequent, earliest-first.+ -- The bang on c forces accumulation strictly to avoid thunk chains.+ mostFrequent :: Ord a => [a] -> Maybe a+ mostFrequent [] = Nothing+ mostFrequent xs = Just $ fst $ minimumBy (comparing snd) $ M.toList stats+ where+ stats = foldl' bump M.empty (zip [0::Int ..] xs)+ bump m (i, x) = M.insertWith combine x (-1, i) m+ combine _ (!c, i) = (c - 1, i)++-- | The ISO 4217 currency code of this journal's guessed base currency+-- ('journalBaseCurrency'), defaulting to "USD".+journalBaseCurrencyCode :: Journal -> CurrencyCode+journalBaseCurrencyCode = maybe "USD" snd . journalBaseCurrency++-- | Unique transaction descriptions used in this journal.+journalDescriptions :: Journal -> [Text]+journalDescriptions = nubSort . map tdescription . jtxns++-- | Sorted unique payees declared by payee directives in this journal.+journalPayeesDeclared :: Journal -> [Payee]+journalPayeesDeclared = nubSort . map fst . jdeclaredpayees++-- | Sorted unique payees used by transactions in this journal.+journalPayeesUsed :: Journal -> [Payee]+journalPayeesUsed = nubSort . map transactionPayee . jtxns++-- | Sorted unique payees used in transactions or declared by payee directives in this journal.+journalPayeesDeclaredOrUsed :: Journal -> [Payee]+journalPayeesDeclaredOrUsed j = toList $ foldMap S.fromList+ [journalPayeesDeclared j, journalPayeesUsed j]++-- | Sorted unique tag names declared by tag directives in this journal.+journalTagsDeclared :: Journal -> [TagName]+journalTagsDeclared = nubSort . map fst . jdeclaredtags++-- | Sorted unique tag names used in this journal (in account directives, transactions, postings..)+journalTagsUsed :: Journal -> [TagName]+journalTagsUsed j = nubSort $ map fst $ concatMap transactionAllTags $ jtxns j+ -- tags used in all transactions and postings and postings' accounts++-- | Sorted unique tag names used in transactions or declared by tag directives in this journal.+journalTagsDeclaredOrUsed :: Journal -> [TagName]+journalTagsDeclaredOrUsed j = toList $ foldMap S.fromList+ [journalTagsDeclared j, journalTagsUsed j]++-- | Sorted unique account names posted to by this journal's transactions.+journalAccountNamesUsed :: Journal -> [AccountName]+journalAccountNamesUsed = accountNamesFromPostings . journalPostings++-- | Sorted unique account names implied by this journal's transactions -+-- accounts posted to and all their implied parent accounts.+journalAccountNamesImplied :: Journal -> [AccountName]+journalAccountNamesImplied = expandAccountNames . journalAccountNamesUsed++-- | Sorted unique account names declared by account directives in this journal.+journalAccountNamesDeclared :: Journal -> [AccountName]+journalAccountNamesDeclared = nubSort . map fst . jdeclaredaccounts++-- | Sorted unique account names declared by account directives or posted to+-- by transactions in this journal.+journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]+journalAccountNamesDeclaredOrUsed j = toList $ foldMap S.fromList+ [journalAccountNamesDeclared j, journalAccountNamesUsed j]++-- | Sorted unique account names declared by account directives, or posted to+-- or implied as parents by transactions in this journal.+journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]+journalAccountNamesDeclaredOrImplied j = toList $ foldMap S.fromList+ [journalAccountNamesDeclared j, expandAccountNames $ journalAccountNamesUsed j]++-- | Convenience/compatibility alias for journalAccountNamesDeclaredOrImplied.+journalAccountNames :: Journal -> [AccountName]+journalAccountNames = journalAccountNamesDeclaredOrImplied++-- | Sorted unique account names declared or implied in this journal+-- which have no children.+journalLeafAccountNames :: Journal -> [AccountName]+journalLeafAccountNames = treeLeaves . journalAccountNameTree++journalAccountNameTree :: Journal -> Tree AccountName+journalAccountNameTree = accountNameTreeFrom . journalAccountNamesDeclaredOrImplied++-- | Which tags have been declared explicitly for this account, if any ?+journalAccountTags :: Journal -> AccountName -> [Tag]+journalAccountTags Journal{jdeclaredaccounttags} a = M.findWithDefault [] a jdeclaredaccounttags++-- | Which tags are in effect for this account, including tags inherited from parent accounts ?+journalInheritedAccountTags :: Journal -> AccountName -> [Tag]+journalInheritedAccountTags j a =+ foldl' (\ts a' -> ts `union` journalAccountTags j a') [] as+ where+ as = a : parentAccountNames a+-- PERF: cache in journal ?++type DateWeightedSimilarityScore = Double+type SimilarityScore = Double+type TimeDistance = Integer++-- | Find up to N most similar and nearest-dated transactions matching+-- the given transaction description and query and exceeding the given+-- description similarity score (0 to 1, see compareDescriptions).+-- The provided Day (today) is used as the reference date;+-- transactions are penalised by their absolute distance from it in days+-- (both past and future).+-- Returns transactions along with+-- their distance in days from today,+-- their description similarity score,+-- and a heuristically date-weighted variant of this that favours nearby transactions.+journalTransactionsSimilarTo :: Journal -> Day -> Text -> Query -> SimilarityScore -> Int+ -> [(DateWeightedSimilarityScore, TimeDistance, SimilarityScore, Transaction)]+journalTransactionsSimilarTo Journal{jtxns} today desc q similaritythreshold n =+ take n $+ dbg1With (+ unlines .+ ("up to 30 transactions above description similarity threshold "<>show similaritythreshold<>" ordered by proximity-weighted similarity:":) .+ take 30 .+ map ( \(w,d,s,Transaction{..}) -> printf "weighted:%8.3f distance:%4d similarity:%5.3f %s %s" w d s (show tdate) tdescription )) $+ sortBy (comparing (negate.first4)) $+ map (\(s,t) -> (weightedScore (s,t), timedistance t, s, t)) $+ filter ((> similaritythreshold).fst)+ [(compareDescriptions desc $ tdescription t, t) | t <- jtxns, q `matchesTransaction` t]+ where+ timedistance t = abs $ diffDays today (tdate t)+ -- Combine similarity and time distance heuristically. This gave decent results+ -- in my "find most recent invoice" use case in 2023-03,+ -- but will probably need more attention.+ weightedScore :: (Double, Transaction) -> Double+ weightedScore (s, t) = 100 * s - fromIntegral (timedistance t) / 4++-- | Return a similarity score from 0 to 1.5 for two transaction descriptions. +-- This is based on compareStrings, with the following modifications:+--+-- - numbers are stripped out before measuring similarity+--+-- - if the (unstripped) first description appears in its entirety within the second,+-- the score is boosted by 0.5.+--+compareDescriptions :: Text -> Text -> Double+compareDescriptions a b =+ (if a `T.isInfixOf` b then (0.5+) else id) $+ compareStrings (simplify a) (simplify b)+ where+ simplify = T.unpack . T.filter (not.isDigit)++-- | Return a similarity score from 0 to 1 for two strings. This+-- was based on Simon White's string similarity algorithm+-- (http://www.catalysoft.com/articles/StrikeAMatch.html), later found+-- to be https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient,+-- and modified to handle short strings better.+-- Todo: check out http://nlp.fi.muni.cz/raslan/2008/raslan08.pdf#page=14 .+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 * commonpairs / totalpairs+ where+ pairs1 = S.fromList $ wordLetterPairs $ uppercase s1+ pairs2 = S.fromList $ wordLetterPairs $ uppercase s2+ commonpairs = fromIntegral $ S.size $ S.intersection pairs1 pairs2+ totalpairs = fromIntegral $ S.size pairs1 + S.size pairs2++wordLetterPairs :: String -> [String]+wordLetterPairs = concatMap letterPairs . words++letterPairs :: String -> [String]+letterPairs (a:b:rest) = [a,b] : letterPairs (b:rest)+letterPairs _ = []++-- Newer account type code.++journalAccountType :: Journal -> AccountName -> Maybe AccountType+journalAccountType Journal{jaccounttypes} = accountNameType jaccounttypes++-- | Add a map of all known account types to the journal.+journalAddAccountTypes :: Journal -> Journal+journalAddAccountTypes j = j{jaccounttypes = journalAccountTypes j}++-- | An account type inherited from the parent account(s),+-- and whether it was originally declared by an account directive (true) or inferred from an account name (false).+type ParentAccountType = (AccountType, Bool)++-- | Build a map of all known account types, explicitly declared+-- or inferred from the account's parent or name.+journalAccountTypes :: Journal -> M.Map AccountName AccountType+journalAccountTypes j = M.fromList [(a,acctType) | (a, Just (acctType,_)) <- flatten t']+ where+ t = accountNameTreeFrom $ journalAccountNames j :: Tree AccountName+ -- Traverse downward through the account tree, applying any explicitly declared account types,+ -- otherwise inferring account types from account names when possible, and propagating account types downward.+ -- Declared account types (possibly inherited from parent) are preferred, inferred types are used as a fallback.+ t' = setTypeHereAndBelow Nothing t :: Tree (AccountName, Maybe (AccountType, Bool))+ where+ declaredtypes = M.keys $ jdeclaredaccounttypes j+ declaredtypesbyname = journalDeclaredAccountTypes j & fmap (,True)+ setTypeHereAndBelow :: Maybe ParentAccountType -> Tree AccountName -> Tree (AccountName, Maybe ParentAccountType)+ setTypeHereAndBelow mparenttype (Node a subs) = Node (a, mnewtype) (map (setTypeHereAndBelow mnewtype) subs)+ where+ mnewtype = mthisacctdeclaredtype <|> mparentacctdeclaredtype <|> mthisacctinferredtype <|> mparentacctinferredtype+ where+ mthisacctdeclaredtype = M.lookup a declaredtypesbyname+ mparentacctdeclaredtype = if fromMaybe False $ snd <$> mparenttype then mparenttype else Nothing+ mparentacctinferredtype = if not $ fromMaybe True $ snd <$> mparenttype then mparenttype else Nothing+ mthisacctinferredtype = accountNameInferTypeExcept declaredtypes a & fmap (,False) -- XXX not sure about this Except logic.. but for now, tests pass++-- | Build a map from account names to explicitly declared account types.+journalDeclaredAccountTypes :: Journal -> M.Map AccountName AccountType+journalDeclaredAccountTypes Journal{jdeclaredaccounttypes} =+ M.fromList $ concat [map (,t) as | (t,as) <- M.toList jdeclaredaccounttypes]++-- | To all postings in the journal, add any tags from their account+-- (including those inherited from parent accounts).+-- Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output).+-- If a tag already exists on the posting, it is not changed (the account tag will be ignored).+journalPostingsAddAccountTags :: Journal -> Journal+journalPostingsAddAccountTags j+ | M.null (jdeclaredaccounttags j) = j -- no account tags declared, nothing to add+ | M.null inheritedtagsbyaccount = j -- no posted-to account has any, nothing to add+ | otherwise = journalMapPostings addtags j+ where+ -- postings whose account has no tags are left as they are (no new posting is built)+ addtags p = maybe p (postingAddTags p) $ M.lookup (paccount p) inheritedtagsbyaccount+ -- the inherited tags of each posted-to account which has some, calculated once per account+ inheritedtagsbyaccount = M.fromList+ [(a, ts) | a <- journalAccountNamesUsed j, let ts = journalInheritedAccountTags j a, not $ null ts]++-- | Remove all tags from the journal's postings except those provided by their account.+-- This is useful for the accounts report.+-- It does not remove tag declarations from the posting comments.+journalPostingsKeepAccountTagsOnly :: Journal -> Journal+journalPostingsKeepAccountTagsOnly j = journalMapPostings keepaccounttags j+ where keepaccounttags p = p{ptags=[]} `postingAddTags` (journalInheritedAccountTags j $ paccount p)++-- | Get any tags declared for this commodity.+journalCommodityTags :: Journal -> CommoditySymbol -> [Tag]+journalCommodityTags Journal{jdeclaredcommoditytags} c =+ M.findWithDefault [] c jdeclaredcommoditytags++-- | Does this commodity have a 'lots:' tag declared ?+journalCommodityUsesLots :: Journal -> CommoditySymbol -> Bool+journalCommodityUsesLots j c = any ((== "lots") . T.toLower . fst) (journalCommodityTags j c)++-- | All commodities with a 'lots:' tag declared.+journalLotfulCommodities :: Journal -> S.Set CommoditySymbol+journalLotfulCommodities j@Journal{jdeclaredcommoditytags} =+ S.filter (journalCommodityUsesLots j) (M.keysSet jdeclaredcommoditytags)++-- | The declared lots: tag values by account (the first value, if an+-- account somehow has several).+journalAccountLotsTags :: Journal -> M.Map AccountName Text+journalAccountLotsTags Journal{jdeclaredaccounttags} =+ M.mapMaybe (\tags -> listToMaybe [v | (k, v) <- tags, T.toLower k == "lots"]) jdeclaredaccounttags++-- | Does this account opt out of lot tracking, via a NONE-valued lots: tag+-- on its own or an ancestor's declaration ? The nearest declaration wins,+-- so a subaccount can re-enable tracking with its own lots: method tag.+-- Postings with explicit cost basis annotations are still lot-tracked+-- regardless (the more specific declaration wins).+journalAccountUsesNoLots :: Journal -> AccountName -> Bool+journalAccountUsesNoLots = accountUsesNoLotsWith . journalAccountLotsTags++-- | Like journalAccountUsesNoLots, but taking the 'journalAccountLotsTags'+-- map (useful where no Journal is at hand, eg during balancing).+accountUsesNoLotsWith :: M.Map AccountName Text -> AccountName -> Bool+accountUsesNoLotsWith lotstags a =+ case [v | a' <- a : parentAccountNames a, Just v <- [M.lookup a' lotstags]] of+ (v:_) -> isNoneLotsTagValue v+ [] -> False++-- | Is this lots: tag value the special NONE value (case insensitive),+-- valid on account declarations to opt out of lot tracking ?+isNoneLotsTagValue :: Text -> Bool+isNoneLotsTagValue v = T.toUpper (T.strip v) == "NONE"++-- | Get the reduction method from a commodity's lots: tag value, if any.+journalCommodityLotsMethod :: Journal -> CommoditySymbol -> Maybe ReductionMethod+journalCommodityLotsMethod j c =+ case [v | (k, v) <- journalCommodityTags j c, T.toLower k == "lots"] of+ (v:_) -> parseReductionMethod v+ [] -> Nothing++-- | Get the reduction method from a posting's lots: tag value (typically inherited from its account), if any.+postingLotsMethod :: Posting -> Maybe ReductionMethod+postingLotsMethod p =+ case [v | (k, v) <- ptags p, T.toLower k == "lots"] of+ (v:_) -> parseReductionMethod v+ [] -> Nothing++-- | Parse a reduction method name from a lots: tag value.+parseReductionMethod :: Text -> Maybe ReductionMethod+parseReductionMethod t = case T.toUpper (T.strip t) of+ "FIFO" -> Just FIFO+ "LIFO" -> Just LIFO+ "HIFO" -> Just HIFO+ "AVERAGE" -> Just AVERAGE+ "SPECID" -> Just SPECID+ "FIFOALL" -> Just FIFOALL+ "LIFOALL" -> Just LIFOALL+ "HIFOALL" -> Just HIFOALL+ "AVERAGEALL" -> Just AVERAGEALL+ _ -> Nothing++-- | Check that all lots: tag values on commodity and account declarations are recognised.+-- On a commodity declaration, an empty value (bare @lots:@ tag) is valid,+-- declaring the commodity lotful with the default FIFO reduction method;+-- a non-empty value must be one of the known reduction methods.+-- On an account declaration, the tag only sets the reduction method for+-- lotful commodities in that account, so a method value is required.+journalCheckLotsTagValues :: Journal -> Either String Journal+journalCheckLotsTagValues j = do+ mapM_ checkCommodity (M.toList $ jdeclaredcommoditytags j)+ mapM_ checkAccount (jdeclaredaccounts j)+ Right j+ where+ methods = "FIFO, LIFO, HIFO, AVERAGE, SPECID, FIFOALL, LIFOALL, HIFOALL, AVERAGEALL"++ unrecognisedmsg :: String+ unrecognisedmsg = unlines [+ "%s:%d:"+ ,"%s"+ ,"unrecognised lots: tag value %s."+ ,"Use " ++ methods ++ ", or nothing (meaning FIFO)"+ ]++ valuelessmsg :: String+ valuelessmsg = unlines [+ "%s:%d:"+ ,"%s"+ ,"An account lots: tag sets the disposal order for lot-tracked commodities there,"+ ,"so it needs a value, one of " ++ methods ++ ";"+ ,"or NONE, to disable lot tracking in this account."+ ,"(A commodity lots: tag enables lot tracking, and can also set the disposal order.)"+ ]++ nonecommoditymsg :: String+ nonecommoditymsg = unlines [+ "%s:%d:"+ ,"%s"+ ,"lots: NONE is not supported on commodity declarations."+ ,"To disable lot tracking of this commodity in particular accounts,"+ ,"add a lots: NONE tag to those accounts' declarations instead;"+ ,"to disable it everywhere, remove the commodity's lots: tag."+ ]++ checkCommodity (sym, tags) =+ case M.lookup sym (jdeclaredcommodities j) of+ Just comm -> mapM_ (checkCommodityTag comm) tags+ Nothing -> Right ()++ checkCommodityTag comm (k, v)+ | T.toLower k /= "lots" = Right ()+ | T.null (T.strip v) = Right ()+ | isNoneLotsTagValue v = Left $ printf nonecommoditymsg f l ex+ | Just _ <- parseReductionMethod v = Right ()+ | otherwise = Left $ printf unrecognisedmsg f l ex (show v)+ where (f, l, _mcols, ex) = makeCommodityTagErrorExcerpt comm k++ checkAccount (acctName, adi) =+ mapM_ (checkAccountTag acctName adi) (aditags adi)++ checkAccountTag acctName adi (k, v)+ | T.toLower k /= "lots" = Right ()+ | T.null (T.strip v) = Left $ printf valuelessmsg f l ex+ | isNoneLotsTagValue v = Right ()+ | Just _ <- parseReductionMethod v = Right ()+ | otherwise = Left $ printf unrecognisedmsg f l ex (show v)+ where (f, l, _mcols, ex) = makeAccountTagErrorExcerpt (acctName, adi) k++-- | To all postings in the journal, add any tags from their amount's commodities.+-- Tags are added to ptags (making them queryable) but not to pcomment (so they don't appear in print output).+-- If a tag already exists on the posting, it is not changed (the commodity tag will be ignored).+journalPostingsAddCommodityTags :: Journal -> Journal+journalPostingsAddCommodityTags j+ | M.null taggedcommodities = j -- no commodity tags declared, nothing to add+ | otherwise = journalMapPostings addtags j+ where+ taggedcommodities = M.filter (not . null) $ jdeclaredcommoditytags j+ -- postings whose commodities have no tags are left as they are (no new posting is built)+ addtags p = case concatMap (\c -> M.findWithDefault [] c taggedcommodities) (postingCommodities p) of+ [] -> p+ tags -> p `postingAddTags` tags++-- | For lot-opening postings with a cost basis (positive; or negative in a+-- liability account, which holds short lots), which don't look like lot+-- transfer destinations, infer transacted cost from cost basis. This runs+-- before transaction balancing (the inferred cost lets an acquire entry with+-- an elided cash amount balance at cost), so lot classification hasn't+-- happened yet; transfer destinations - which must not get a transacted+-- cost - are recognised by shape: a positive cost-basis posting is skipped+-- when the transaction has an explicit negative amount of the same commodity+-- and quantity in another account, or unpriced in the same account (a+-- transfer-from counterpart), or the+-- commodity's unpriced negative and positive quantities sum to matching+-- totals (a split or consolidating transfer group, possibly minus a fee),+-- or an equity posting with no cost-basis amounts (an equity transfer, eg+-- close --clopen --lots style opening balances).+journalInferPostingsTransactedCost :: Journal -> Journal+journalInferPostingsTransactedCost j = journalMapTransactions inferTxn j+ where+ inferTxn t = t{tpostings = map (postingInferTransactedCost t) (tpostings t)}++ postingInferTransactedCost t p+ | not (any needsInference $ amounts $ pamount p) = p -- nothing to infer+ | hasEquityCounterpart t = p -- equity transfer: not for transfer postings+ | otherwise = p'{poriginal = Just $ originalPosting p}+ where+ p' = p{pamount = mapMixedAmount amountInferTransactedCost $ pamount p}+ -- a lot inflow: positive, or negative in a liability account (a short lot)+ -- (the cheap checks first; few amounts have a cost basis, and multiplying Decimals is slow)+ needsInference a = hasCostBasisCost a && isNothing (acost a) && aquantity a * lotsign > 0+ && not (hasTransferFromCounterpart t p a)+ && not (hasTransferGroupShape t p (acommodity a))+ lotsign = maybe 1 lotDirectionSign (journalAccountType j (paccount p) >>= accountTypeLotDirection)+ amountInferTransactedCost a+ | needsInference a, Just CostBasis{cbCost=Just c} <- acostbasis a = a{acost = Just (UnitCost c)}+ | otherwise = a+ hasCostBasisCost a = case acostbasis a of+ Just CostBasis{cbCost=Just _} -> True+ _ -> False++ -- Does another posting have an explicit negative amount of this commodity+ -- and quantity, in a different account, or unpriced in the same account ?+ -- Then this looks like a transfer pair (mirroring the lot classifier's+ -- counterpart matching and same-account pairing).+ hasTransferFromCounterpart t p a =+ any (\q -> any (\qa -> acommodity qa == acommodity a && aquantity qa == negate (aquantity a)+ && (paccount q /= paccount p || isNothing (acost qa)))+ (amountsRaw (pamount q)))+ (tpostings t)++ -- Do the transaction's unpriced amounts in this commodity look like a+ -- split or consolidating transfer group (#2692) ? True when the total+ -- unpriced negative quantity equals the total unpriced positive quantity,+ -- is nonzero, and at least one negative is in a different account.+ -- Priced amounts are excluded on both sides: a priced posting (eg a fee+ -- disposal -0.02 A {$100} @ $100) is a deliberate trade, not part of the+ -- transfer.+ hasTransferGroupShape t p c =+ negTotal > 0 && negTotal == posTotal && any (/= paccount p) negAccts+ where+ unpricedAmts q = [a | a <- amountsRaw (pamount q), acommodity a == c, isNothing (acost a)]+ negs = [(paccount q, negate (aquantity a)) | q <- tpostings t, a <- unpricedAmts q, aquantity a < 0]+ posTotal = sum [aquantity a | q <- tpostings t, a <- unpricedAmts q, aquantity a > 0]+ negTotal = sum (map snd negs)+ negAccts = map fst negs++ -- Does the transaction have an equity posting with no cost-basis amounts ?+ -- (Mirrors the lot classifier's equity-transfer detection.)+ hasEquityCounterpart t =+ any (\q -> maybe False isEquityType (journalAccountType j (paccount q))+ && not (any (isJust . acostbasis) (amountsRaw (pamount q))))+ (tpostings t)++-- | The account name to use for postings which hledger generates to an account of the given type:+-- the first account declared with that type (by a type: tag), in declaration order;+-- or if there is none, the alphabetically first account which has that type+-- (inferred from its name, or a parent's);+-- or if there is none, the given default account name.+journalAccountForType :: AccountName -> AccountType -> Journal -> AccountName+journalAccountForType defaultacct atype j = headDef defaultacct $ declared ++ inferred+ where+ declaredtypes = journalDeclaredAccountTypes j+ declared = [a | (a,_) <- jdeclaredaccounts j, M.lookup a declaredtypes == Just atype]+ inferred = M.keys $ M.filter (==atype) $ jaccounttypes j++-- | The account name to use for conversion postings generated by --infer-equity+-- (see journalAccountForType; the default is equity:conversion).+journalBaseConversionAccount :: Journal -> AccountName+journalBaseConversionAccount = journalAccountForType defaultBaseConversionAccount Conversion++-- | All the accounts in this journal which are declared or inferred as V/Conversion type.+-- This does not include new account names which might be generated by --infer-equity, currently.+journalConversionAccounts :: Journal -> [AccountName]+journalConversionAccounts = M.keys . M.filter (==Conversion) . jaccounttypes++-- | The account name to use for inferred gain postings+-- (see journalAccountForType; the default is revenues:gain).+journalBaseGainAccount :: Journal -> AccountName+journalBaseGainAccount = journalAccountForType defaultGainAccount Gain++-- | All the accounts in this journal which are declared or inferred as G/Gain type, alphabetically.+journalGainAccounts :: Journal -> [AccountName]+journalGainAccounts = M.keys . M.filter (==Gain) . jaccounttypes+++-- Various kinds of filtering on journals. We do it differently depending+-- on the command.++-------------------------------------------------------------------------------+-- filtering V2++-- | Keep only transactions matching the query expression.+filterJournalTransactions :: Query -> Journal -> Journal+filterJournalTransactions q j@Journal{jtxns}+ | queryIsNull q = j -- everything matches, nothing to do+ | otherwise = j{jtxns=filter (matchesTransactionExtra (journalAccountType j) q) jtxns}++-- | Keep only postings matching the query expression.+-- This can leave unbalanced transactions.+filterJournalPostings :: Query -> Journal -> Journal+filterJournalPostings q j@Journal{jtxns=ts}+ | queryIsNull q = j -- everything matches, nothing to do+ | otherwise = j{jtxns=map (filterTransactionPostingsExtra (journalAccountType j) q) ts}++-- | Keep only postings which do not match the query expression, but for which a related posting does.+-- This can leave unbalanced transactions.+filterJournalRelatedPostings :: Query -> Journal -> Journal+filterJournalRelatedPostings q j@Journal{jtxns=ts} = j{jtxns=map (filterTransactionRelatedPostings q) ts}++-- | Within each posting's amount, keep only the parts matching the query, and+-- remove any postings with all amounts removed.+-- This can leave unbalanced transactions.+filterJournalAmounts :: Query -> Journal -> Journal+filterJournalAmounts q j@Journal{jtxns=ts}+ | queryIsNull q = j -- everything matches, nothing to do+ | otherwise = j{jtxns=map (filterTransactionAmounts q) ts}++-- | Filter out all parts of this transaction's amounts which do not match the+-- query, and remove any postings with all amounts removed.+-- This can leave the transaction unbalanced.+filterTransactionAmounts :: Query -> Transaction -> Transaction+filterTransactionAmounts q t@Transaction{tpostings=ps} = t{tpostings=mapMaybe (filterPostingAmount q) ps}++-- | Filter out all parts of this posting's amount which do not match the query, and remove the posting+-- if this removes all amounts.+filterPostingAmount :: Query -> Posting -> Maybe Posting+filterPostingAmount q p@Posting{pamount=as}+ | null newamt = Nothing+ | otherwise = Just p{pamount=Mixed newamt}+ where+ Mixed newamt = filterMixedAmount (q `matchesAmount`) as++filterTransactionPostings :: Query -> Transaction -> Transaction+filterTransactionPostings q t@Transaction{tpostings=ps} = t{tpostings=filter (q `matchesPosting`) ps}++-- Like filterTransactionPostings, but is given the map of account types so can also filter by account type.+filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction+filterTransactionPostingsExtra atypes q t@Transaction{tpostings=ps} =+ t{tpostings=filter (matchesPostingExtra atypes q) ps}++filterTransactionRelatedPostings :: Query -> Transaction -> Transaction+filterTransactionRelatedPostings q t@Transaction{tpostings=ps} =+ t{tpostings=if null matches then [] else ps \\ matches}+ where matches = filter (matchesPosting q) ps++-- | Apply a transformation to a journal's transactions.+journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal+journalMapTransactions f j@Journal{jtxns=ts} = j{jtxns=map f ts}++-- | Apply a transformation to a journal's postings.+journalMapPostings :: (Posting -> Posting) -> Journal -> Journal+journalMapPostings f j@Journal{jtxns=ts} = j{jtxns=map (transactionMapPostings f) ts}++-- | Apply a transformation to a journal's posting amounts.+journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal+journalMapPostingAmounts f = journalMapPostings (postingTransformAmount f)++{-+-------------------------------------------------------------------------------+-- filtering V1++-- | Keep only transactions we are interested in, as described by the+-- filter specification.+filterJournalTransactions :: FilterSpec -> Journal -> Journal+filterJournalTransactions FilterSpec{datespan=datespan+ ,cleared=cleared+ -- ,real=real+ -- ,empty=empty+ ,acctpats=apats+ ,descpats=dpats+ ,depth=depth+ ,fMetadata=md+ } =+ filterJournalTransactionsByStatus cleared .+ filterJournalPostingsByDepth depth .+ filterJournalTransactionsByAccount apats .+ filterJournalTransactionsByMetadata md .+ filterJournalTransactionsByDescription dpats .+ filterJournalTransactionsByDate datespan++-- | Keep only postings we are interested in, as described by the filter+-- specification. This can leave unbalanced transactions.+filterJournalPostings :: FilterSpec -> Journal -> Journal+filterJournalPostings FilterSpec{datespan=datespan+ ,cleared=cleared+ ,real=real+ ,empty=empty+ ,acctpats=apats+ ,descpats=dpats+ ,depth=depth+ ,fMetadata=md+ } =+ filterJournalPostingsByRealness real .+ filterJournalPostingsByStatus cleared .+ filterJournalPostingsByEmpty empty .+ filterJournalPostingsByDepth depth .+ filterJournalPostingsByAccount apats .+ filterJournalTransactionsByMetadata md .+ filterJournalTransactionsByDescription dpats .+ filterJournalTransactionsByDate datespan++-- | Keep only transactions whose metadata matches all metadata specifications.+filterJournalTransactionsByMetadata :: [(String,String)] -> Journal -> Journal+filterJournalTransactionsByMetadata pats j@Journal{jtxns=ts} = j{jtxns=filter matchmd ts}+ where matchmd t = all (`elem` tmetadata t) pats++-- | Keep only transactions whose description matches the description patterns.+filterJournalTransactionsByDescription :: [String] -> Journal -> Journal+filterJournalTransactionsByDescription pats j@Journal{jtxns=ts} = j{jtxns=filter matchdesc ts}+ where matchdesc = matchpats pats . tdescription++-- | Keep only transactions which fall between begin and end dates.+-- We include transactions on the begin date and exclude transactions on the end+-- date, like ledger. An empty date string means no restriction.+filterJournalTransactionsByDate :: DateSpan -> Journal -> Journal+filterJournalTransactionsByDate (DateSpan begin end) j@Journal{jtxns=ts} = j{jtxns=filter match ts}+ where match t = maybe True (tdate t>=) begin && maybe True (tdate t<) end++-- | Keep only transactions which have the requested cleared/uncleared+-- status, if there is one.+filterJournalTransactionsByStatus :: Maybe Bool -> Journal -> Journal+filterJournalTransactionsByStatus Nothing j = j+filterJournalTransactionsByStatus (Just val) j@Journal{jtxns=ts} = j{jtxns=filter match ts}+ where match = (==val).tstatus++-- | Keep only postings which have the requested cleared/uncleared status,+-- if there is one.+filterJournalPostingsByStatus :: Maybe Bool -> Journal -> Journal+filterJournalPostingsByStatus Nothing j = j+filterJournalPostingsByStatus (Just c) j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}+ where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter ((==c) . postingCleared) ps}++-- | Strip out any virtual postings, if the flag is true, otherwise do+-- no filtering.+filterJournalPostingsByRealness :: Bool -> Journal -> Journal+filterJournalPostingsByRealness False j = j+filterJournalPostingsByRealness True j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}+ where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter isReal ps}++-- | Strip out any postings with zero amount, unless the flag is true.+filterJournalPostingsByEmpty :: Bool -> Journal -> Journal+filterJournalPostingsByEmpty True j = j+filterJournalPostingsByEmpty False j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}+ where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (not . isEmptyPosting) ps}++-- -- | Keep only transactions which affect accounts deeper than the specified depth.+-- filterJournalTransactionsByDepth :: Maybe Int -> Journal -> Journal+-- filterJournalTransactionsByDepth Nothing j = j+-- filterJournalTransactionsByDepth (Just d) j@Journal{jtxns=ts} =+-- j{jtxns=(filter (any ((<= d+1) . accountNameLevel . paccount) . tpostings) ts)}++-- | Strip out any postings to accounts deeper than the specified depth+-- (and any transactions which have no postings as a result).+filterJournalPostingsByDepth :: Maybe Int -> Journal -> Journal+filterJournalPostingsByDepth Nothing j = j+filterJournalPostingsByDepth (Just d) j@Journal{jtxns=ts} =+ j{jtxns=filter (not . null . tpostings) $ map filtertxns ts}+ where filtertxns t@Transaction{tpostings=ps} =+ t{tpostings=filter ((<= d) . accountNameLevel . paccount) ps}++-- | Keep only postings which affect accounts matched by the account patterns.+-- This can leave transactions unbalanced.+filterJournalPostingsByAccount :: [String] -> Journal -> Journal+filterJournalPostingsByAccount apats j@Journal{jtxns=ts} = j{jtxns=map filterpostings ts}+ where filterpostings t@Transaction{tpostings=ps} = t{tpostings=filter (matchpats apats . paccount) ps}++-- | Keep only transactions which affect accounts matched by the account patterns.+-- More precisely: each positive account pattern excludes transactions+-- which do not contain a posting to a matched account, and each negative+-- account pattern excludes transactions containing a posting to a matched+-- account.+filterJournalTransactionsByAccount :: [String] -> Journal -> Journal+filterJournalTransactionsByAccount apats j@Journal{jtxns=ts} = j{jtxns=filter tmatch ts}+ where+ tmatch t = (null positives || any positivepmatch ps) && (null negatives || not (any negativepmatch ps)) where ps = tpostings t+ positivepmatch p = any (`amatch` a) positives where a = paccount p+ negativepmatch p = any (`amatch` a) negatives where a = paccount p+ amatch pat a = regexMatchesCI (abspat pat) a+ (negatives,positives) = partition isnegativepat apats++-}++-- | Reverse all lists of parsed items, which during parsing were+-- prepended to, so that the items are in parse order. Part of+-- post-parse finalisation.+journalReverse :: Journal -> Journal+journalReverse j =+ j {jfiles = reverse $ jfiles j+ ,jdeclaredaccounts = reverse $ jdeclaredaccounts j+ ,jtxns = reverse $ jtxns j+ ,jitems = reverse $ jitems j+ ,jtxnmodifiers = reverse $ jtxnmodifiers j+ ,jperiodictxns = reverse $ jperiodictxns j+ ,jasserts = reverse $ jasserts j+ ,jpricedirectives = reverse $ jpricedirectives j+ }++-- | Set this journal's last read time, ie when its files were last read.+journalSetLastReadTime :: POSIXTime -> Journal -> Journal+journalSetLastReadTime t j = j{ jlastreadtime = t }+++-- | Number this journal's transactions, counting upward from 1, and tie their knots,+-- so that their postings refer to the renumbered transactions.+-- If they are already numbered that way, the journal is returned unchanged+-- (avoiding a new copy of every transaction).+journalNumberAndTieTransactions :: Journal -> Journal+journalNumberAndTieTransactions j@Journal{jtxns=ts}+ | and $ zipWith (\i t -> tindex t == i) [1..] ts = j+ | otherwise = journalTieTransactions $ journalNumberTransactions j++-- | Number (set the tindex field) this journal's transactions, counting upward from 1.+journalNumberTransactions :: Journal -> Journal+journalNumberTransactions j@Journal{jtxns=ts} = j{jtxns=zipWith (\i t -> t{tindex=i}) [1..] ts}++-- | Tie the knot in all of this journal's transactions, ensuring their postings+-- refer to them. This should be done last, after any other transaction-modifying operations.+journalTieTransactions :: Journal -> Journal+journalTieTransactions j@Journal{jtxns=ts} = j{jtxns=map txnTieKnot ts}++-- | Untie all transaction-posting knots in this journal, so that eg+-- recursiveSize and GHCI's :sprint can work on it.+journalUntieTransactions :: Transaction -> Transaction+journalUntieTransactions t@Transaction{tpostings=ps} = t{tpostings=map (\p -> p{ptransaction=Nothing}) ps}++-- | Apply any transaction modifier rules in the journal (adding automated+-- postings to transactions, eg). Or if a modifier rule fails to parse,+-- return the error message. A reference date is provided to help interpret+-- relative dates in transaction modifier queries.+-- The first argument selects whether to add visible tags to generated postings & modified transactions.+journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal+journalModifyTransactions verbosetags d j =+ case modifyTransactions+ (journalAccountType j)+ (journalInheritedAccountTags j)+ (journalCommodityStyles j)+ d verbosetags (jtxnmodifiers j) (jtxns j) of+ Right ts -> Right j{jtxns=ts}+ Left err -> Left err++-- | Apply this journal's commodity display styles to all of its posting amounts.+-- This does no display rounding, keeping decimal digits as they were;+-- it is suitable for an early cleanup pass before calculations.+-- Reports may want to do additional rounding/styling at render time.+-- Price directives' amounts are left as written (though they still influence the inferred styles),+-- so that error messages and `get`'s rewritten price files show them that way;+-- commands which list prices, like prices and print, style them when rendering.+-- This can return an error message eg if inconsistent number formats are found.+journalStyleAmounts :: Journal -> Either String Journal+journalStyleAmounts = fmap applystyles . journalInferCommodityStyles+ where+ applystyles j = journalMapPostings (postingShareStyles styles . styleAmounts styles) j+ where styles = journalCommodityStylesWith NoRounding j -- defer rounding, in case of print --round=none++-- | A memory optimisation, used after applying commodity styles to a posting's amounts.+-- An amount whose display precision differs from its commodity's usual precision+-- (eg $5 when the usual is $5.25) ends up with its own copy of the commodity's style,+-- which differs only in precision. This replaces such copies with one shared copy+-- for each commodity and precision, from a table of each commodity's style at every+-- possible precision (whose entries are created only when first needed).+-- On a 100k-transaction journal with mixed precisions this saves about 3% of memory;+-- it doesn't change the run time noticeably.+postingShareStyles :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting+postingShareStyles styles = postingTransformAmount $ \(Mixed m) -> Mixed $ M.map shareAmountStyle m -- commodities are unchanged, so the map keys are too+ where+ sharedstyles = M.map (\s -> A.listArray (0, 255) [s{asprecision=Precision p} | p <- [0..255]]) styles++ shareAmountStyle a = a{astyle = shareStyle (acommodity a) (astyle a), acost = shareCostStyle <$> acost a}++ shareCostStyle (UnitCost a) = UnitCost $ shareAmountStyle a+ shareCostStyle (TotalCost a) = TotalCost $ shareAmountStyle a++ -- If this style is the same as a shared one, use the shared one.+ shareStyle comm s = case (asprecision s, M.lookup comm sharedstyles) of+ (Precision p, Just stylesbyprecision) | stylesbyprecision A.! p == s -> stylesbyprecision A.! p+ _ -> s++-- | Get the canonical amount styles for this journal, whether (in order of precedence):+-- set globally in InputOpts,+-- declared by commodity directives, +-- declared by a default commodity (D) directive, +-- or inferred from posting amounts, +-- as a map from symbol to style. +-- Styles from directives are assumed to specify the decimal mark.+journalCommodityStyles :: Journal -> M.Map CommoditySymbol AmountStyle+journalCommodityStyles j =+ -- XXX could be some redundancy here, cf journalStyleInfluencingAmounts+ explicitstyles <> aliasstyles <> inferredstyles+ where+ explicitstyles = globalstyles <> declaredstyles <> defaultcommoditystyle+ globalstyles = jglobalcommoditystyles j+ declaredstyles = M.mapMaybe cformat $ jdeclaredcommodities j+ defaultcommoditystyle = M.fromList $ catMaybes [jparsedefaultcommodity j]+ inferredstyles = jinferredcommoditystyles j+ -- A commodity alias without a declared style of its own uses its commodity's number format+ -- (precision, decimal mark, digit groups), with the symbol placement of the amounts written+ -- with the alias, if any, otherwise of its commodity.+ aliasstyles = M.fromList+ [ (a, cst{ascommodityside = ascommodityside pst, ascommodityspaced = ascommodityspaced pst})+ | c <- M.elems (jdeclaredcommodities j)+ , Just cst <- [M.lookup (csymbol c) (explicitstyles <> inferredstyles)]+ , a <- commodityAliases c+ , let pst = M.findWithDefault cst a inferredstyles+ ]++-- | Like journalCommodityStyles, but attach a particular rounding strategy to the styles,+-- affecting how they will affect display precisions when applied.+journalCommodityStylesWith :: Rounding -> Journal -> M.Map CommoditySymbol AmountStyle+journalCommodityStylesWith r = amountStylesSetRounding r . journalCommodityStyles++-- | Collect and save inferred amount styles for each commodity based on+-- P directive amounts, posting amounts but not cost amounts, and maybe the last D amount, in that commodity.+-- Styles inferred previously for commodities which no longer appear in these are kept+-- (eg for commodity aliases, whose amounts have been converted, so that print can show them as written).+-- Can return an error message eg if inconsistent number formats are found.+journalInferCommodityStyles :: Journal -> Either String Journal+journalInferCommodityStyles j =+ Right j{jinferredcommoditystyles = dbg7 "journalInferCommodityStyles" $+ M.mapWithKey withExplicitPrecision allstyles `M.union` jinferredcommoditystyles j}+ where+ -- Styles are inferred from all amounts (for formatting like symbol placement,+ -- decimal mark, digit groups), but precision only from explicitly-written amounts:+ -- inferred balancing amounts must not raise the journal-wide display precision+ -- and surprise the user. Both style maps are accumulated in one traversal of the+ -- postings, with the directive amounts added last so that they take precedence.+ withExplicitPrecision sym s = maybe s (\s' -> s{asprecision = asprecision s'}) $ M.lookup sym explstyles+ allstyles = addAmountStyles directiveamts allpostingstyles+ explstyles = addAmountStyles directiveamts explpostingstyles+ (allpostingstyles, explpostingstyles) = foldr addPostingStyles (mempty, mempty) $ journalPostings j+ addPostingStyles p (!allsts, !explsts) =+ (addAmountStyles amts allsts, if isExplicitAmount p then addAmountStyles amts explsts else explsts)+ where amts = amountsRaw $ pamount p+ addAmountStyles amts styles = foldr addAmountStyle styles amts+ -- The default commodity (D) amount and price directive amounts. Costs are not included.+ directiveamts = catMaybes (mdefaultcommodityamt : map (Just . pdamount) (jpricedirectives j))+ mdefaultcommodityamt =+ (\(sym,style) -> nullamt{acommodity=sym, astyle=style}) <$> jparsedefaultcommodity j++-- -- | Apply this journal's historical price records to unpriced amounts where possible.+-- journalApplyPriceDirectives :: Journal -> Journal+-- journalApplyPriceDirectives j@Journal{jtxns=ts} = j{jtxns=map fixtransaction ts}+-- where+-- fixtransaction t@Transaction{tdate=d, tpostings=ps} = t{tpostings=map fixposting ps}+-- where+-- fixposting p@Posting{pamount=a} = p{pamount=fixmixedamount a}+-- fixmixedamount = mapMixedAmount fixamount+-- fixamount = fixprice+-- fixprice a@Amount{price=Just _} = a+-- fixprice a@Amount{commodity=c} = a{price=maybe Nothing (Just . UnitCost) $ journalPriceDirectiveFor j d c}++-- -- | Get the price for a commodity on the specified day from the price database, if known.+-- -- Does only one lookup step, ie will not look up the price of a price.+-- journalPriceDirectiveFor :: Journal -> Day -> CommoditySymbol -> Maybe MixedAmount+-- journalPriceDirectiveFor j d CommoditySymbol{symbol=s} = do+-- let ps = reverse $ filter ((<= d).pddate) $ filter ((s==).hsymbol) $ sortBy (comparing pddate) $ jpricedirectives j+-- case ps of (PriceDirective{pdamount=a}:_) -> Just a+-- _ -> Nothing++-- | Infer transaction-implied market prices from commodity-exchanging+-- transactions, if any. It's best to call this after transactions have+-- been balanced and posting amounts have appropriate prices attached.+journalInferMarketPricesFromTransactions :: Journal -> Journal+journalInferMarketPricesFromTransactions j =+ j{jinferredmarketprices =+ dbg4With (("jinferredmarketprices:\n"<>) . showMarketPrices) $+ map priceDirectiveToMarketPrice .+ concatMap postingPriceDirectivesFromCost $+ journalPostings j+ }++-- | Aliases declared on a commodity directive by its @alias:@ tags.+commodityAliases :: Commodity -> [CommoditySymbol]+commodityAliases = map (acommodity . fst) . caliases++-- | Update a commodity's declaration with a later declaration of it, in the same file tree.+-- The later declaration adds to the earlier one rather than replacing it:+-- aliases are combined, a display style replaces the earlier one only if the later declaration has one,+-- and the later tags come first (so they win, for tags looked up by their first value).+-- The comment and source position are the later declaration's.+commodityRedeclare :: Commodity -> Commodity -> Commodity+commodityRedeclare new old = new{+ cformat = cformat new <|> cformat old+ ,ctags = ctags new `union` ctags old+ ,caliases = caliases old `unionAliases` caliases new+ }++-- | Combine two declarations of a commodity from different journals (file trees, or a file and its included file),+-- the first being the later one. Like 'commodityRedeclare', this keeps the later one's comment, source position,+-- and display style if it has one, and the aliases (in reading order) and tags (the later one's first) of both.+commodityCombine :: Commodity -> Commodity -> Commodity+commodityCombine c1 c2 = c1{+ cformat = cformat c1 <|> cformat c2+ ,ctags = ctags c1 `union` ctags c2+ ,caliases = caliases c2 `unionAliases` caliases c1+ }++-- | Combine two lists of commodity aliases, the first being the earlier ones, keeping them in reading order+-- and dropping repeated definitions (same symbol and quantity).+-- An alias redefined with a different quantity is kept, so it can be reported as a conflict.+unionAliases :: [(Amount, SourcePos)] -> [(Amount, SourcePos)] -> [(Amount, SourcePos)]+unionAliases = unionBy ((==) `on` \(a, _) -> (acommodity a, aquantity a))++-- | All commodity symbols that this journal treats as declared:+-- both the canonical 'jdeclaredcommodities' keys and any 'alias:'+-- values declared on those commodity directives.+commoditiesAndAliases :: Journal -> S.Set CommoditySymbol+commoditiesAndAliases j =+ M.keysSet (jdeclaredcommodities j)+ <> S.fromList [ a+ | c <- M.elems (jdeclaredcommodities j)+ , a <- commodityAliases c+ ]++-- | Commodity aliases: each alias symbol, with its commodity, its quantity+-- (the number of alias units equal to one unit of the commodity),+-- and the commodity's display style if known.+type CommodityAliases = M.Map CommoditySymbol (CommoditySymbol, Quantity, Maybe AmountStyle)++-- | The commodity aliases declared in this journal.+journalCommodityAliases :: Journal -> CommodityAliases+journalCommodityAliases j =+ M.fromList [(acommodity a, (csymbol c, aquantity a, M.lookup (csymbol c) styles))+ | c <- M.elems $ jdeclaredcommodities j, (a, _) <- caliases c]+ where styles = journalCommodityStyles j++-- | Convert an amount written in one of these commodity aliases to its commodity,+-- also returning the alias quantity (or 1).+-- The converted amount gets the commodity's display style. For a plain alias, it keeps its display precision;+-- for an alias with a quantity, it gets the commodity's display precision+-- (or more, if needed to show an exactly converted amount fully; or if that's unknown, all its decimal places up to 8).+convertAliasAmount :: CommodityAliases -> Amount -> (Amount, Quantity)+convertAliasAmount aliases a = case M.lookup (acommodity a) aliases of+ Nothing -> (a, 1)+ Just (c, 1, ms) -> (a{acommodity = c, astyle = maybe (astyle a) (\s -> s{asprecision = asprecision $ astyle a}) ms}, 1)+ Just (c, q, ms) -> (a'{astyle = style{asprecision = Precision prec}}, q)+ where+ a' = a{acommodity = c, aquantity = aquantity a / q}+ digits = amountInternalPrecision a'+ exact = multiplyQuantities (aquantity a') q == aquantity a+ (style, prec) = case ms of+ Just s@AmountStyle{asprecision = Precision n} -> (s, if exact then max n digits else n)+ _ -> (fromMaybe (astyle a) ms, min defaultMaxDisplayPrecision digits)++-- | Convert all amounts written in a commodity alias to the commodity it is an alias of.+-- For an alias with a quantity (other than 1), amount quantities are divided by it,+-- and unit costs, cost bases and market prices of the alias are multiplied by it+-- (but if an amount or its unit cost converts inexactly, the unit cost is replaced by the exact total cost).+-- This is done for posting amounts, with their costs, cost bases and balance assertions;+-- periodic transaction and auto posting rules (whose multipliers' symbols are just renamed);+-- and price directives. A converted posting keeps its original form in poriginal, for print.+--+-- Returns 'Left' with a verbose error if the same alias is declared on more than one commodity,+-- or if an alias is also declared as a commodity with aliases of its own.+journalApplyCommodityAliases :: Journal -> Either String Journal+journalApplyCommodityAliases j+ | ((a, cs):_) <- conflicts = Left $ unlines $+ [ "Alias '" <> T.unpack a <> "' is declared on more than one commodity:", ""] <> map commodityExcerpt cs+ | (c:_) <- chained = Left $ unlines+ [ "Commodity '" <> T.unpack (csymbol c) <> "' has aliases, but is also an alias of another commodity:", ""+ , commodityExcerpt c ]+ | M.null aliases = Right j+ | otherwise = Right j+ { jtxns = map (transactionMapPostings convertPosting) $ jtxns j+ , jperiodictxns = [pt{ptpostings = map convertPosting $ ptpostings pt} | pt <- jperiodictxns j]+ , jtxnmodifiers = [tm{tmpostingrules = map convertRule $ tmpostingrules tm} | tm <- jtxnmodifiers j]+ , jpricedirectives = map convertPrice $ jpricedirectives j+ }+ where+ comms = M.elems $ jdeclaredcommodities j+ conflicts = [(a, cs) | (a, cs) <- M.toList $ M.fromListWith (++) [(a, [c]) | c <- comms, a <- commodityAliases c], length cs > 1]+ chained = [c | c <- comms, not (null $ caliases c), csymbol c `M.member` aliases]+ commodityExcerpt c = let (f, l, _, ex) = makeCommodityTagErrorExcerpt c "alias" in f <> ":" <> show l <> ":\n" <> T.unpack ex++ aliases = journalCommodityAliases j+ isAlias = (`M.member` aliases) . acommodity+ convertSymbol = convertAliasAmount aliases+ -- Show all of a calculated amount's decimal digits (up to 8), but no trailing zeros.+ withAllDigits a = amountSetPrecision (Precision $ min defaultMaxDisplayPrecision $ amountInternalPrecision a') a'+ where a' = a{aquantity = normalizeDecimal $ aquantity a}+ -- Multiply a per-unit price by an alias quantity.+ scaleBy 1 a = a+ scaleBy q a = withAllDigits a{aquantity = aquantity a * q}+ -- Convert a cost, price or balance assertion amount, showing all its digits if it was divided.+ convertExactAmount a = case convertSymbol a of+ (a', 1) -> a'+ (a', _) -> withAllDigits a'+ convertAmount a = a'{ acost = convertCost <$> acost a+ , acostbasis = (\cb -> cb{cbCost = scaleBy q . convertExactAmount <$> cbCost cb}) <$> acostbasis a+ }+ where+ (a', q) = convertSymbol a+ -- If the amount or its unit cost converts inexactly (eg 10 min = 0.1666.. h),+ -- use the total cost calculated before converting, so the cost stays exact.+ convertCost (UnitCost u)+ | isInexact a || isInexact u = TotalCost $ withAllDigits $ fst $ convertSymbol u{aquantity = multiplyQuantities (abs $ aquantity a) (aquantity u)}+ | otherwise = UnitCost $ scaleBy q $ convertExactAmount u+ convertCost (TotalCost t) = TotalCost $ convertExactAmount t+ -- Does converting this amount from an alias round its quantity ?+ isInexact a = case convertSymbol a of+ (_, 1) -> False+ (a', q) -> multiplyQuantities (aquantity a') q /= aquantity a+ hasAlias a = isAlias a || any (isAlias . costAmount) (acost a) || any isAlias (acostbasis a >>= cbCost)+ where costAmount (UnitCost u) = u+ costAmount (TotalCost t) = t++ convertPosting p+ | any hasAlias (amountsRaw $ pamount p) || any (isAlias . baamount) (pbalanceassertion p) =+ p{ pamount = mapMixedAmount convertAmount $ pamount p+ , pbalanceassertion = (\ba -> ba{baamount = convertExactAmount $ baamount ba}) <$> pbalanceassertion p+ , poriginal = Just $ originalPosting p+ }+ | otherwise = p+ convertRule r@TMPostingRule{tmprPosting = p, tmprIsMultiplier = ismult}+ | ismult = r{tmprPosting = p{pamount = mapMixedAmount (fst . convertSymbol) $ pamount p}}+ | otherwise = r{tmprPosting = convertPosting p}+ convertPrice pd@PriceDirective{pdcommodity = from, pdamount = a} =+ case M.lookup from aliases of+ Nothing -> pd{pdamount = convertExactAmount a}+ Just (c, q, _) -> pd{pdcommodity = c, pdamount = scaleBy q $ convertExactAmount a}++-- | Convert all this journal's amounts to cost using their attached prices, if any.+journalToCost :: ConversionOp -> Journal -> Journal+journalToCost cost j@Journal{jtxns=ts} = j{jtxns=map (transactionToCost cost) ts}++-- | Identify and tag (1) equity conversion postings and (2) postings which have (or could have ?) redundant costs.+-- And if the addcosts flag is true, also add any costs which can be inferred from equity conversion postings.+-- This is always called before transaction balancing to tag the redundant-cost postings so they can be ignored.+-- With --infer-costs, it is called again after transaction balancing (when it has more information to work with) to infer costs from equity postings.+-- See transactionTagCostsAndEquityAndMaybeInferCosts for more details, and hledger manual > Cost reporting for more background.+journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either String Journal+journalTagCostsAndEquityAndMaybeInferCosts verbosetags addcosts j+ | null conversionaccts = Right j -- no conversion accounts, so no conversion postings: nothing to do+ | otherwise = do+ ts <- mapM (transactionTagCostsAndEquityAndMaybeInferCosts verbosetags addcosts conversionaccts) $ jtxns j+ return j{jtxns=ts}+ where conversionaccts = journalConversionAccounts j++-- | Add equity postings inferred from costs, where needed and possible.+-- See hledger manual > Cost reporting.+journalInferEquityFromCosts :: Bool -> Journal -> Journal+journalInferEquityFromCosts verbosetags j =+ journalMapTransactions (transactionInferEquityPostings verbosetags equityAcct) j+ where equityAcct = journalBaseConversionAccount j++-- -- | Get this journal's unique, display-preference-canonicalised commodities, by symbol.+-- journalCanonicalCommodities :: Journal -> M.Map String CommoditySymbol+-- journalCanonicalCommodities j = canonicaliseCommodities $ journalAmountCommodities j++-- -- | Get all this journal's amounts' commodities, in the order parsed.+-- journalAmountCommodities :: Journal -> [CommoditySymbol]+-- journalAmountCommodities = map acommodity . concatMap amounts . journalAmounts++-- -- | Get all this journal's amount and price commodities, in the order parsed.+-- journalAmountAndPriceCommodities :: Journal -> [CommoditySymbol]+-- journalAmountAndPriceCommodities = concatMap amountCommodities . concatMap amounts . journalAmounts++-- -- | Get this amount's commodity and any commodities referenced in its price.+-- amountCommodities :: Amount -> [CommoditySymbol]+-- amountCommodities Amount{acommodity=c,acost=p} =+-- case p of Nothing -> [c]+-- Just (UnitCost ma) -> c:(concatMap amountCommodities $ amounts ma)+-- Just (TotalCost ma) -> c:(concatMap amountCommodities $ amounts ma)++-- | Get an ordered list of amounts in this journal which can influence+-- canonical amount display styles (excluding the ones in commodity directives). +-- They are, in the following order:+--+-- * amounts in market price (P) directives (in parse order)+-- * posting amounts and optionally cost amounts (in parse order)+-- * the amount in the final default commodity (D) directive+--+journalStyleInfluencingAmounts :: Bool -> Journal -> [Amount]+journalStyleInfluencingAmounts includecost j =+ dbg7 "journalStyleInfluencingAmounts" $+ catMaybes $ concat [+ [mdefaultcommodityamt]+ ,map (Just . pdamount) $ jpricedirectives j+ ,map Just $ if includecost+ then journalPostingAndCostAmounts j+ else concatMap amountsRaw $ journalPostingAmounts j+ ]+ where+ -- D's amount style isn't actually stored as an amount, make it into one+ mdefaultcommodityamt =+ case jparsedefaultcommodity j of+ Just (symbol,style) -> Just nullamt{acommodity=symbol,astyle=style}+ Nothing -> Nothing++-- overcomplicated/unused amount traversal stuff+--+-- Get an ordered list of 'AmountStyle's from the amounts in this+-- journal which influence canonical amount display styles. See+-- traverseJournalAmounts.+-- journalAmounts :: Journal -> [Amount]+-- journalAmounts = getConst . traverseJournalAmounts (Const . (:[]))+--+-- Apply a transformation to the journal amounts traversed by traverseJournalAmounts.+-- overJournalAmounts :: (Amount -> Amount) -> Journal -> Journal+-- overJournalAmounts f = runIdentity . traverseJournalAmounts (Identity . f)+--+-- A helper that traverses over most amounts in the journal,+-- in particular the ones which influence canonical amount display styles,+-- processing them with the given applicative function.+--+-- These include, in the following order:+--+-- * the amount in the final default commodity (D) directive+-- * amounts in market price (P) directives (in parse order)+-- * posting amounts in transactions (in parse order)+--+-- Transaction price amounts, which may be embedded in posting amounts+-- (the acost field), are left intact but not traversed/processed.+--+-- traverseJournalAmounts :: Applicative f => (Amount -> f Amount) -> Journal -> f Journal+-- traverseJournalAmounts f j =+-- recombine <$> (traverse . dcamt) f (jparsedefaultcommodity j)+-- <*> (traverse . pdamt) f (jpricedirectives j)+-- <*> (traverse . tps . traverse . pamt . amts . traverse) f (jtxns j)+-- where+-- recombine pds txns = j { jpricedirectives = pds, jtxns = txns }+-- -- a bunch of traversals+-- dcamt g pd = (\mdc -> case mdc of Nothing -> Nothing+-- Just ((c,stpd{pdamount =amt}+-- ) <$> g (pdamount pd)+-- pdamt g pd = (\amt -> pd{pdamount =amt}) <$> g (pdamount pd)+-- tps g t = (\ps -> t {tpostings=ps }) <$> g (tpostings t)+-- pamt g p = (\amt -> p {pamount =amt}) <$> g (pamount p)+-- amts g (Mixed as) = Mixed <$> g as++-- | The fully specified exact date span enclosing the dates (primary or secondary)+-- of all this journal's transactions and postings, or DateSpan Nothing Nothing+-- if there are none.+journalDateSpan :: Bool -> Journal -> DateSpan+journalDateSpan False = journalDateSpanHelper $ Just PrimaryDate+journalDateSpan True = journalDateSpanHelper $ Just SecondaryDate++-- | The fully specified date span enclosing the dates (primary and secondary)+-- of all this journal's transactions and postings, or DateSpan Nothing Nothing+-- if there are none.+journalDateSpanBothDates :: Journal -> DateSpan+journalDateSpanBothDates = journalDateSpanHelper Nothing++-- | A helper for journalDateSpan which takes Maybe WhichDate directly. Nothing+-- uses both primary and secondary dates.+journalDateSpanHelper :: Maybe WhichDate -> Journal -> DateSpan+journalDateSpanHelper whichdate j =+ DateSpan (Exact <$> minimumMay dates) (Exact . addDays 1 <$> maximumMay dates)+ where+ dates = pdates ++ tdates+ tdates = concatMap gettdate ts+ pdates = concatMap getpdate $ concatMap tpostings ts+ ts = jtxns j+ gettdate t = case whichdate of+ Just PrimaryDate -> [tdate t]+ Just SecondaryDate -> [fromMaybe (tdate t) $ tdate2 t]+ Nothing -> tdate t : maybeToList (tdate2 t)+ getpdate p = case whichdate of+ Just PrimaryDate -> maybeToList $ pdate p+ Just SecondaryDate -> maybeToList $ pdate2 p <|> pdate p+ Nothing -> catMaybes [pdate p, pdate2 p]++-- | The earliest of this journal's transaction and posting dates, or+-- Nothing if there are none.+journalStartDate :: Bool -> Journal -> Maybe Day+journalStartDate secondary j = fromEFDay <$> b where DateSpan b _ = journalDateSpan secondary j++-- | The "exclusive end date" of this journal: the day following its latest transaction +-- or posting date, or Nothing if there are none.+journalEndDate :: Bool -> Journal -> Maybe Day+journalEndDate secondary j = fromEFDay <$> e where DateSpan _ e = journalDateSpan secondary j++-- | The latest of this journal's transaction and posting dates, or+-- Nothing if there are none.+journalLastDay :: Bool -> Journal -> Maybe Day+journalLastDay secondary j = addDays (-1) <$> journalEndDate secondary j++-- | Apply the pivot transformation to all postings in a journal,+-- replacing their account name by their value for the given field or tag.+journalPivot :: Text -> Journal -> Journal+journalPivot fieldortagname j = j{jtxns = map (transactionPivot fieldortagname) . jtxns $ j}++-- | Replace this transaction's postings' account names with the value+-- of the given field or tag, if any.+-- The postings are relinked to the new transaction, so that queries which+-- look at a posting's siblings (any:, all:) see the pivoted account names.+transactionPivot :: Text -> Transaction -> Transaction+transactionPivot fieldortagname t = txnTieKnot t{tpostings = map (postingPivot fieldortagname) . tpostings $ t}++-- | Replace this posting's account name with the value+-- of the given field or tag, if any, otherwise the empty string.+postingPivot :: Text -> Posting -> Posting+postingPivot fieldortagname p =+ p{paccount = pivotAccount fieldortagname p, poriginal = Just $ originalPosting p}++pivotAccount :: Text -> Posting -> Text+pivotAccount fieldortagname p =+ T.intercalate ":" [pivotComponent x p | x <- T.splitOn ":" fieldortagname]++-- | Get the value of the given field or tag for this posting.+-- "comm" and "cur" are accepted as synonyms meaning the commodity symbol.+-- Pivoting on an unknown field or tag, or on commodity when there are multiple commodities, returns "".+-- Pivoting on a tag when there are multiple values for that tag, returns the first value.+-- Pivoting on the "type" tag normalises type values to their short spelling.+pivotComponent :: Text -> Posting -> Text+pivotComponent fieldortagname p+ | fieldortagname == "code", Just t <- ptransaction p = tcode t+ | fieldortagname `elem` descnames, Just t <- ptransaction p = tdescription t+ | fieldortagname == "payee", Just t <- ptransaction p = transactionPayee t+ | fieldortagname == "note", Just t <- ptransaction p = transactionNote t+ | fieldortagname == "status", Just t <- ptransaction p = T.pack . show . tstatus $ t+ | fieldortagname `elem` acctnames = paccount p+ | fieldortagname `elem` commnames = case map acommodity $ amounts $ pamount p of [s] -> s; _ -> unknown+ | fieldortagname == "amt" = case amounts $ pamount p of [a] -> T.pack $ show $ aquantity a; _ -> unknown+ | fieldortagname == "cost" = case amounts $ pamount p of [a@Amount{acost=Just _}] -> T.pack $ lstrip $ showAmountCost a; _ -> unknown+ | Just (_, tagvalue) <- postingFindTag fieldortagname p =+ if fieldortagname == "type"+ then either (const tagvalue) (T.pack . show) $ parseAccountType True tagvalue+ else tagvalue+ | otherwise = unknown+ where+ descnames = ["desc", "description"] -- allow "description" for hledger <=1.30 compat+ acctnames = ["acct", "account"] -- allow either; acct is the query prefix, account is more natural+ commnames = ["cur","comm"] -- allow either; cur is the query prefix, comm is more consistent+ unknown = ""++postingFindTag :: TagName -> Posting -> Maybe (TagName, TagValue)+postingFindTag tagname p = find ((tagname==) . fst) $ postingAllTags p++-- | Apply some account aliases to all posting account names in the journal, as described by accountNameApplyAliases.+-- This can fail due to a bad replacement pattern in a regular expression alias.+journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal+-- short circuit the common case, just in case there's a performance impact from txnTieKnot etc.+journalApplyAliases [] j = Right j+journalApplyAliases aliases j = + case mapM (transactionApplyAliases aliases) $ jtxns j of+ Right ts -> Right j{jtxns = ts}+ Left err -> Left err++-- -- | Build a database of market prices in effect on the given date,+-- -- from the journal's price directives.+-- journalPrices :: Day -> Journal -> Prices+-- journalPrices d = toPrices d . jpricedirectives++-- -- | Render a market price as a P directive.+-- showPriceDirectiveDirective :: PriceDirective -> String+-- showPriceDirectiveDirective pd = unwords+-- [ "P"+-- , showDate (pddate pd)+-- , T.unpack (pdcommodity pd)+-- , (showAmount . amountSetPrecision maxprecision) (pdamount pd+-- )+-- ]++-- debug helpers+-- traceAmountPrecision a = trace (show $ map (precision . acommodity) $ amounts a) a+-- tracePostingsCommodities ps = trace (show $ map ((map (precision . acommodity) . amounts) . pamount) ps) ps++-- tests+--+-- A sample journal for testing, similar to examples/sample.journal.+-- Provide an option to either use explicit amounts or missing amounts, for testing purposes.+--+-- 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/10/01 take a loan+-- assets:bank:checking $1+-- liabilities:debts $-1+--+-- 2008/12/31 * pay off+-- liabilities:debts $1+-- assets:bank:checking++samplejournal = samplejournalMaybeExplicit True++samplejournalMaybeExplicit :: Bool -> Journal+samplejournalMaybeExplicit explicit = nulljournal+ {jtxns = [+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 01 01,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="income",+ tcomment="",+ ttags=[],+ tpostings=+ ["assets:bank:checking" `post` usd 1+ ,"income:salary" `post` if explicit then usd (-1) else missingamt+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 06 01,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="gift",+ tcomment="",+ ttags=[],+ tpostings=+ ["assets:bank:checking" `post` usd 1+ ,"income:gifts" `post` if explicit then usd (-1) else missingamt+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 06 02,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="save",+ tcomment="",+ ttags=[],+ tpostings=+ ["assets:bank:saving" `post` usd 1+ ,"assets:bank:checking" `post` if explicit then usd (-1) else missingamt+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 06 03,+ tdate2=Nothing,+ tstatus=Cleared,+ tcode="",+ tdescription="eat & shop",+ tcomment="",+ ttags=[],+ tpostings=["expenses:food" `post` usd 1+ ,"expenses:supplies" `post` usd 1+ ,"assets:cash" `post` if explicit then usd (-2) else missingamt+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 10 01,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="take a loan",+ tcomment="",+ ttags=[],+ tpostings=["assets:bank:checking" `post` usd 1+ ,"liabilities:debts" `post` usd (-1)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot $ Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 12 31,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="pay off",+ tcomment="",+ ttags=[],+ tpostings=["liabilities:debts" `post` usd 1+ ,"assets:bank:checking" `post` if explicit then usd (-1) else missingamt+ ],+ tprecedingcomment=""+ }+ ]+ }++tests_Journal = testGroup "Journal" [++ testCase "journalDateSpan" $+ journalDateSpan True nulljournal{+ jtxns = [nulltransaction{tdate = fromGregorian 2014 02 01+ ,tpostings = [posting{pdate=Just (fromGregorian 2014 01 10)}]+ }+ ,nulltransaction{tdate = fromGregorian 2014 09 01+ ,tpostings = [posting{pdate2=Just (fromGregorian 2014 10 10)}]+ }+ ]+ }+ @?= (DateSpan (Just $ Exact $ fromGregorian 2014 1 10) (Just $ Exact $ fromGregorian 2014 10 11))+ ]
+ Hledger/Data/JournalChecks.hs view
@@ -0,0 +1,405 @@+{-|+Various additional validation checks that can be performed on a Journal.+Some are called as part of reading a file in strict mode,+others can be called only via the check command.+-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Data.JournalChecks (+ journalStrictChecks,+ journalCheckAsserts,+ journalCheckAccounts,+ journalCheckBalanceAssertions,+ journalCheckCommodities,+ journalUndeclaredCommodities,+ journalCheckLots,+ journalCheckPayees,+ journalCheckPairedConversionPostings,+ journalCheckRecentAssertions,+ journalCheckTags,+ module Hledger.Data.JournalChecks.Ordereddates,+ module Hledger.Data.JournalChecks.Uniqueleafnames,+)+where++import Data.Char (isSpace)+import Data.List.Extra+import Data.Map qualified as M+import Data.Maybe+import Data.Set qualified as S+import Data.Text qualified as T+import Safe (atMay, lastMay, headMay)+import Text.Printf (printf)++import Hledger.Data.AccountName (isAccountNamePrefixOf)+import Hledger.Data.Errors+import Hledger.Data.Journal+import Hledger.Data.JournalChecks.Assert+import Hledger.Data.JournalChecks.Ordereddates+import Hledger.Data.JournalChecks.Uniqueleafnames+import Hledger.Data.Posting (defaultDecimalMarkColumn, isVirtual, postingDate, postingHasTag, transactionAllTags, conversionPostingTagName, costPostingTagName, imbalancePostingTagName, postingAsLines, generatedPostingTagName, generatedTransactionTagName, modifiedTransactionTagName, feesplitPostingTagName, lotsplitPostingTagName, lotParentAssertionTagName, AmountCols(..))+import Hledger.Data.Types+import Hledger.Data.Amount (amountIsZero, amountsRaw, defaultFmt, missingamt)+import Hledger.Data.Transaction (transactionPayee, showTransactionLineFirstPart, partitionAndCheckConversionPostings)+import Data.Time (diffDays)+import Hledger.Utils+import Data.Ord+import Hledger.Data.Dates (showDate)+import Hledger.Data.Balancing (journalBalanceTransactions, defbalancingopts)+import Hledger.Data.Lots (isGainPosting, lotBaseAccount)++-- | Run the extra -s/--strict checks on a journal, in order of priority,+-- returning the first error message if any of them fail.+journalStrictChecks :: Journal -> Either String ()+journalStrictChecks j = do+ -- keep the order of checks here synced with Check.md and Hledger.Cli.Commands.Check.Check.+ -- balanced is checked earlier, in journalFinalise+ journalCheckCommodities j+ journalCheckAccounts j++-- | Check that all the journal's postings are to accounts with+-- account directives, returning an error message otherwise.+-- Postings which hledger generated, to an account it chose, are exempt.+journalCheckAccounts :: Journal -> Either String ()+journalCheckAccounts j = mapM_ checkacct (journalPostings j)+ where+ declaredaccts = S.fromList $ map fst $ jdeclaredaccounts j+ checkacct p@Posting{paccount=a}+ | hasGeneratedAccount p = Right ()+ | acct `S.member` declaredaccts = Right ()+ | otherwise = Left $ printf (unlines [+ "%s:%d:"+ ,"%s"+ ,"Strict account checking is enabled, and"+ ,"account \"%s\" has not been declared."+ ]) f l ex acct+ ++ unlines advice+ where+ acct = lotBaseAccount a+ (f,l,_mcols,ex) = makePostingAccountErrorExcerpt p+ advice = case outOfScopeAlias acct of+ Just (alias, target, pos) -> [+ printf "\"%s\" is an alias of account \"%s\", declared at %s," alias target (sourcePosFileLine pos)+ ,"but that alias does not apply here. An account alias affects only the entries after it"+ ,"in the same file or its included files, until end of file or an end aliases directive."+ ,"Consider declaring the account before this entry (in this file or a file including it),"+ ,"or writing the account's full name."+ ]+ Nothing -> [+ "Consider adding an account directive. Examples:"+ ,""+ ,"account " <> T.unpack acct+ ]++ -- An alias: tag of a declared account which matches this account name (wholly or its leading components),+ -- and its account and declaration position. Such an alias was not in effect here, or it would have been applied.+ outOfScopeAlias acct = headMay+ [ (alias, target, adisourcepos adi)+ | (target, adi) <- jdeclaredaccounts j+ , (n, alias) <- journalAccountTags j target+ , T.toLower n == "alias"+ , alias == acct || alias `isAccountNamePrefixOf` acct+ ]++ -- Was this posting generated by hledger, to an account chosen by hledger (not the user) ?+ -- Ie, an equity conversion posting from --infer-equity, a gain posting in a lot disposal,+ -- or an imbalance posting from --infer-imbalance. (Not eg an auto posting, whose account the user chose.)+ hasGeneratedAccount p =+ postingHasTag imbalancePostingTagName p+ || (postingHasTag generatedPostingTagName p && (postingHasTag conversionPostingTagName p || isGainPosting p))++-- | Check all balance assertions in the journal and return an error message if any of them fail.+-- (Technically, this also tries to balance the journal and can return balancing failure errors;+-- ensure the journal is already balanced (with journalBalanceTransactions) to avoid this.)+journalCheckBalanceAssertions :: Journal -> Either String ()+journalCheckBalanceAssertions = fmap (const ()) . journalBalanceTransactions defbalancingopts++-- | The distinct commodity symbols referenced in a posting's amount(s) or+-- balance assertion, ignoring the "missing" amount and bare zeroes (#1767).+postingCommoditiesUsed :: Posting -> [CommoditySymbol]+postingCommoditiesUsed Posting{pamount=amt, pbalanceassertion} =+ map acommodity (filter (not . isIgnorable) $ amountsRaw amt)+ ++ [acommodity a | Just a <- [baamount <$> pbalanceassertion]]+ where isIgnorable a = a==missingamt || (amountIsZero a && T.null (acommodity a)) -- #1767++-- | The commodity symbols referenced in a P directive.+priceDirectiveCommoditiesUsed :: PriceDirective -> [CommoditySymbol]+priceDirectiveCommoditiesUsed PriceDirective{pdcommodity=c, pdamount=amt} = [c, acommodity amt]++-- | The commodities referenced by this journal's postings and P directives that+-- have not been declared by a commodity directive, nor as an @alias:@ of one.+-- These are exactly the commodities that make 'journalCheckCommodities' (hledger+-- check commodities, and -s) fail. The synthetic 1:1 price directives inferred+-- from @alias:@ tags contribute only aliases, so they never appear here.+journalUndeclaredCommodities :: Journal -> [CommoditySymbol]+journalUndeclaredCommodities j =+ filter (`S.notMember` commoditiesAndAliases j) . nubSort $+ concatMap priceDirectiveCommoditiesUsed (jpricedirectives j)+ ++ concatMap postingCommoditiesUsed (journalPostings j)++-- | Check that all the commodities used in this journal's postings and P directives+-- have been declared by commodity directives, returning an error message otherwise.+journalCheckCommodities :: Journal -> Either String ()+journalCheckCommodities j = do+ mapM_ checkPriceDirectiveCommodities $ jpricedirectives j+ mapM_ checkPostingCommodities $ journalPostings j+ where+ declared = commoditiesAndAliases j+ firstUndeclaredOf = find (`S.notMember` declared)++ errmsg = unlines [+ "%s:%d:"+ ,"%s"+ ,"Strict commodity checking is enabled, and"+ ,"commodity %s has not been declared."+ ,"Consider adding a commodity directive. Examples:"+ ,""+ ,"commodity %s1000.00"+ ,"commodity 1.000,00 %s"+ ]++ checkPriceDirectiveCommodities pd =+ case firstUndeclaredOf (priceDirectiveCommoditiesUsed pd) of+ Nothing -> Right ()+ Just comm -> Left $ printf errmsg f l ex (show comm) comm comm+ where (f,l,_mcols,ex) = makePriceDirectiveErrorExcerpt pd Nothing++ checkPostingCommodities p =+ case firstUndeclaredOf (postingCommoditiesUsed p) of+ Nothing -> Right ()+ Just comm -> Left $ printf errmsg f l ex (show comm) comm comm+ where+ (f,l,_mcols,ex) = makePostingErrorExcerpt p finderrcols+ where+ -- Calculate columns suitable for highlighting the excerpt.+ -- We won't show these in the main error line as they aren't+ -- accurate for the actual data.++ -- Find the best position for an error column marker when this posting+ -- is rendered by showTransaction.+ -- Reliably locating a problem commodity symbol in showTransaction output+ -- is really tricky. Some examples:+ --+ -- assets "C $" -1 @ $ 2+ -- ^+ -- assets $1 = $$1+ -- ^+ -- assets [ANSI RED]$-1[ANSI RESET]+ -- ^+ --+ -- To simplify, we will mark the whole amount + balance assertion region, like:+ -- assets "C $" -1 @ $ 2+ -- ^^^^^^^^^^^^^^+ -- XXX refine this region when it's easy+ finderrcols p' t txntxt =+ case transactionFindPostingIndex (==p') t of+ Nothing -> Nothing+ Just pindex -> Just (amtstart, Just amtend)+ where+ tcommentlines = max 0 (length (T.lines $ tcomment t) - 1)+ errrelline = 1 + tcommentlines + pindex -- XXX doesn't count posting coment lines+ errline = fromMaybe "" (T.lines txntxt `atMay` (errrelline-1))+ acctend = 4 + T.length (paccount p') + if isVirtual p' then 2 else 0+ amtstart = acctend + (T.length $ T.takeWhile isSpace $ T.drop acctend errline) + 1+ amtend = amtstart + (T.length $ T.stripEnd $ T.takeWhile (/=';') $ T.drop amtstart errline)++-- | Check that all the journal's transactions have payees declared with+-- payee directives, returning an error message otherwise.+journalCheckPayees :: Journal -> Either String ()+journalCheckPayees j = mapM_ checkpayee (jtxns j)+ where+ declaredpayees = S.fromList $ map fst $ jdeclaredpayees j+ checkpayee t+ | payee `S.member` declaredpayees = Right ()+ | otherwise = Left $+ printf (unlines [+ "%s:%d:"+ ,"%s"+ ,"Strict payee checking is enabled, and"+ ,"payee %s has not been declared."+ ,"Consider adding a payee directive. Examples:"+ ,""+ ,"payee %s"+ ]) f l ex (show payee) payee+ where+ payee = transactionPayee t+ (f,l,_mcols,ex) = makeTransactionErrorExcerpt t finderrcols+ -- Calculate columns suitable for highlighting the excerpt.+ -- We won't show these in the main error line as they aren't+ -- accurate for the actual data.+ finderrcols t' = Just (col, Just col2)+ where+ col = T.length (showTransactionLineFirstPart t') + 2+ col2 = col + T.length (transactionPayee t') - 1++-- | Check that all the journal's tags (on accounts, commodities, transactions, postings..)+-- have been declared with tag directives, returning an error message otherwise.+journalCheckTags :: Journal -> Either String ()+journalCheckTags j = do+ mapM_ checkaccttags $ jdeclaredaccounts j+ mapM_ checkcommtags $ M.elems $ jdeclaredcommodities j+ mapM_ checktxntags $ jtxns j+ where+ checkaccttags (a, adi) = mapM_ (checkaccttag.fst) $ aditags adi+ where+ checkaccttag tagname+ | tagname `S.member` declaredtags = Right ()+ | otherwise = Left $ printf msg f l ex (show tagname) tagname+ where (f,l,_mcols,ex) = makeAccountTagErrorExcerpt (a, adi) tagname+ checkcommtags c = mapM_ (checkcommtag.fst) $ ctags c+ where+ checkcommtag tagname+ | tagname `S.member` declaredtags = Right ()+ | otherwise = Left $ printf msg f l ex (show tagname) tagname+ where (f,l,_mcols,ex) = makeCommodityTagErrorExcerpt c tagname+ checktxntags txn = mapM_ (checktxntag . fst) $ transactionAllTags txn+ where+ checktxntag tagname+ | tagname `S.member` declaredtags = Right ()+ | otherwise = Left $ printf msg f l ex (show tagname) tagname+ where+ (f,l,_mcols,ex) = makeTransactionErrorExcerpt txn finderrcols+ where+ finderrcols _txn' = Nothing+ -- don't bother for now+ -- Just (col, Just col2)+ -- where+ -- col = T.length (showTransactionLineFirstPart txn') + 2+ -- col2 = col + T.length tagname - 1+ declaredtags = S.fromList $ map fst (jdeclaredtags j) ++ builtinTags+ msg = (unlines [+ "%s:%d:"+ ,"%s"+ ,"Strict tag checking is enabled, and"+ ,"tag %s has not been declared."+ ,"Consider adding a tag directive. Examples:"+ ,""+ ,"tag %s"+ ])++-- | Tag names which have special significance to hledger, and need not be declared for `hledger check tags`.+-- Keep synced with check-tags.test and hledger manual > Special tags.+builtinTags = [+ "date" -- overrides a posting's date+ ,"date2" -- overrides a posting's secondary date+ ,"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+ ,"t" -- appears on postings generated by timedot letters+ ,"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+ ]+ -- these tags are used in both hidden and visible form+ <> ts <> map toVisibleTagName ts+ where+ ts = [+ generatedTransactionTagName -- marks txns generated by periodic rule+ ,modifiedTransactionTagName -- marks txns which have had auto postings added+ ,generatedPostingTagName -- marks postings which have been generated+ ,costPostingTagName -- marks equity conversion postings which have been matched with a nearby costful posting+ ,conversionPostingTagName -- marks costful postings which have been matched with a nearby pair of equity conversion postings+ ,"_ptype" -- marks lot postings with their classification (acquire, dispose, transfer-from, transfer-to, gain)+ ,feesplitPostingTagName -- marks fee fragments split off lot transfers+ ,lotsplitPostingTagName -- marks tail fragments of postings split across lots+ ,lotParentAssertionTagName -- marks postings carrying a balance assertion relocated from a posting split into lots+ ]++-- | In each tranaction, check that any conversion postings occur in adjacent pairs.+journalCheckPairedConversionPostings :: Journal -> Either String ()+journalCheckPairedConversionPostings j =+ mapM_ (transactionCheckPairedConversionPostings conversionaccts) $ jtxns j+ where conversionaccts = journalConversionAccounts j++transactionCheckPairedConversionPostings :: [AccountName] -> Transaction -> Either String ()+transactionCheckPairedConversionPostings conversionaccts t =+ case partitionAndCheckConversionPostings True conversionaccts (zip [0..] $ tpostings t) of+ Left err -> Left $ T.unpack err+ Right _ -> Right ()++----------++-- | The number of days allowed between an account's latest balance assertion +-- and latest posting (7).+maxlag = 7++-- | Check that accounts with balance assertions have no posting more+-- than maxlag days after their latest balance assertion.+journalCheckRecentAssertions :: Journal -> Either String ()+journalCheckRecentAssertions j =+ let acctps = groupOn paccount $ sortOn paccount $ journalPostings j+ in case mapMaybe findRecentAssertionError acctps of+ [] -> Right ()+ firsterr:_ -> Left firsterr++-- | Do the recentassertions check for one account: given a list of postings to the account,+-- if any of them contain a balance assertion, identify the latest balance assertion,+-- and if any postings are >maxlag days later than the assertion,+-- return an error message identifying the first of them.+-- Postings on the same date will be handled in parse order (hopefully).+findRecentAssertionError :: [Posting] -> Maybe String+findRecentAssertionError ps = do+ let rps = sortOn (Data.Ord.Down . postingDate) ps+ let (afterlatestassertrps, untillatestassertrps) = span (isNothing.pbalanceassertion) rps+ latestassertdate <- postingDate <$> headMay untillatestassertrps+ let withinlimit date = diffDays date latestassertdate <= maxlag+ firsterrorp <- lastMay $ dropWhileEnd (withinlimit.postingDate) afterlatestassertrps+ let lag = diffDays (postingDate firsterrorp) latestassertdate+ let acct = paccount firsterrorp+ let (f,l,_mcols,ex) = makePostingAccountErrorExcerpt firsterrorp+ -- let comm =+ -- case map acommodity $ amounts $ pamount firsterrorp of+ -- [] -> ""+ -- (t:_) | T.length t == 1 -> t+ -- (t:_) -> t <> " "+ Just $ chomp $ printf+ (unlines [+ "%s:%d:",+ "%s\n",+ -- "The recentassertions check is enabled, so accounts with balance assertions must",+ -- "have a balance assertion within %d days of their latest posting.",+ "The recentassertions check is enabled, so accounts with balance assertions",+ "must have a recent one, not more than %d days older than their latest posting.",+ "In account: %s",+ "the last assertion was on %s, %d days before this latest posting.",+ "Consider adding a new balance assertion to the above posting. Eg:",+ "",+ "%s = BALANCE"+ ])+ f+ l+ (textChomp ex)+ maxlag+ (bold' $ T.unpack acct)+ (showDate latestassertdate)+ lag+ (showposting firsterrorp)+ where+ showposting p =+ headDef "" $ fst $ postingAsLines defaultFmt False True statusw acctw dc p{pcomment=""}+ where+ statusw = case pstatus p of Unmarked -> 0; _ -> 2+ acctw = T.length $ paccount p+ -- single-posting render: no cross-posting alignment to satisfy,+ -- so eqcol / asndecimalcol are unused (no assertion is rendered+ -- here either, but pass safe defaults).+ dc = AmountCols { acDecMark = defaultDecimalMarkColumn, acEquals = 0, acAssDecMark = 0 }++-- -- | Print the last balance assertion date & status of all accounts with balance assertions.+-- printAccountLastAssertions :: Day -> [BalanceAssertionInfo] -> IO ()+-- printAccountLastAssertions today acctassertioninfos = do+-- forM_ acctassertioninfos $ \BAI{..} -> do+-- putStr $ printf "%-30s %s %s, %d days ago\n"+-- baiAccount+-- (if baiLatestClearedAssertionStatus==Unmarked then " " else show baiLatestClearedAssertionStatus)+-- (show baiLatestClearedAssertionDate)+-- (diffDays today baiLatestClearedAssertionDate)++-- | Check all lot tracking calculations. Validation runs during journalFinalise+-- (unless --ignore-lots/-I is in effect), so any valid Journal reaching this point+-- has already passed the checks. This stub exists so @hledger check lots@ remains+-- a valid command, and also re-enables the validation when -I was passed.+journalCheckLots :: Journal -> Either String ()+journalCheckLots _ = Right ()
+ Hledger/Data/JournalChecks/Assert.hs view
@@ -0,0 +1,410 @@+{-|+Checking assert directives: standing rules declared in the journal,+each a query which must match no rows, or some rows, of the equivalent balance report+(over the whole journal, or in every period of a period expression).+See the hledger manual's "assert directive" section, and doc/SPEC-assert.md.++The rows are calculated here by direct accumulation over the journal's postings,+replicating what @hledger bal -E QUERY@ would show, rather than by running the balance report,+which would make journal reading depend on the reports code.+-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.JournalChecks.Assert (+ journalCheckAsserts+)+where++import Control.Monad (mfilter)+import Data.Char (isAlphaNum)+import Data.HashMap.Strict qualified as HM+import Data.IntMap qualified as IM+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List (sortBy, transpose)+import Data.Map.Strict qualified as M+import Data.Maybe (isNothing, mapMaybe)+import Safe (headMay, lastMay)+import Data.Ord (comparing)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day, addDays)+import Text.Printf (printf)+import Text.Megaparsec (SourcePos(..), unPos)++import Hledger.Data.AccountName (clipOrEllipsifyAccountName)+import Hledger.Data.Amount (maPlus, nullmixedamt, showMixedAmountOneLine)+import Hledger.Data.Dates (showDate, showDateSpan, spanContainsDate, spanEnd, spanIntersect, spanStart, spanValidDefaultsFrom)+import Hledger.Data.DayPartition (splitSpanToDateSpans)+import Hledger.Data.Errors (decorateExcerpt)+import Hledger.Data.Journal (filterPostingAmount, journalAccountType, journalDateSpan, journalPostings)+import Hledger.Data.Posting (hasAmount, postingDate, postingStripCosts)+import Hledger.Data.Types+import Hledger.Query+import Hledger.Utils (fitText)+import Text.DocLayout (realLength)++-- | Check the rules of all this journal's assert directives, in parse order,+-- returning an error message for the first failure.+-- The day is today's date, for resolving relative dates in queries.+journalCheckAsserts :: Day -> Journal -> Either String ()+journalCheckAsserts today j = mapM_ (checkAssert today j acctids numberedps jspan) $ jasserts j+ where+ -- Calculated once, for all directives: the journal's postings in date order+ -- (stably, so same-day postings stay in parse order), each with its account number+ -- (see assertAccountQueriesEnabled), and the journal's date span.+ (acctids, numberedps) = numberPostingAccounts $ sortBy (comparing postingDate) $ journalPostings j+ jspan = journalDateSpan False j++-- | A posting's account names, as used by account query terms: its account,+-- and its original account (before aliasing or pivoting) if that is different.+type PostingAccounts = (AccountName, Maybe AccountName)++postingAccounts :: Posting -> PostingAccounts+postingAccounts p = (a, mfilter (/= a) $ paccount <$> poriginal p) where a = paccount p++-- | Number the distinct account names of these postings, returning the numbering,+-- and the postings with their numbers (in the same order).+numberPostingAccounts :: [Posting] -> (HM.HashMap PostingAccounts Int, [(Int, Posting)])+numberPostingAccounts ps = (ids, reverse numbered)+ where+ (ids, numbered) = foldl' number (HM.empty, []) ps+ number (m, acc) p = case HM.lookup k m of+ Just i -> (m, (i, p) : acc)+ Nothing -> let !i = HM.size m in (HM.insert k i m, (i, p) : acc)+ where k = postingAccounts p++-- | What matched at a failing checkpoint, shown in the error message:+-- the matching rows (account, change, balance), or, when the query has no+-- change:/balance: terms and so is about which postings exist, the matching postings.+-- (At a failing checkpoint of a some rule, nothing matched.)+data Evidence = MatchedRows [(AccountName, MixedAmount, MixedAmount)] | MatchedPostings [Posting]++-- | A failing checkpoint: its span, how many rows or postings matched there,+-- and the first of them (as many as the error message may still show).+data Failure = Failure !DateSpan !Int Evidence++-- | Keep only the first n items of some evidence.+takeEvidence :: Int -> Evidence -> Evidence+takeEvidence n (MatchedRows rows) = MatchedRows $ take n rows+takeEvidence n (MatchedPostings ps) = MatchedPostings $ take n ps++-- | How many items some evidence has.+evidenceSize :: Evidence -> Int+evidenceSize (MatchedRows rows) = length rows+evidenceSize (MatchedPostings ps) = length ps++-- | Evaluate some evidence fully, so that it doesn't keep the checking state of its checkpoint alive.+forceEvidence :: Evidence -> ()+forceEvidence (MatchedPostings ps) = length ps `seq` ()+forceEvidence (MatchedRows rows) = foldr (\(a, chg, bal) r -> a `seq` chg `seq` bal `seq` r) () rows++-- | An account's running balance, and its matching-amount counts (see 'assertCountingEnabled').+data RunningBalance = RunningBalance !MixedAmount ![Int]++-- | Matching-amount counts: an optimisation for periodic rules with balance: terms.+-- These rules re-test an account's balance in each period where it changes, and a balance: term+-- matches a balance if any one of its single-commodity amounts does, so a balance holding many+-- commodities (dozens, or even hundreds) is costly to re-test. Instead, each running balance+-- keeps, for each balance: term, a count of its amounts which match; a posting changes only the+-- amounts in its own commodities, so only those are re-tested to update the counts, and the term+-- matches the balance when its count is above zero. This makes the cost per posting independent+-- of how many commodities the balance holds. (The error message's rows are still calculated+-- directly, see evidenceAt.)+--+-- The one rule for this code: with the counts, balanceMatches must give exactly what testing the+-- whole balance would. To disable the optimisation, eg while investigating a wrong result, set+-- this to False: balances are then re-tested in full, which is slower but simpler.+-- The code it enables is marked "matching-amount counts" in checkAssert.+assertCountingEnabled :: Bool+assertCountingEnabled = True++-- | Per-account queries: an optimisation for selecting each rule's postings.+-- Each rule's query is tested against every posting in the journal, and its account terms+-- (acct:, type:, depth:) are regular expression matches against the posting's account name,+-- which cost much more than the rest. But postings share a few account names, so instead,+-- for each distinct account name the query is partially evaluated (see 'postingQueryForAccount'),+-- leaving a smaller query (usually just "match all" or "match none") to test against that+-- account's postings. This makes selecting postings several times cheaper.+--+-- The one rule for this code: the per-account query must match exactly the postings+-- the whole query would. To disable the optimisation, eg while investigating a wrong result,+-- set this to False: each posting is then tested with the whole query.+assertAccountQueriesEnabled :: Bool+assertAccountQueriesEnabled = True++-- A possible further optimisation, if many rules become common: each rule still scans all+-- of the journal's postings, so with 100 rules (on a large journal, measured 2026-11-10)+-- a bal report took about 3.5 times as long. Grouping the postings by account once, for+-- all rules, would let each rule visit only the accounts its per-account query doesn't+-- rule out (merging their postings by date), so that a rule about a few accounts would+-- cost almost nothing. Rules about many accounts would cost about the same as now.++-- | Check one assert directive's rule, given the journal's account numbering (see 'numberPostingAccounts'),+-- its postings in date order with their account numbers, and its date span.+-- Each checkpoint is the balance report @bal -E -b START -e END QUERY@: its rows are the+-- accounts (clipped to the query's depth) with postings matching the query in the period,+-- plus, when the query has balance: terms, the accounts with earlier postings (whose change+-- may be zero); each row has its change in the period and its balance at the period end.+-- All checkpoints are checked, so that a failure can report every failing checkpoint, and what matched there.+checkAssert :: Day -> Journal -> HM.HashMap PostingAccounts Int -> [(Int, Posting)] -> DateSpan -> AssertDirective -> Either String ()+checkAssert today j acctids numberedps jspan ad@AssertDirective{adQuantifier=quant, adPeriod=mperiod, adQueryText=querytxt, adSkips=skips} = do+ (rowq, otherq) <- either (Left . (errorPrefix ad <>)) Right $ querySplitRowTerms . fst =<< parseQuery today querytxt+ let+ -- As in the balance report, date: terms don't select postings; they set the report period,+ -- intersected with the period expression's span if any. (date2: terms are ignored, as in bal without --date2.)+ datespan = queryDateSpan False otherq++ -- The postings selected by the other non-row query terms, prepared as the balance report would:+ -- amounts limited to the parts matching amt:/cur: terms, and costs stripped. Still in date order,+ -- and generated lazily. Each is paired with a copy whose account name is clipped to the depth: terms'+ -- depth: the copies are what is checked, the originals are what an error message shows.+ depthspec = queryDepth otherq+ postingq = filterQuery (not . queryIsDateOrDate2) $ filterQuery (not . queryIsDepth) otherq+ amtq = filterQuery queryIsAmtOrCur postingq+ atype = journalAccountType j+ selected (i, p)+ | assertAccountQueriesEnabled = matchesPostingExtra atype (IM.findWithDefault postingq i queriesbyaccount) p+ | otherwise = matchesPostingExtra atype postingq p+ -- The posting query, partially evaluated for each account (lazily, when first needed).+ queriesbyaccount = IM.fromList [(i, postingQueryForAccount atype a morig postingq) | ((a, morig), i) <- HM.toList acctids]+ prepare p = do+ p' <- if queryIsNull amtq then Just p else filterPostingAmount amtq p+ Just $ postingStripCosts p'+ ps = [ (p, p{paccount = clipOrEllipsifyAccountName depthspec $ paccount p})+ | p <- filter hasAmount $ mapMaybe (prepare . snd) $ filter selected numberedps ]++ hasrowterms = not $ queryIsNull rowq+ hasbalanceq = queryHasBalance rowq+ haschangeq = queryHasChange rowq+ passes anymatched = case quant of+ AssertNone -> not anymatched+ AssertSome -> anymatched+ before mend (_, p) = maybe True (postingDate p <) mend+ onOrAfter mstart (_, p) = maybe True (postingDate p >=) mstart++ -- A period's changes by account.+ addPosting m p = M.insertWith (flip maPlus) (paccount p) (pamount p) m+ amountsOf = foldl' addPosting M.empty++ -- The change: and balance: terms, as amount comparisons, each with whether it is negated.+ -- (They are combined by AND, see querySplitRowTerms.)+ changeterms = [(neg, Amt o n mc) | (neg, Change o n mc) <- signedRowTerms rowq]+ balanceterms = [(neg, Amt o n mc) | (neg, Balance o n mc) <- signedRowTerms rowq]+ changeMatches chg = and [neg /= matchesMixedAmount t chg | (neg, t) <- changeterms]+ zerochangematches = changeMatches nullmixedamt++ -- Running balances by account. With assertCountingEnabled, these also have the matching-amount counts.+ addPostingRunning m p = M.insert (paccount p) (RunningBalance bal' counts') m+ where+ RunningBalance bal counts = M.findWithDefault (RunningBalance nullmixedamt $ map (const 0) balanceterms) (paccount p) m+ bal' = bal `maPlus` pamount p+ counts' | assertCountingEnabled = updateMatchCounts bal bal' (pamount p) counts+ | otherwise = counts+ -- Does this running balance match the balance: terms ?+ balanceMatches (RunningBalance bal@(Mixed amts) counts)+ | assertCountingEnabled && not (M.null amts) = and [neg /= (c > 0) | ((neg, _), c) <- zip balanceterms counts]+ | otherwise = and [neg /= matchesMixedAmount t bal | (neg, t) <- balanceterms]++ --- matching-amount counts (see assertCountingEnabled)+ -- Update an account's matching-amount counts, given its balance before and after a posting, and the+ -- posting's amount: only the amounts in the posting's commodities have changed, so only they are re-tested.+ updateMatchCounts bal bal' (Mixed pamts) counts = forceElems $ zipWith (+) counts+ [ sum [fromEnum (matchesIn bal' k) - fromEnum (matchesIn bal k) | k <- M.keys pamts]+ | (_, t) <- balanceterms+ , let matchesIn (Mixed amts) k = maybe False (matchesAmount t) $ M.lookup k amts ]+ where forceElems xs = foldr seq xs xs+ --- end of matching-amount counts++ -- The checkpoints: the whole journal within the date: span, or each period of the period expression.+ checkpoints = case mperiod of+ Nothing -> [datespan]+ Just (interval, spn) ->+ -- The periods, as the balance report would calculate them: from the period expression's span+ -- and the date: terms' span, with open ends filled from the journal's span,+ -- and adjusted to interval boundaries unless a start date was specified.+ let requestedspan = spn `spanIntersect` datespan+ in splitSpanToDateSpans (isNothing $ spanStart requestedspan) interval $+ requestedspan `spanValidDefaultsFrom` jspan++ -- Check each checkpoint in turn, returning the failing ones, each with the number of matches there,+ -- and the first of them, until the error message has as many as it will show (so that a rule+ -- failing in many periods doesn't accumulate all of their matches).+ -- Postings before the first checkpoint count in the balances only, and postings after the last are ignored.+ -- With balance: terms, this maintains the running balances, and the set of accounts whose+ -- balance matches the balance: terms, updating only the accounts posted to in each period.+ -- Each period's rows are the accounts with postings in it, plus, with balance: terms, the+ -- accounts with earlier postings, whose change is zero. Without change:/balance: terms every+ -- row matches, so it's just whether the period has any postings.+ -- Checkpoints in the periods of skip subdirectives are skipped, but their postings still count in the balances.+ checkPeriods _ _ _ _ [] = []+ checkPeriods !want !balances !matching remaining (sp:sps)+ | isSkipped sp || passes anyrowmatches = rest want+ | otherwise = let !failure = Failure sp nmatched kept -- evaluated now, not when the message reads it+ in forceEvidence kept `seq` (failure : rest (want - evidenceSize kept))+ where+ rest w = checkPeriods w balances' matching' later sps+ kept = takeEvidence want evidence+ (upto, later) = span (before $ spanEnd sp) remaining+ now = dropWhile (not . onOrAfter (spanStart sp)) upto+ changes = amountsOf $ map snd now+ (balances', matching')+ | hasbalanceq = (bals, foldl' upd matching $ S.fromList $ map (paccount . snd) upto)+ | otherwise = (balances, matching)+ where+ bals = foldl' addPostingRunning balances $ map snd upto+ upd s a = if maybe False balanceMatches (M.lookup a bals) then S.insert a s else S.delete a s+ anyrowmatches+ | not hasrowterms = not $ null now+ | not hasbalanceq = any changeMatches changes+ | not haschangeq = not $ S.null matching'+ | otherwise = any (\(a, chg) -> a `S.member` matching' && changeMatches chg) (M.toList changes)+ || (zerochangematches && any (`M.notMember` changes) (S.toList matching'))+ -- What matched here, for the error message, and how many (counted without listing them).+ nmatched+ | not hasrowterms = length now+ | not hasbalanceq = length $ filter changeMatches $ M.elems changes+ | not haschangeq = S.size matching'+ | otherwise = length [() | (a, chg) <- M.toList changes, a `S.member` matching', changeMatches chg]+ + (if zerochangematches then S.size matching' - length (filter (`S.member` matching') $ M.keys changes) else 0)+ evidence+ | not hasrowterms = MatchedPostings $ map fst now+ | hasbalanceq = MatchedRows [ (a, chg, bal) | a <- S.toAscList matching'+ , let chg = M.findWithDefault nullmixedamt a changes, changeMatches chg+ , Just (RunningBalance bal _) <- [M.lookup a balances'] ]+ | otherwise = MatchedRows [ (a, chg, nullmixedamt) | (a, chg) <- M.toAscList changes, changeMatches chg ]++ -- Is this checkpoint skipped, because a skipped date is among the dates it examines ?+ -- A rule with balance: and no change: terms examines the period's last day (where the balance is tested);+ -- any other rule examines the whole period.+ isSkipped sp+ | null skips = False+ | hasbalanceq && not haschangeq = maybe False (\e -> any (`spanContainsDate` addDays (-1) e) skips) $ spanEnd sp+ | otherwise = any (spansOverlap sp) skips+ spansOverlap a b = case (spanStart i, spanEnd i) of+ (Just s, Just e) -> s < e+ _ -> True+ where i = a `spanIntersect` b++ case checkPeriods maxMatchesShown M.empty S.empty ps checkpoints of+ [] -> Right ()+ failures -> Left $ assertFailureMessage ad rowq (length $ filter (not . isSkipped) checkpoints) failures++-- | The change: and balance: terms of a row query (see 'querySplitRowTerms'), each with whether it is negated.+signedRowTerms :: Query -> [(Bool, Query)]+signedRowTerms (And qs) = concatMap signedRowTerms qs+signedRowTerms (Not q) = [(not neg, t) | (neg, t) <- signedRowTerms q]+signedRowTerms q = [(False, q) | queryIsRowTerm q]++-- | The first line(s) of an assert directive error: file position and excerpt.+errorPrefix :: AssertDirective -> String+errorPrefix AssertDirective{adSourcePos=SourcePos f l _, adSourceText=txt} =+ printf "%s:%d:\n%s\n" f (unPos l) (decorateExcerpt (unPos l) Nothing $ txt <> "\n")++-- | Explain an assert directive's failure, given its row query, its number of checkpoints, and the+-- failing checkpoints with what matched there: where it failed, which rows (changes, balances, or both)+-- or postings matched, up to a limit, or that none did, and the equivalent report command+-- (a balance report for rows, a register for postings), covering all the failing checkpoints.+assertFailureMessage :: AssertDirective -> Query -> Int -> [Failure] -> String+assertFailureMessage ad@AssertDirective{adQuantifier=quant, adPeriod=mperiod, adPeriodText=periodtxt, adQueryText=querytxt}+ rowq ncheckpoints failures =+ errorPrefix ad <> T.unpack (T.unlines $ explanation <> [reportline])+ where+ maxperiodsshown = 5+ hasrowterms = not $ queryIsNull rowq+ periodic = ncheckpoints > 1+ nfailed = length failures++ -- What the matches are called, and the matches as table rows, from all failing checkpoints.+ -- Rows get a period column when there are several checkpoints (postings have their date).+ noun | hasrowterms = rowsnoun+ | otherwise = "postings"+ (rowsnoun, amountcells) = case (queryHasChange rowq, queryHasBalance rowq) of+ (True, False) -> ("changes", \chg _ -> [showamt chg])+ (False, _) -> ("balances", \_ bal -> [showamt bal])+ (True, True) -> ("accounts", \chg bal -> [showamt chg, showamt bal])+ showamt = T.pack . showMixedAmountOneLine+ tablerows = flip concatMap failures $ \(Failure sp _ ev) -> case ev of+ MatchedRows rows -> [(if periodic then periodLabel sp else "") : a : amountcells chg bal | (a, chg, bal) <- rows]+ MatchedPostings ps -> [ [showDate $ postingDate p, fitText Nothing (Just 30) True True desc, paccount p, showamt $ pamount p]+ | p <- ps, let desc = maybe "" tdescription $ ptransaction p ]+ matchlines = alignColumns (if hasrowterms then [False, False, True, True] else [False, False, False, True]) tablerows+ nhidden = sum [n | Failure _ n _ <- failures] - length matchlines++ explanation = case quant of+ AssertNone ->+ ("This assert directive failed " <> wherefailed <> ".")+ : ("These " <> noun <> " matched" <> (if noun == "accounts" then " (change, balance)" else "") <> ":")+ : map (" " <>) matchlines+ <> [" ...and " <> T.pack (show nhidden) <> " more." | nhidden > 0]+ AssertSome+ | periodic -> ["This assert directive failed " <> wherefailed <> ".",+ "No " <> noun <> " matched in " <> (if nfailed == 1 then "that period." else "those periods.")]+ | otherwise -> ["This assert directive failed " <> wherefailed <> ": no " <> noun <> " matched."]+ reportline = (if nhidden > 0 then "To see them all: " else "To see the report: ") <> reportcmd++ -- Where it failed: over the whole journal (or the date: terms' span), in its one period, or in some of its periods.+ wherefailed = case (mperiod, failures) of+ (Nothing, [Failure (DateSpan Nothing Nothing) _ _]) -> "(checked over the whole journal)"+ (Nothing, [Failure sp _ _]) -> "(checked over the period " <> showDateSpan sp <> ")"+ (_, [Failure sp _ _]) | not periodic -> if isOneDay sp then "on " <> periodLabel sp else "for the period " <> periodLabel sp+ _ -> "in " <> T.pack (show nfailed) <> " of " <> T.pack (show ncheckpoints) <> " periods: "+ <> T.intercalate ", " (map failureLabel $ take maxperiodsshown failures)+ <> (if nfailed > maxperiodsshown then " and " <> T.pack (show $ nfailed - maxperiodsshown) <> " more" else "")++ -- The report command, covering the failing checkpoints: from the start of the first to the end of the last.+ -- It has -I, since reading the journal would otherwise fail on this rule again.+ -- For a balance report covering several periods, it has the period expression's report interval+ -- (from its text; -b and -e override its dates), and leaves out the change:/balance: terms,+ -- since in a multi-period report those test each row's total, not each period.+ reportcmd = T.unwords $ ["hledger"] <> cmd <> periodflags <> map shellQuote queryterms+ -- With balance: terms, -H makes bal show the balances which were tested, not the period's changes.+ cmd | hasrowterms = ["bal", "-I", "-E"] <> ["-H" | queryHasBalance rowq]+ | otherwise = ["reg", "-I"]+ multiperiod = hasrowterms && nfailed > 1+ periodflags = case mperiod of+ Nothing -> []+ Just _ -> ["-p " <> shellQuote periodtxt | multiperiod]+ <> dateflag "-b" (spanStart . failureSpan =<< headMay failures)+ <> dateflag "-e" (spanEnd . failureSpan =<< lastMay failures)+ queryterms = filter (\t -> not (T.null t) && not (multiperiod && isRowTermText t)) $ words'' queryprefixes querytxt+ isRowTermText t = any (`T.isPrefixOf` stripNots t) ["change:", "balance:"]+ stripNots t = maybe t stripNots $ T.stripPrefix "not:" t+ dateflag flag = maybe [] (\d -> [flag, showDate d])+ failureSpan (Failure sp _ _) = sp+ failureLabel = periodLabel . failureSpan++-- | The most matches an assert rule's error message shows.+maxMatchesShown :: Int+maxMatchesShown = 10++-- | How a checkpoint is shown in an error message: as a date if it's one day, otherwise as a period.+periodLabel :: DateSpan -> Text+periodLabel sp+ | isOneDay sp = maybe "" showDate $ spanStart sp+ | otherwise = showDateSpan sp++isOneDay :: DateSpan -> Bool+isOneDay sp = case (spanStart sp, spanEnd sp) of+ (Just s, Just e) -> addDays 1 s == e+ _ -> False++-- | Lay out a table as lines of text, with two spaces between columns,+-- each column left- or right-aligned (if its flag is true) to its widest cell.+-- Columns which are empty in every row are left out.+alignColumns :: [Bool] -> [[Text]] -> [Text]+alignColumns rightaligns rows = map T.stripEnd $ map (T.intercalate " ") $ transpose+ [map (pad right $ foldl' max 0 $ map realLength col) col | (right, col) <- zip rightaligns $ transpose rows, any (not . T.null) col]+ where pad right w = fitText (Just w) Nothing False (not right)++-- | Quote a query term for a shell command line, if needed.+shellQuote :: Text -> Text+shellQuote t+ | not (T.null t) && T.all safe t = t+ | otherwise = "'" <> T.replace "'" "'\\''" t <> "'"+ where safe c = isAlphaNum c || c `elem` (":._-/+=@,%" :: String)
+ Hledger/Data/JournalChecks/Ordereddates.hs view
@@ -0,0 +1,65 @@+module Hledger.Data.JournalChecks.Ordereddates (+ journalCheckOrdereddates+)+where++import Control.Monad (forM)+import Data.List (groupBy)+import Data.Maybe (isJust)+import Text.Printf (printf)+import Data.Text qualified as T (pack, unlines)++import Hledger.Data.Errors (makeTransactionErrorExcerpt)+import Hledger.Data.Posting (generatedTransactionTagName)+import Hledger.Data.Transaction (transactionFile)+import Hledger.Data.Types+import Hledger.Utils (textChomp)++journalCheckOrdereddates :: Journal -> Either String ()+journalCheckOrdereddates j = do+ let+ -- we check date ordering within each file, not across files+ -- note, relying on txns always being sorted by file here+ -- forecast transactions are ignored; they are generated, not written in the file,+ -- and are appended after the others, ordered by rule rather than by date+ txnsbyfile = groupBy (\t1 t2 -> transactionFile t1 == transactionFile t2) $ filter (not . isForecast) $ jtxns j+ isForecast = isJust . lookup generatedTransactionTagName . ttags+ compare' a b = tdate a <= tdate b+ (const $ Right ()) =<< (forM txnsbyfile $ \ts ->+ case checkTransactions compare' ts of+ FoldAcc{fa_previous=Nothing} -> Right ()+ FoldAcc{fa_error=Nothing} -> Right ()+ FoldAcc{fa_error=Just t, fa_previous=Just tprev} -> Left $ printf+ ("%s:%d:\n%s\nOrdered dates checking is enabled, and this transaction's\n"+ ++ "date (%s) is out of order with the previous transaction.\n"+ ++ "Consider moving this entry into date order, or adjusting its date.")+ f l ex (show $ tdate t)+ where+ (_,_,_,ex1) = makeTransactionErrorExcerpt tprev (const Nothing)+ (f,l,_,ex2) = makeTransactionErrorExcerpt t finderrcols+ -- separate the two excerpts by an empty line, which flycheck-hledger accepts between excerpts+ ex = T.unlines [textChomp ex1, T.pack "", textChomp ex2]+ finderrcols _t = Just (1, Just 10)+ )++data FoldAcc a b = FoldAcc+ { fa_error :: Maybe a+ , fa_previous :: Maybe b+ }++checkTransactions :: (Transaction -> Transaction -> Bool)+ -> [Transaction] -> FoldAcc Transaction Transaction+checkTransactions compare' = foldWhile f FoldAcc{fa_error=Nothing, fa_previous=Nothing}+ where+ f current acc@FoldAcc{fa_previous=Nothing} = acc{fa_previous=Just current}+ f current acc@FoldAcc{fa_previous=Just previous} =+ if compare' previous current+ then acc{fa_previous=Just current}+ else acc{fa_error=Just current}++foldWhile :: (a -> FoldAcc a b -> FoldAcc a b) -> FoldAcc a b -> [a] -> FoldAcc a b+foldWhile _ acc [] = acc+foldWhile fold acc (a:as) =+ case fold a acc of+ acc'@FoldAcc{fa_error=Just _} -> acc'+ acc' -> foldWhile fold acc' as
+ Hledger/Data/JournalChecks/Uniqueleafnames.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.JournalChecks.Uniqueleafnames (+ journalCheckUniqueleafnames+)+where++import Data.Function (on)+import Data.List (groupBy, sortBy)+import Data.Text (Text)+import Data.Text qualified as T+import Safe (headErr)+import Text.Printf (printf)++import Hledger.Data.AccountName (accountLeafName)+import Hledger.Data.Errors (makePostingErrorExcerpt)+import Hledger.Data.Journal (journalPostings, journalAccountNamesUsed)+import Hledger.Data.Posting (isVirtual)+import Hledger.Data.Types+import Hledger.Utils (chomp, textChomp)++-- | Check that all the journal's postings are to accounts with a unique leaf name.+-- Otherwise, return an error message for the first offending posting.+journalCheckUniqueleafnames :: Journal -> Either String ()+journalCheckUniqueleafnames j = do+ -- find all duplicate leafnames, and the full account names they appear in+ case finddupes $ journalLeafAndFullAccountNames j of+ [] -> Right ()+ -- pick the first duplicated leafname and show the transactions of+ -- the first two postings using it, highlighting the second as the error.+ (leaf,fulls):_ ->+ case filter ((`elem` fulls).paccount) $ journalPostings j of+ ps@(p:p2:_) -> Left $ chomp $ printf+ ("%s:%d:\n%s\nChecking for unique account leaf names is enabled, and\n"+ ++"account leaf name %s is not unique.\n"+ ++"It appears in these account names, which are used in %d places:\n%s"+ ++"\nConsider changing these account names so their last parts are different."+ )+ f l ex (show leaf) (length ps) accts+ where+ -- t = fromMaybe nulltransaction ptransaction -- XXX sloppy+ (_,_,_,ex1) = makePostingErrorExcerpt p (\_ _ _ -> Nothing)+ (f,l,_,ex2) = makePostingErrorExcerpt p2 finderrcols+ -- separate the two excerpts by an empty line, which flycheck-hledger accepts between excerpts+ ex = T.unlines [textChomp ex1, T.pack "", textChomp ex2]+ finderrcols p' _ _ = Just (col, Just col2)+ where+ a = paccount p'+ alen = T.length a+ llen = T.length $ accountLeafName a+ col = 5 + (if isVirtual p' then 1 else 0) + alen - llen+ col2 = col + llen - 1+ accts = T.unlines fulls++ _ -> Right () -- shouldn't happen++finddupes :: (Ord leaf, Eq full) => [(leaf, full)] -> [(leaf, [full])]+finddupes leafandfullnames = zip dupLeafs dupAccountNames+ where+ dupAccountNames = map (map snd) dupes+ dupLeafs = case dupes of+ [] -> []+ _ -> map (fst . headErr) dupes -- PARTIAL headErr succeeds because of pattern+ dupes = fnddupes leafandfullnames+ where+ fnddupes = filter ((> 1) . length)+ . groupBy ((==) `on` fst)+ . sortBy (compare `on` fst)++journalLeafAndFullAccountNames :: Journal -> [(Text, AccountName)]+journalLeafAndFullAccountNames = map leafAndAccountName . journalAccountNamesUsed+ where leafAndAccountName a = (accountLeafName a, a)
+ Hledger/Data/Json.hs view
@@ -0,0 +1,346 @@+{-+JSON instances. Should they be in Types.hs ?+-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}++module Hledger.Data.Json (+ -- * Instances+ -- * Utilities+ toJsonText+ ,writeJsonFile+ ,readJsonFile+) where++import Data.Aeson+import Data.Aeson.Encode.Pretty (Config(..), Indent(..), NumberFormat(..),+ encodePretty', encodePrettyToTextBuilder')+--import Data.Aeson.TH+import Data.ByteString.Lazy qualified as BL+import Data.Decimal (DecimalRaw(..), roundTo)+import Data.Maybe (fromMaybe)+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Map qualified as M+import Text.Megaparsec (Pos, SourcePos, mkPos, unPos)++import Hledger.Data.Types+import Hledger.Utils.IO (error')+import Hledger.Data.Amount (amountsRaw, mixed)++-- To JSON++instance ToJSON Status+instance ToJSON SourcePos++-- Use the same encoding as the underlying Int+instance ToJSON Pos where+ toJSON = toJSON . unPos+ toEncoding = toEncoding . unPos++-- https://github.com/hledgerorg/hledger/issues/1195++-- The default JSON output for Decimal can contain 255-digit integers+-- (for repeating decimals caused by implicit transaction prices).+-- JSON output is intended to be consumed by diverse apps and+-- programming languages, which can't handle numbers like that.+-- From #1195:+--+-- > - JavaScript uses 64-bit IEEE754 numbers which can only accurately+-- > represent integers up to 9007199254740991 (i.e. a maximum of 15 digits).+-- > - Java’s largest integers are limited to 18 digits.+-- > - Python 3 integers are unbounded.+-- > - Python 2 integers are limited to 18 digits like Java.+-- > - C and C++ number limits depend on platform — most platforms should+-- > be able to represent unsigned integers up to 64 bits, i.e. 19 digits.+--+-- What is the best compromise for both accuracy and practicality ?+-- For now, we provide both the maximum precision representation+-- (decimalPlaces & decimalMantissa), and a floating point representation+-- with up to 10 decimal places (and an unbounded number of integer digits).+-- We hope the mere presence of the large number in JSON won't break things,+-- and that the overall number of significant digits in the floating point+-- remains manageable in practice. (I'm not sure how to limit the number+-- of significant digits in a Decimal right now.)+instance (Integral a, ToJSON a) => ToJSON (DecimalRaw a) where+ toJSON = object . decimalKV+ toEncoding = pairs . mconcat . decimalKV++decimalKV :: (+#if MIN_VERSION_aeson(2,2,0)+ KeyValue e kv,+#else+ KeyValue kv,+#endif+ Integral a, ToJSON a) => DecimalRaw a -> [kv]+decimalKV d = let d' = if decimalPlaces d <= 10 then d else roundTo 10 d in+ [ "decimalPlaces" .= decimalPlaces d'+ , "decimalMantissa" .= decimalMantissa d'+ , "floatingPoint" .= (realToFrac d' :: Double)+ ]++instance ToJSON CostBasis+instance ToJSON Amount+instance ToJSON Rounding+instance ToJSON AmountStyle++-- Use the same JSON serialisation as Maybe Word8+instance ToJSON AmountPrecision where+ toJSON = toJSON . \case+ Precision n -> Just n+ NaturalPrecision -> Nothing+ toEncoding = toEncoding . \case+ Precision n -> Just n+ NaturalPrecision -> Nothing++instance ToJSON Side+instance ToJSON DigitGroupStyle++instance ToJSON MixedAmount where+ toJSON = toJSON . amountsRaw+ toEncoding = toEncoding . amountsRaw++instance ToJSON BalanceAssertion+instance ToJSON AmountCost+instance ToJSON MarketPrice+instance ToJSON PostingRealness++instance ToJSON Posting where+ toJSON = object . postingKV+ toEncoding = pairs . mconcat . postingKV++postingKV ::+#if MIN_VERSION_aeson(2,2,0)+ KeyValue e kv+#else+ KeyValue kv+#endif+ => Posting -> [kv]+postingKV Posting{..} =+ [ "pdate" .= pdate+ , "pdate2" .= pdate2+ , "pstatus" .= pstatus+ , "paccount" .= paccount+ , "pamount" .= pamount+ , "pcomment" .= pcomment+ , "preal" .= preal+ , "ptags" .= ptags+ , "pbalanceassertion" .= pbalanceassertion+ -- To avoid a cycle, show just the parent transaction's index number+ -- in a dummy field. When re-parsed, there will be no parent.+ , "ptransaction_" .= maybe "" (show.tindex) ptransaction+ -- This is probably not wanted in json, we discard it.+ , "poriginal" .= (Nothing :: Maybe Posting)+ ]++instance ToJSON Transaction+instance ToJSON TransactionModifier+instance ToJSON TMPostingRule+instance ToJSON PeriodicTransaction+instance ToJSON PriceDirective+instance ToJSON EFDay+instance ToJSON DateSpan+instance ToJSON Interval+instance ToJSON Period+instance ToJSON AccountAlias+instance ToJSON AccountType+instance ToJSONKey AccountType+instance ToJSON AccountDeclarationInfo+instance ToJSON PayeeDeclarationInfo+instance ToJSON TagDeclarationInfo+instance ToJSON Commodity+instance ToJSON TimeclockCode+instance ToJSON TimeclockEntry++-- Journal's jparse* fields are transient parser state, not journal data,+-- so we omit them from the JSON.+instance ToJSON JournalFile+instance ToJSON Journal where+ toJSON = object . journalKV+ toEncoding = pairs . mconcat . journalKV++journalKV ::+#if MIN_VERSION_aeson(2,2,0)+ KeyValue e kv+#else+ KeyValue kv+#endif+ => Journal -> [kv]+journalKV j =+ [ "jdeclaredpayees" .= jdeclaredpayees j+ , "jdeclaredtags" .= jdeclaredtags j+ , "jdeclaredaccounts" .= jdeclaredaccounts j+ , "jdeclaredaccounttags" .= jdeclaredaccounttags j+ , "jdeclaredaccounttypes" .= jdeclaredaccounttypes j+ , "jaccounttypes" .= jaccounttypes j+ , "jdeclaredcommodities" .= jdeclaredcommodities j+ , "jdeclaredcommoditytags" .= jdeclaredcommoditytags j+ , "jinferredcommoditystyles" .= jinferredcommoditystyles j+ , "jglobalcommoditystyles" .= jglobalcommoditystyles j+ , "jpricedirectives" .= jpricedirectives j+ , "jinferredmarketprices" .= jinferredmarketprices j+ , "jtxnmodifiers" .= jtxnmodifiers j+ , "jperiodictxns" .= jperiodictxns j+ , "jtxns" .= jtxns j+ , "jfiles" .= jfiles j+ , "jlastreadtime" .= jlastreadtime j+ ]++instance ToJSON BalanceData+instance ToJSON a => ToJSON (PeriodData a) where+ toJSON a = object+ [ "pdpre" .= pdpre a+ , "pdperiods" .= (M.toList $ pdperiods a)+ ]++instance ToJSON a => ToJSON (Account a) where+ toJSON = object . accountKV+ toEncoding = pairs . mconcat . accountKV++accountKV ::+#if MIN_VERSION_aeson(2,2,0)+ (KeyValue e kv, ToJSON a)+#else+ (KeyValue kv, ToJSON a)+#endif+ => Account a -> [kv]+accountKV a =+ [ "aname" .= aname a+ , "adeclarationinfo" .= adeclarationinfo a+ -- To avoid a cycle, show just the parent account's name+ -- in a dummy field. When re-parsed, there will be no parent.+ , "aparent_" .= maybe "" aname (aparent a)+ -- Just the names of subaccounts, as a dummy field, ignored when parsed.+ , "asubs_" .= map aname (asubs a)+ -- The actual subaccounts (and their subs..), making a (probably highly redundant) tree+ -- ,"asubs" .= asubs a+ -- Omit the actual subaccounts+ , "asubs" .= ([]::[Account BalanceData])+ , "aboring" .= aboring a+ , "adata" .= adata a+ ]++instance ToJSON Ledger++-- From JSON++instance FromJSON Status+instance FromJSON SourcePos+-- Use the same encoding as the underlying Int+instance FromJSON Pos where+ parseJSON = fmap mkPos . parseJSON++instance FromJSON CostBasis+instance FromJSON Amount+instance FromJSON Rounding+instance FromJSON AmountStyle++-- Use the same JSON serialisation as Maybe Word8+instance FromJSON AmountPrecision where+ parseJSON = fmap (maybe NaturalPrecision Precision) . parseJSON++instance FromJSON Side+instance FromJSON DigitGroupStyle++instance FromJSON MixedAmount where+ parseJSON = fmap (mixed :: [Amount] -> MixedAmount) . parseJSON++instance FromJSON BalanceAssertion+instance FromJSON AmountCost+instance FromJSON MarketPrice+instance FromJSON PostingRealness+instance FromJSON Posting+instance FromJSON Transaction+instance FromJSON AccountDeclarationInfo++instance FromJSON BalanceData+instance FromJSON a => FromJSON (PeriodData a) where+ parseJSON = withObject "PeriodData" $ \v -> PeriodData+ <$> v .: "pdpre"+ <*> (M.fromList <$> v .: "pdperiods")++-- XXX The ToJSON instance replaces subaccounts with just names.+-- Here we should try to make use of those to reconstruct the+-- parent-child relationships.+instance FromJSON a => FromJSON (Account a)++-- Decimal, various attempts+--+-- https://stackoverflow.com/questions/40331851/haskell-data-decimal-as-aeson-type+----instance FromJSON Decimal where parseJSON =+---- A.withScientific "Decimal" (return . right . eitherFromRational . toRational)+--+-- https://github.com/bos/aeson/issues/474+-- http://hackage.haskell.org/package/aeson-1.4.2.0/docs/Data-Aeson-TH.html+-- $(deriveFromJSON defaultOptions ''Decimal) -- doesn't work+-- $(deriveFromJSON defaultOptions ''DecimalRaw) -- works; requires TH, but gives better parse error messages+--+-- https://github.com/PaulJohnson/Haskell-Decimal/issues/6+instance FromJSON (DecimalRaw Integer)+--+-- @simonmichael, I think the code in your first comment should work if it compiles—though “work” doesn’t mean you can parse a JSON number directly into a `Decimal` using the generic instance, as you’ve discovered.+--+--Error messages with these extensions are always rather cryptic, but I’d prefer them to Template Haskell. Typically you’ll want to start by getting a generic `ToJSON` instance working, then use that to figure out what the `FromJSON` instance expects to parse: for a correct instance, `encode` and `decode` should give you an isomorphism between your type and a subset of `Bytestring` (up to the `Maybe` wrapper that `decode` returns).+--+--I don’t have time to test it right now, but I think it will also work without `DeriveAnyClass`, just using `DeriveGeneric` and `StandAloneDeriving`. It should also work to use the [`genericParseJSON`](http://hackage.haskell.org/package/aeson/docs/Data-Aeson.html#v:genericParseJSON) function to implement the class explicitly, something like this:+--+--{-# LANGUAGE DeriveGeneric #-}+--{-# LANGUAGE StandAloneDeriving #-}+--import GHC.Generics+--import Data.Aeson+--deriving instance Generic Decimal+--instance FromJSON Decimal where+-- parseJSON = genericParseJSON defaultOptions+--+--And of course you can avoid `StandAloneDeriving` entirely if you’re willing to wrap `Decimal` in your own `newtype`.++-- XXX these will allow reading a Journal, but currently the+-- jdeclaredaccounttypes Map gets serialised as a JSON list, which+-- can't be read back.+--+-- instance FromJSON AccountAlias+-- instance FromJSONKey AccountType where fromJSONKey = genericFromJSONKey defaultJSONKeyOptions+-- instance FromJSON AccountType+-- instance FromJSON ClockTime+-- instance FromJSON Commodity+-- instance FromJSON DateSpan+-- instance FromJSON Interval+-- instance FromJSON Period+-- instance FromJSON PeriodicTransaction+-- instance FromJSON PriceDirective+-- instance FromJSON TimeclockCode+-- instance FromJSON TimeclockEntry+-- instance FromJSON TransactionModifier+-- instance FromJSON Journal+++-- Utilities++-- | Config for pretty printing JSON output.+jsonConf :: Config+jsonConf = Config{confIndent=Spaces 2, confCompare=compare, confNumFormat=Generic, confTrailingNewline=True}++-- | Show a JSON-convertible haskell value as pretty-printed JSON text.+toJsonText :: ToJSON a => a -> TL.Text+toJsonText = TB.toLazyText . encodePrettyToTextBuilder' jsonConf++-- | Write a JSON-convertible haskell value to a pretty-printed JSON file.+-- Eg: writeJsonFile "a.json" nulltransaction+writeJsonFile :: ToJSON a => FilePath -> a -> IO ()+writeJsonFile f = BL.writeFile f . encodePretty' jsonConf++-- | Read a JSON file and decode it to the target type, or raise an error if we can't.+-- Eg: readJsonFile "a.json" :: IO Transaction+readJsonFile :: FromJSON a => FilePath -> IO a+readJsonFile f = do+ bl <- BL.readFile f+ -- PARTIAL:+ let v = fromMaybe (error' $ "could not decode JSON in "++show f++" to target value")+ (decode bl :: Maybe Value)+ case fromJSON v :: FromJSON a => Result a of+ Error e -> error' e+ Success t -> return t
Hledger/Data/Ledger.hs view
@@ -7,141 +7,106 @@ -} -module Hledger.Data.Ledger+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.Ledger (+ nullledger+ ,ledgerFromJournal+ ,ledgerAccountNames+ ,ledgerAccount+ ,ledgerRootAccount+ ,ledgerTopAccounts+ ,ledgerLeafAccounts+ ,ledgerPostings+ ,ledgerDateSpan+ ,ledgerCommodities+ ,tests_Ledger+) where-import Data.Map (Map, findWithDefault, fromList)-import Data.Tree-import Test.HUnit++import Data.Map qualified as M+import Safe (headDef) import Text.Printf -import Hledger.Utils+import Test.Tasty (testGroup)+import Test.Tasty.HUnit ((@?=), testCase) import Hledger.Data.Types-import Hledger.Data.Account (nullacct)-import Hledger.Data.AccountName+import Hledger.Data.Account+import Hledger.Data.Dates (nulldate) import Hledger.Data.Journal-import Hledger.Data.Posting-import Hledger.Data.Matching+import Hledger.Query instance Show Ledger where- show l = printf "Ledger with %d transactions, %d accounts\n%s"- (length (jtxns $ journal l) +- length (jmodifiertxns $ journal l) +- length (jperiodictxns $ journal l))- (length $ accountnames l)- (showtree $ accountnametree l)+ show l = printf "Ledger with %d transactions, %d accounts\n" --"%s"+ (length (jtxns $ ljournal l) ++ length (jtxnmodifiers $ ljournal l) ++ length (jperiodictxns $ ljournal l))+ (length $ ledgerAccountNames l)+ -- (showtree $ ledgerAccountNameTree l) nullledger :: Ledger-nullledger = Ledger{- journal = nulljournal,- accountnametree = nullaccountnametree,- accountmap = fromList []- }---- | Filter a journal's transactions as specified, and then process them--- to derive a ledger containing all balances, the chart of accounts,--- canonicalised commodities etc.-journalToLedger :: FilterSpec -> Journal -> Ledger-journalToLedger fs j = nullledger{journal=j',accountnametree=t,accountmap=m}- where j' = filterJournalPostings fs{depth=Nothing} j- (t, m) = journalAccountInfo j'+nullledger = Ledger {+ ljournal = nulljournal,+ laccounts = []+ } --- | Filter a journal's transactions as specified, and then process them--- to derive a ledger containing all balances, the chart of accounts,--- canonicalised commodities etc.--- Like journalToLedger but uses the new matchers.-journalToLedger2 :: Matcher -> Journal -> Ledger-journalToLedger2 m j = nullledger{journal=j',accountnametree=t,accountmap=amap}- where j' = filterJournalPostings2 m j- (t, amap) = journalAccountInfo j'+-- | Filter a journal's transactions with the given query, then build+-- a "Ledger", containing the journal plus the tree of all its+-- accounts with their subaccount-inclusive and subaccount-exclusive+-- balances. If the query includes a depth limit, the ledger's journal+-- will be depth limited, but the ledger's account tree will not.+ledgerFromJournal :: Query -> Journal -> Ledger+ledgerFromJournal q j = nullledger{ljournal=j'', laccounts=as}+ where+ (q',depthq) = (filterQuery (not . queryIsDepth) q, filterQuery queryIsDepth q)+ j' = filterJournalAmounts (filterQuery queryIsCur q) $ -- remove amount parts which the query's cur: terms would exclude+ filterJournalPostings q' j+ -- Ledger does not use date-separated balances, so dates are left empty+ as = accountsFromPostings (const $ Just nulldate) $ journalPostings j'+ j'' = filterJournalPostings depthq j' -- | List a ledger's account names. ledgerAccountNames :: Ledger -> [AccountName]-ledgerAccountNames = drop 1 . flatten . accountnametree+ledgerAccountNames = drop 1 . map aname . laccounts -- | Get the named account from a ledger.-ledgerAccount :: Ledger -> AccountName -> Account-ledgerAccount l a = findWithDefault nullacct a $ accountmap l---- | List a ledger's accounts, in tree order-ledgerAccounts :: Ledger -> [Account]-ledgerAccounts = drop 1 . flatten . ledgerAccountTree 9999---- | List a ledger's top-level accounts, in tree order-ledgerTopAccounts :: Ledger -> [Account]-ledgerTopAccounts = map root . branches . ledgerAccountTree 9999+ledgerAccount :: Ledger -> AccountName -> Maybe (Account BalanceData)+ledgerAccount l a = lookupAccount a $ laccounts l --- | List a ledger's bottom-level (subaccount-less) accounts, in tree order-ledgerLeafAccounts :: Ledger -> [Account]-ledgerLeafAccounts = leaves . ledgerAccountTree 9999+-- | Get this ledger's root account, which is a dummy "root" account+-- above all others. This should always be first in the account list,+-- if somehow not this returns a null account.+ledgerRootAccount :: Ledger -> Account BalanceData+ledgerRootAccount = headDef nullacct . laccounts --- | Accounts in ledger whose name matches the pattern, in tree order.-ledgerAccountsMatching :: [String] -> Ledger -> [Account]-ledgerAccountsMatching pats = filter (matchpats pats . aname) . accounts+-- | List a ledger's top-level accounts (the ones below the root), in tree order.+ledgerTopAccounts :: Ledger -> [Account BalanceData]+ledgerTopAccounts = asubs . headDef nullacct . laccounts --- | List a ledger account's immediate subaccounts-ledgerSubAccounts :: Ledger -> Account -> [Account]-ledgerSubAccounts l Account{aname=a} = - map (ledgerAccount l) $ filter (`isSubAccountNameOf` a) $ accountnames l+-- | List a ledger's bottom-level (subaccount-less) accounts, in tree order.+ledgerLeafAccounts :: Ledger -> [Account BalanceData]+ledgerLeafAccounts = filter (null.asubs) . laccounts -- | List a ledger's postings, in the order parsed. ledgerPostings :: Ledger -> [Posting]-ledgerPostings = journalPostings . journal---- | Get a ledger's tree of accounts to the specified depth.-ledgerAccountTree :: Int -> Ledger -> Tree Account-ledgerAccountTree depth l = treemap (ledgerAccount l) $ treeprune depth $ accountnametree l---- | Get a ledger's tree of accounts rooted at the specified account.-ledgerAccountTreeAt :: Ledger -> Account -> Maybe (Tree Account)-ledgerAccountTreeAt l acct = subtreeat acct $ ledgerAccountTree 9999 l+ledgerPostings = journalPostings . ljournal -- | The (fully specified) date span containing all the ledger's (filtered) transactions, -- or DateSpan Nothing Nothing if there are none. ledgerDateSpan :: Ledger -> DateSpan-ledgerDateSpan = postingsDateSpan . ledgerPostings---- | Convenience aliases.-accountnames :: Ledger -> [AccountName]-accountnames = ledgerAccountNames--account :: Ledger -> AccountName -> Account-account = ledgerAccount--accounts :: Ledger -> [Account]-accounts = ledgerAccounts--topaccounts :: Ledger -> [Account]-topaccounts = ledgerTopAccounts--accountsmatching :: [String] -> Ledger -> [Account]-accountsmatching = ledgerAccountsMatching--subaccounts :: Ledger -> Account -> [Account]-subaccounts = ledgerSubAccounts--postings :: Ledger -> [Posting]-postings = ledgerPostings--commodities :: Ledger -> Map String Commodity-commodities = journalCanonicalCommodities . journal--accounttree :: Int -> Ledger -> Tree Account-accounttree = ledgerAccountTree--accounttreeat :: Ledger -> Account -> Maybe (Tree Account)-accounttreeat = ledgerAccountTreeAt---- datespan :: Ledger -> DateSpan--- datespan = ledgerDateSpan--rawdatespan :: Ledger -> DateSpan-rawdatespan = journalDateSpan . journal+ledgerDateSpan = journalDateSpanBothDates . ljournal -ledgeramounts :: Ledger -> [MixedAmount]-ledgeramounts = journalAmounts . journal+-- | All commodities used in this ledger.+ledgerCommodities :: Ledger -> [CommoditySymbol]+ledgerCommodities = M.keys . jinferredcommoditystyles . ljournal -tests_Hledger_Data_Ledger = TestList- [- ]+-- tests +tests_Ledger =+ testGroup "Ledger" [+ testCase "ledgerFromJournal" $ do+ length (ledgerPostings $ ledgerFromJournal Any nulljournal) @?= 0+ length (ledgerPostings $ ledgerFromJournal Any samplejournal) @?= 13+ length (ledgerPostings $ ledgerFromJournal (Depth 2) samplejournal) @?= 7+ ]
+ Hledger/Data/Lots.hs view
@@ -0,0 +1,3086 @@+{-|+Lot tracking for investment accounting.++This module implements two pipeline stages (see doc\/SPEC-finalising.md):++1. Classification ('journalClassifyLotPostings'): identifies lot postings+ and tags them as acquire, dispose, transfer-from, or transfer-to.++2. Calculation ('journalCalculateLots'): walks transactions in date order,+ accumulating a map from commodities to their lots, and:++ - For acquire postings: generates lot names from cost basis and appends+ them to the account name as subaccounts.++ - For dispose postings: selects an existing lot subaccount matched by+ the posting's lot selector, using the configured reduction method+ (FIFO by default, configurable per account\/commodity via @lots:@ tag).+ If needed and if the lot selector permits it, selects multiple lots,+ splitting the posting into one per lot.+ Dispose postings with a transacted price (selling price) generate gain postings.+ Bare disposes without a price (e.g. fee deductions) get lot subaccounts but no gain.++ - For transfer postings: selects lots from the source account (like+ dispose) and recreates them under the destination account. The lot's+ cost basis is preserved through the transfer.+ Multi-lot transfers are supported (eg via @{}@ to transfer all lots).++For background, see doc\/SPEC-lots.md and doc\/PLAN-lots.md.++== Errors++User-visible errors from this module. See also Hledger.Data.Errors and doc/ERRORS.md.++journalCalculateLots:++* validateUserLabels:+ "lot id is not unique: commodity X, date D, label L"++* processAcquirePosting:+ "acquire posting has no cost basis",+ "...has multiple cost basis amounts",+ "X is lotful but this acquire posting has no cost basis or price",+ "...has no lot cost",+ "duplicate lot id: {...} for commodity X"++* processDisposePosting:+ "dispose posting has no cost basis",+ "...has no transacted price (selling price)" / "(buying price, to cover the short)",+ "...has non-negative quantity" / "non-positive quantity (a short position is covered by a positive posting)",+ "SPECID requires a lot selector",+ "lot ... has no cost basis (internal error)",+ "lot subaccount ... does not match resolved lot"++* groupIndexedTransferPostings:+ "transfer-to/from posting ... has no matching ... posting",+ "Mismatched transfer quantities for lot-tracked commodity X",+ "... posting has no lotful commodity"++* processTransferGroup:+ "transfer-from posting has no cost basis",+ "...has multiple cost basis amounts",+ "lot transfers should have no transacted price",+ "transfer-from posting has non-negative quantity",+ "transfer-to posting has no single positive X amount",+ "could not distribute transferred lots exactly (internal error)",+ "lot ... has no cost basis (internal error)",+ "lot cost basis ... does not match transfer-to cost basis"++* selectLots:+ "SPECID requires an explicit lot selector",+ "no X lots available for transfer/disposal from account Y on DATE"+ (with a hint to use a liability account for a short position),+ and on any lot error, a hint naming a later same-date entry which adds+ the commodity to an empty source account (see laterSupplyHint),+ "no lots matching {...} for commodity X in account Y on DATE",+ "lot selector is ambiguous, matches N lots in account Y",+ "Insufficient lots for commodity X in account Y"++* validateGlobalCompliance:+ "METHOD: lot(s) on other account(s) have higher priority than the lots in ACCT"++* poolWeightedAvgCost:+ "no lots with cost basis available for averaging",+ "cannot average lots with different cost commodities",+ "cannot average lots with zero total quantity"++* foldMPostings (via isUnclassifiedLotfulPosting):+ "X is declared lotful ... but this posting was not classified"+ (exempt: zero-amount lotful postings; in a liability account, notes that+ short lots can't be transferred yet)++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Data.Lots (+ journalHasLotFeatures,+ transactionHasLotfulAmounts,+ journalClassifyLotPostings,+ journalStripBalancerCopiedBases,+ transactionAutoSplitFeeOutflows,+ journalCalculateLots,+ journalCheckAcquireBasis,+ journalCheckLotsMethodCoherence,+ journalAveragePoolTotals,+ journalAveragePoolCosts,+ journalCollapseLotDetail,+ journalTagGainPostings,+ transactionTagGainPostings,+ journalAddOrCheckGainPostings,+ isDisposePosting,+ isGainPosting,+ isSetAsideGainPosting,+ lotBaseAccount,+ lotDirectionOf,+ journalLotDirection,+ lotSubaccountName,+ mergeCostBasis,+ parseLotName,+ resolveReductionMethodForAccount,+ showLotName,+) where++import Control.Applicative ((<|>))+import Data.Bifunctor (first)+import Control.Monad (foldM, guard, unless, when)+import Data.List (dropWhileEnd, intercalate, partition, sort, sortOn)+import Data.Ord (Down(..))+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map.Strict qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Char (isDigit)+import Data.Decimal (decimalPlaces, roundTo)+import Data.Time.Calendar (Day, fromGregorianValid)+import Text.Printf (printf)++import Hledger.Data.AccountName (accountNameType, parentAccountNames)+import Hledger.Data.AccountType (LotDirection(..), accountTypeLotDirection, isAssetType, isEquityType, isLiabilityType, lotDirectionSign)+import Hledger.Data.Amount (AmountFormat(..), mixed, maPlus, mixedAmountStripCosts, amountRoundedQuantity, amountSetPrecisionMin, amountSetQuantity, amountsRaw, divideAmountAndUpdatePrecision, isNegativeAmount, maNegate, maSum, mapMixedAmount, mixedAmount, mixedAmountCost, mixedAmountIsZero, mixedAmountLooksZero, multiplyQuantities, nullmixedamt, noCostFmt, oneLineNoCostFmt, showAmountWith, showAmountsDistinctly, showMixedAmountOneLine, showMixedAmountsDistinctly)+import Hledger.Data.Errors (makeAccountTagErrorExcerpt, makeCommodityTagErrorExcerpt, makePostingErrorExcerptByIndex, makeTransactionErrorExcerpt, transactionFindPostingIndex)+import Hledger.Data.Journal (journalAccountLotsTags, journalAccountType, journalAccountUsesNoLots, journalBaseGainAccount, journalCommodityLotsMethod, journalCommodityStylesWith, journalCommodityUsesLots, journalInheritedAccountTags, journalLotfulCommodities, journalMapPostings, journalMapTransactions, journalPostings, journalTieTransactions, parseReductionMethod)+import Hledger.Data.Posting (costPostingTagName, generatedPostingTagName, hasAmount, isReal, isVirtual, lotParentAssertionTagName, lotsplitPostingTagName, nullposting, originalPosting, postingAddHiddenAndMaybeVisibleTag, postingRemoveHiddenAndVisibleTag, postingDate, postingHasTag, postingStripCosts, feesplitPostingTagName)+import Hledger.Data.Transaction (transactionCommodityStyles, txnTieKnot)+import Hledger.Data.Types+import Hledger.Utils (dbg5, dbg5With)++-- Types++-- | Map from commodity to (map from lot id to (map from account name to lot balance)).+-- Keyed by commodity at the top level so lots of different commodities don't clash.+-- The inner Map LotId is ordered by date then label, supporting FIFO/LIFO naturally.+-- The innermost Map AccountName allows the same lot to exist at multiple accounts+-- (eg after a partial lot transfer).+type LotState = M.Map CommoditySymbol (M.Map LotId (M.Map AccountName Amount))++-- | Resolve which reduction method to use for a posting, and where it came from.+-- Checks account-inherited tags first, then commodity tags, defaulting to FIFO.+-- Since commodity tags are propagated to ptags, we distinguish by checking the+-- commodity's own declared tags separately.+resolveReductionMethodWithSource :: Journal -> Posting -> CommoditySymbol -> (ReductionMethod, String)+resolveReductionMethodWithSource j p = resolveReductionMethodForAccount j (paccount p)++-- | Resolve which reduction method is in effect for an account and commodity,+-- and where it came from: the account's (inherited) lots: tag if any,+-- else the commodity's lots: tag value if any, else FIFO.+resolveReductionMethodForAccount :: Journal -> AccountName -> CommoditySymbol -> (ReductionMethod, String)+resolveReductionMethodForAccount j acct commodity =+ case accountLotsMethod of+ Just m -> (m, "from account tag on " ++ T.unpack acct)+ Nothing -> case journalCommodityLotsMethod j commodity of+ Just m -> (m, "from commodity tag on " ++ T.unpack commodity)+ Nothing -> (FIFO, "default")+ where+ -- Check account-inherited tags only (excluding commodity-propagated tags).+ accountLotsMethod =+ let acctTags = journalInheritedAccountTags j acct+ in case [v | (k, v) <- acctTags, T.toLower k == "lots"] of+ (v:_) -> parseReductionMethod v+ [] -> Nothing++-- | Check that global (*ALL) reduction methods are used coherently:+-- when any account holding a lot-tracked commodity resolves to a global+-- method, every account holding that commodity must resolve to the same+-- method. Mixing a global method with any other is rejected, because the+-- global validation (and, for AVERAGEALL, the global pool updates) only+-- make sense when every account participates. Local methods (FIFO, LIFO,+-- HIFO, SPECID, AVERAGE) may be mixed per account freely.+journalCheckLotsMethodCoherence :: Journal -> Either String Journal+journalCheckLotsMethodCoherence j = do+ mapM_ checkCommodity (M.toList holdings)+ Right j+ where+ -- The base accounts holding each lot-tracked commodity (postings with+ -- a cost basis annotation, or a lotful commodity in an account that+ -- hasn't opted out of lot tracking with lots: NONE), grouped by lot+ -- direction: long lots (asset accounts) and short lots (liability+ -- accounts) are separate pools, which may use different methods.+ holdings :: M.Map (CommoditySymbol, LotDirection) (S.Set AccountName)+ holdings = M.fromListWith S.union+ [ ((acommodity a, journalLotDirectionOrLong j acct), S.singleton acct)+ | p <- journalPostings j+ , let acct = lotBaseAccount (paccount p)+ , a <- amountsRaw (pamount p)+ , isJust (acostbasis a)+ || (journalCommodityUsesLots j (acommodity a) && not (journalAccountUsesNoLots j acct)) ]++ resolutions c accts = [ (acct, m, src)+ | acct <- S.toList accts+ , let (m, src) = resolveReductionMethodForAccount j acct c ]++ checkCommodity ((c, _), accts) =+ case [r | r@(_, m, _) <- rs, methodIsGlobal m] of+ [] -> Right ()+ (gacct, gmethod, gsrc):_ ->+ case [r | r@(_, m, _) <- rs, m /= gmethod] of+ [] -> Right ()+ conflicts -> Left $ errmsg c gacct gmethod gsrc conflicts+ where rs = resolutions c accts++ errmsg c gacct gmethod gsrc conflicts =+ maybe "" (\(f, l, _, ex) -> printf "%s:%d:\n%s\n" f l ex) (methodDecl gacct c)+ ++ T.unpack c ++ " uses the global method " ++ show gmethod ++ " (" ++ gsrc ++ ")"+ ++ " in " ++ T.unpack gacct ++ ",\nbut a different method elsewhere:\n"+ ++ unlines [" " ++ T.unpack acct ++ " uses " ++ show m ++ " (" ++ src ++ ")" | (acct, m, src) <- conflicts]+ ++ "A global (*ALL) method must be used by every account holding the commodity.\n"+ ++ "Declare it once on the commodity declaration, and remove conflicting account lots: tags."++ -- The declaration providing an account's method for a commodity,+ -- rendered as an error excerpt: the nearest self-or-ancestor account+ -- declaration with a method-valued lots: tag, else the commodity's+ -- declaration. Mirrors resolveReductionMethodForAccount's precedence.+ methodDecl :: AccountName -> CommoditySymbol -> Maybe (FilePath, Int, Maybe (Int, Maybe Int), Text)+ methodDecl acct c =+ case [ (a', adi) | a' <- acct : parentAccountNames acct+ , Just adi <- [lookup a' (jdeclaredaccounts j)]+ , any isMethodTag (aditags adi) ] of+ ((a', adi):_) -> Just $ makeAccountTagErrorExcerpt (a', adi) "lots"+ [] -> (`makeCommodityTagErrorExcerpt` "lots") <$> M.lookup c (jdeclaredcommodities j)+ where isMethodTag (k, v) = T.toLower k == "lots" && isJust (parseReductionMethod v)++-- | The units and total cost basis of each AVERAGE or AVERAGEALL lot pool,+-- from the journal's lot postings dated before the given date (if any),+-- keyed by base account and commodity. Dividing gives the pool's running+-- average cost: acquisitions carry their acquisition cost and disposals+-- and transfers the then-current average, so the quantity-weighted sum+-- works out to the pool's average. An AVERAGE pool is one account's lots;+-- an AVERAGEALL pool is the lots in all accounts with the same lot+-- direction (long lots in asset accounts, or short lots in liability+-- accounts). Pools with no units, or with cost bases in several+-- commodities, are omitted.+-- The lot subaccount names of AVERAGE lots leave out the cost (it changes+-- as the pool is re-averaged), so this is how reports and generated+-- entries (holdings, close) find it.+journalAveragePoolTotals :: Journal -> Maybe Day -> M.Map (AccountName, CommoditySymbol) (Quantity, Amount)+journalAveragePoolTotals j mend = M.fromList+ [ ((base, c), (units, ub1{aquantity = sum [aquantity a * aquantity ub | (a, ub) <- entries]}))+ | (base, c) <- S.toList $ S.fromList [ (lotBaseAccount sub, acommodity a) | (sub, a) <- lotamts ]+ , let method = fst $ resolveReductionMethodForAccount j base c+ , methodIsAverage method+ , let inPool sub+ | methodIsGlobal method = journalLotDirectionOrLong j (lotBaseAccount sub) == journalLotDirectionOrLong j base+ | otherwise = lotBaseAccount sub == base+ entries = [ (a, ub) | (sub, a) <- lotamts, acommodity a == c, inPool sub+ , Just ub <- [cbCost =<< acostbasis a] ]+ , (ub1:_) <- [map snd entries]+ , all ((== acommodity ub1) . acommodity . snd) entries+ , let units = sum [aquantity a | (a, _) <- entries]+ , units /= 0+ ]+ where+ -- the amounts posted to lot subaccounts before the end date+ lotamts = [ (paccount p, a)+ | p <- journalPostings j+ , isJust $ lotSubaccountName $ paccount p+ , maybe True (postingDate p <) mend+ , a <- amountsRaw $ pamount p ]++-- | The average cost of each AVERAGE or AVERAGEALL lot pool, as of (just+-- before) the given date, keyed by base account and commodity. Exact,+-- displayed with at most 8 decimal places. See 'journalAveragePoolTotals'.+journalAveragePoolCosts :: Journal -> Maybe Day -> M.Map (AccountName, CommoditySymbol) Amount+journalAveragePoolCosts j mend =+ M.map (\(units, cost) -> divideAmountAndUpdatePrecision units cost) (journalAveragePoolTotals j mend)++-- | If the account name's final colon-separated component is enclosed in @{@+-- and @}@, treat it as a lot subaccount and return @Just (base, "{...}")@.+-- Otherwise return @Nothing@.+-- Full validation of the lot name (parts, dates, costs) is left to 'parseLotName';+-- this function only identifies candidates so they can be validated uniformly.+splitLotSubaccount :: AccountName -> Maybe (AccountName, Text)+splitLotSubaccount a = do+ -- check this first: it's cheap, and rules out almost all account names. (breakOnEnd reverses the text.)+ guard $ "}" `T.isSuffixOf` a+ let (prefix, leaf) = T.breakOnEnd ":" a+ guard $ not (T.null prefix)+ guard $ "{" `T.isPrefixOf` leaf+ Just (T.dropEnd 1 prefix, leaf)++-- | Strip any trailing lot subaccount (a final @:{...}@ component) from an+-- account name. E.g., @\"assets:broker:{2026-01-15, $50}\"@ becomes+-- @\"assets:broker\"@.+lotBaseAccount :: AccountName -> AccountName+lotBaseAccount a = maybe a fst (splitLotSubaccount a)++-- | The lot direction of an account (or of a lot subaccount's base account):+-- Long for asset accounts, Short for liability accounts (which hold short+-- positions), none for other account types. See 'LotDirection'.+lotDirectionOf :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe LotDirection+lotDirectionOf lookupAccountType acct =+ lookupAccountType (lotBaseAccount acct) >>= accountTypeLotDirection++-- | The lot direction of an account in this journal. See 'lotDirectionOf'.+journalLotDirection :: Journal -> AccountName -> Maybe LotDirection+journalLotDirection j = lotDirectionOf (journalAccountType j)++-- | The lot direction of an account in this journal, treating accounts+-- of other types (which can hold lots only when written with explicit+-- cost basis annotations, eg equity:opening) as Long.+journalLotDirectionOrLong :: Journal -> AccountName -> LotDirection+journalLotDirectionOrLong j = fromMaybe Long . journalLotDirection j++-- | Does this amount open or receive a lot (an inflow) in an account with+-- this direction ? Positive in a Long account, negative in a Short one.+isLotInflow :: LotDirection -> Amount -> Bool+isLotInflow dir a = aquantity a * lotDirectionSign dir > 0++-- | Does this amount close or send a lot (an outflow) in an account with+-- this direction ? Negative in a Long account, positive in a Short one.+isLotOutflow :: LotDirection -> Amount -> Bool+isLotOutflow dir a = aquantity a * lotDirectionSign dir < 0++-- | Render a lot name in the consolidated hledger format for use as a subaccount name.+-- Format: @{YYYY-MM-DD, COST}@ or @{YYYY-MM-DD, \"LABEL\", COST}@.+-- The cost amount is rendered using its own intrinsic style. Callers that want+-- the journal's canonical commodity styles applied (eg when building a lot+-- subaccount name) should pre-style the 'CostBasis' with 'styleLotCbCost'.+showLotName :: CostBasis -> T.Text+showLotName CostBasis{cbDate, cbLabel, cbCost} =+ "{" <> T.intercalate ", " parts <> "}"+ where+ parts = catMaybes+ [ fmap (T.pack . show) cbDate+ , fmap (\l -> "\"" <> l <> "\"") cbLabel+ -- Show a zero cost with its commodity symbol (eg $0), not as a bare 0:+ -- the name is the lot's basis of record, and must round-trip faithfully.+ , fmap (T.pack . showAmountWith noCostFmt{displayZeroCommodity=True}) cbCost+ ]++-- | Apply the journal's canonical commodity styles to a 'CostBasis's cost+-- amount, for consistent rendering of the amount inside a lot subaccount name.+-- Styles should have been computed with 'NoRounding' (preserving the original+-- decimal digits); all other style fields — decimal mark, digit group separators,+-- commodity position and spacing — come from the canonical style.+styleLotCbCost :: M.Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis+styleLotCbCost styles cb = cb{cbCost = styleAmounts styles <$> cbCost cb}++-- | Widen a 'CostBasis's cost amount's display precision to at least the+-- commodity style's declared precision (if any), so eg with @commodity €1.00@+-- an inferred per-unit cost of 2.5 renders as @2.50@. For user-written+-- explicit costs, prefer 'styleLotCbCost' alone (no widening).+widenLotCbCost :: M.Map CommoditySymbol AmountStyle -> CostBasis -> CostBasis+widenLotCbCost styles cb = cb{cbCost = widen <$> cbCost cb}+ where+ widen a = case M.lookup (acommodity a) styles of+ Just AmountStyle{asprecision = Precision p} -> amountSetPrecisionMin p a+ _ -> a++-- | Render a lot subaccount name, dropping the cost component under AVERAGE/AVERAGEALL.+-- AVERAGE pools share a single running per-unit cost that changes on every+-- acquisition; embedding it in the subaccount name would make the subaccount+-- unstable across acquisitions. The running cost remains on each lot's+-- @acostbasis@ for use by reports and @print --lots@.+showLotNameForMethod :: ReductionMethod -> CostBasis -> T.Text+showLotNameForMethod method cb+ | methodIsAverage method = showLotName cb{cbCost = Nothing}+ | otherwise = showLotName cb++-- | Like 'mergeCostBasis', but under AVERAGE/AVERAGEALL the cost field is+-- ignored: the pool's running cost legitimately differs from what the user+-- wrote on any specific acquire posting.+mergeCostBasisForMethod :: ReductionMethod -> CostBasis -> CostBasis -> Either String CostBasis+mergeCostBasisForMethod method a b+ | methodIsAverage method = mergeCostBasis a{cbCost = Nothing} b{cbCost = Nothing}+ | otherwise = mergeCostBasis a b++-- | Extract the lot subaccount name (the @{...}@ component) from an account name,+-- or @Nothing@ if there is none.+-- E.g., @\"assets:broker:{2026-01-15, $50}\"@ returns @Just \"{2026-01-15, $50}\"@.+lotSubaccountName :: AccountName -> Maybe Text+lotSubaccountName = fmap snd . splitLotSubaccount++-- | Parse a lot name (as produced by 'showLotName') back into a 'CostBasis'.+-- The input should be the full @{...}@ string including braces.+-- Parts are comma-separated and all optional: date (@YYYY-MM-DD@),+-- label (@\"LABEL\"@), and cost (parsed by the supplied callback).+-- The callback avoids an import cycle (Lots.hs cannot import Read-layer parsers).+parseLotName :: (String -> Maybe Amount) -> Text -> Either String CostBasis+parseLotName parseAmt t = do+ inner <- case T.stripPrefix "{" t >>= T.stripSuffix "}" of+ Just s -> Right (T.strip s)+ Nothing -> Left $ "lot name must be enclosed in braces: " ++ T.unpack t+ if T.null inner+ then Right $ CostBasis Nothing Nothing Nothing+ else do+ let parts = map T.strip $ splitParts inner+ parseParts parts+ where+ parseParts parts = go parts Nothing Nothing Nothing+ where+ go [] d l c = Right $ CostBasis d l c+ go (p:ps) d l c+ | isDatePart p = case parseDate p of+ Just day -> go ps (Just day) l c+ Nothing -> Left $ "invalid date in lot name: " ++ T.unpack p+ | isLabelPart p = go ps d (Just (T.drop 1 (T.dropEnd 1 p))) c+ | otherwise = case parseAmt (T.unpack p) of+ Just amt -> go ps d l (Just amt)+ Nothing -> Left $ fromMaybe ("invalid lot name: " ++ T.unpack p)+ (missingDateCommaHint p <|> wrongOrderHint p)++ -- If the cost part starts with a date, or is followed by a comma and+ -- something date- or label-like, the parts are out of order+ -- (eg @{$10, "note"}@ or @{"note", 2026-01-15, $10}@).+ wrongOrderHint :: Text -> Maybe String+ wrongOrderHint p+ | isDatePart (T.take 10 p)+ || any startsAnotherPart (map (T.stripStart . T.drop 1) $ filter ("," `T.isPrefixOf`) $ T.tails p)+ = Just $ "lot name parts must be in this order (if present): {DATE, \"LABEL\", COST}: " ++ T.unpack t+ | otherwise = Nothing+ where startsAnotherPart s = "\"" `T.isPrefixOf` s || isDatePart (T.take 10 s)++ -- If a part starts with what looks like a date but no comma followed,+ -- the user probably forgot the comma (eg @{2026-01-15 $10}@). Show a+ -- corrected form to make the fix obvious.+ missingDateCommaHint :: Text -> Maybe String+ missingDateCommaHint p+ | T.length p > 10+ , let (candidate, rest) = T.splitAt 10 p+ , isDatePart candidate+ , let rest' = T.stripStart rest+ , not (T.null rest')+ , T.head rest' /= ','+ = Just $ "Missing comma in lot name: " ++ T.unpack p+ ++ "\nDid you mean: " ++ T.unpack candidate ++ ", " ++ T.unpack rest' ++ " ?"+ | otherwise = Nothing++ isDatePart p = T.length p == 10 && T.all (\c -> isDigit c || c == '-') p+ isLabelPart p = "\"" `T.isPrefixOf` p && "\"" `T.isSuffixOf` p && T.length p >= 2++ parseDate p = do+ let s = T.unpack p+ case s of+ [y1,y2,y3,y4,'-',m1,m2,'-',d1,d2] ->+ fromGregorianValid+ (read [y1,y2,y3,y4])+ (read [m1,m2])+ (read [d1,d2])+ _ -> Nothing++ -- Split the inner text of a lot name into up to 3 parts (date, label, cost)+ -- by peeling known-format prefixes in DLC order, exploiting the fact that+ -- dates and labels have unambiguous syntax. This avoids splitting on commas,+ -- which would break when the cost amount contains a decimal comma (e.g. @1,5@)+ -- or when the commodity symbol contains commas (e.g. @"an, odd, commodity"@).+ -- After each part, @,@ followed by optional whitespace is consumed.+ --+ -- Examples:+ -- @"2026-01-15, \"my, label\", €1,50"@ -> @["2026-01-15", "\"my, label\"", "€1,50"]@+ -- @"2026-01-15, \"an, odd, commodity\" 1,5"@ -> @["2026-01-15", "\"an, odd, commodity\" 1,5"]@+ -- @"2026-01-15, \"a, b\", \"an, odd, commodity\" 1,5" -> @["2026-01-15", "\"a, b\"", "\"an, odd, commodity\" 1,5"]@+ -- @"$100"@ -> @["$100"]@+ splitParts :: Text -> [Text]+ splitParts s =+ let (mdate, s1) = peelDate s+ (mlabel, s2) = peelLabel s1+ mcost = let c = T.strip s2 in if T.null c then Nothing else Just c+ in catMaybes [mdate, mlabel, mcost]++ -- Try to peel a date (YYYY-MM-DD) from the front. Returns the date text+ -- and the remainder after stripping a comma separator, or Nothing and the+ -- unchanged input. Requires that the date candidate is followed by end of+ -- string or a comma with optional surrounding whitespace (to keep the + -- syntax regular; gives a helpful error if the comma is missing).+ peelDate :: Text -> (Maybe Text, Text)+ peelDate s+ | T.length s >= 10+ , let (candidate, rest) = T.splitAt 10 s+ , isDatePart candidate+ , properBoundary rest+ = (Just candidate, stripSep rest)+ | otherwise = (Nothing, s)+ where+ properBoundary txt = case T.uncons (T.stripStart txt) of+ Nothing -> True+ Just (',', _) -> True+ _ -> False++ -- Try to peel a double-quoted label from the front. Scans from the opening+ -- quote to the next closing quote. A quoted string is only treated as a+ -- label if it is followed by a comma separator or end of input. If it is+ -- followed by digits or other amount-starting characters (after optional+ -- whitespace), it is a quoted commodity symbol that belongs to the cost+ -- amount, so we leave it alone.+ peelLabel :: Text -> (Maybe Text, Text)+ peelLabel s+ | Just s' <- T.stripPrefix "\"" s+ = let (inner, rest) = T.break (== '"') s'+ in case T.uncons rest of+ Just ('"', rest')+ | looksLikeCostRemainder rest' -> (Nothing, s) -- quoted commodity symbol, not a label+ | otherwise -> (Just ("\"" <> inner <> "\""), stripSep rest')+ _ -> (Nothing, s) -- malformed, leave for parseAmt+ | otherwise = (Nothing, s)++ -- After a closing quote, does the remainder look like it continues as a+ -- cost amount (i.e. the quoted string was a commodity symbol, not a label)?+ -- True when the next non-space character is a digit, sign, or decimal mark.+ looksLikeCostRemainder :: Text -> Bool+ looksLikeCostRemainder t' =+ case T.uncons (T.stripStart t') of+ Just (c, _) -> isDigit c || c == '+' || c == '-' || c == '.'+ Nothing -> False++ -- Strip an optional comma and any surrounding whitespace.+ stripSep :: Text -> Text+ stripSep s0 =+ let s1 = T.stripStart s0+ in case T.uncons s1 of+ Just (',', s2) -> T.stripStart s2+ _ -> s1++-- | Do two lot cost amounts refer to the same cost, for lot identification ?+-- True if their commodities match and their quantities are equal exactly,+-- or one equals the other's display-rounded value, or one equals the other+-- rounded to its own number of decimal places. The latter two let a+-- displayed lot name (eg an inferred $10/3 cost rendered as $3.33333333),+-- or a coarser written cost (eg $3.33), be written back in a journal and+-- still identify the lot, while stored lot costs keep full precision for+-- exact gain arithmetic (#2689). This is the same agreement rule as+-- 'journalCheckAcquireBasis' applies between a written basis and the+-- transacted cost.+lotCostsMatch :: Amount -> Amount -> Bool+lotCostsMatch x y =+ acommodity x == acommodity y &&+ (aquantity x == aquantity y+ || aquantity x == amountRoundedQuantity y+ || amountRoundedQuantity x == aquantity y+ || aquantity x == roundTo (places x) (aquantity y)+ || roundTo (places y) (aquantity x) == aquantity y)+ where places = decimalPlaces . aquantity -- as written, trailing zeros included++-- | Merge two 'CostBasis' values. For each field, if both are @Just@, they+-- must agree (returns error if not); otherwise takes whichever is @Just@.+-- The first argument is typically the account-name basis (more complete),+-- the second is the amount's existing basis.+mergeCostBasis :: CostBasis -> CostBasis -> Either String CostBasis+mergeCostBasis a b = do+ d <- mergeField "date" show (cbDate a) (cbDate b)+ l <- mergeField "label" T.unpack (cbLabel a) (cbLabel b)+ c <- mergeCostField (cbCost a) (cbCost b)+ Right $ CostBasis d l c+ where+ mergeField :: Eq a => String -> (a -> String) -> Maybe a -> Maybe a -> Either String (Maybe a)+ mergeField _ _ Nothing y = Right y+ mergeField _ _ x Nothing = Right x+ mergeField name showVal (Just x) (Just y)+ | x == y = Right (Just x)+ | otherwise = Left $ "conflicting cost basis " ++ name+ ++ ": account name has " ++ showVal x+ ++ " but amount has " ++ showVal y++ mergeCostField :: Maybe Amount -> Maybe Amount -> Either String (Maybe Amount)+ mergeCostField Nothing y = Right y+ mergeCostField x Nothing = Right x+ mergeCostField (Just x) (Just y)+ | lotCostsMatch x y = Right (Just x)+ | otherwise = Left $ "conflicting cost basis cost"+ ++ ": account name has " ++ showAmountWith noCostFmt x+ ++ " but amount has " ++ showAmountWith noCostFmt y++-- | Does this journal use lots at all ? True if any commodity is declared+-- lotful, any account declaration has a lots: tag, or any posting (in+-- transactions, periodic transaction rules or auto posting rules) has a cost+-- basis annotation or a lot subaccount name. When false, the lot-related+-- finalisation stages would all be no-ops, so journalFinalise skips them.+journalHasLotFeatures :: Journal -> Bool+journalHasLotFeatures j =+ not (S.null $ journalLotfulCommodities j)+ || not (M.null $ journalAccountLotsTags j)+ || any postingHasLotFeature allpostings+ where+ allpostings =+ journalPostings j+ ++ concatMap ptpostings (jperiodictxns j)+ ++ [tmprPosting r | tm <- jtxnmodifiers j, r <- tmpostingrules tm]+ postingHasLotFeature p =+ any (isJust . acostbasis) (amountsRaw $ pamount p)+ || isJust (lotSubaccountName $ paccount p)++-- Classification (pipeline stage 1)++-- | Classify lot-related postings by adding ptype tags.+-- Must be called after journalAddAccountTypes so account types are available,+-- and after transaction balancing, so that all posting amounts (including+-- ones inferred from elided amounts or balance assignments) are known:+-- classification then gives the same result for every entry shape as if all+-- amounts had been written explicitly (#2686, #2690, #2692).+-- The verbosetags parameter controls whether the ptype tags will be made visible in comments.+-- Before classification, try to auto-split lot transfers with fees+-- into a transfer portion and a dispose portion, so both get classified correctly.+journalClassifyLotPostings :: Bool -> Journal -> Journal+journalClassifyLotPostings verbosetags j = journalMapTransactions classify j+ where+ classify t+ | not $ transactionHasLotfulAmounts lotfulcomms t = t -- nothing lot-related here: leave it, and its knot, alone+ | otherwise =+ txnTieKnot -- retie the postings' transaction pointers (nothing else does after this)+ . transactionClassifyLotPostings verbosetags lookupType commodityIsLotful accountUsesNoLots+ . transactionAutoSplitFeeOutflows verbosetags lookupType commodityIsLotful accountUsesNoLots+ $ t+ lookupType = journalAccountType j+ lotfulcomms = journalLotfulCommodities j+ commodityIsLotful = (`S.member` lotfulcomms)+ accountUsesNoLots = journalAccountUsesNoLots j++-- | Could this transaction involve lots ? True if any of its amounts has a+-- cost basis annotation or is in one of the given lotful commodities.+-- A cheap test, broader than any of the lot stages' own triggers, so they+-- can skip the (usually many) transactions for which it is false.+transactionHasLotfulAmounts :: S.Set CommoditySymbol -> Transaction -> Bool+transactionHasLotfulAmounts lotfulcomms = any (any lotful . amountsRaw . pamount) . tpostings+ where lotful a = isJust (acostbasis a) || acommodity a `S.member` lotfulcomms++-- | Detect a lot transfer with a fee - an unpriced negative lotful asset+-- posting (bare in a lotful commodity, or carrying a cost basis annotation)+-- whose absolute quantity exceeds the positive quantities received by+-- asset accounts, where the excess matches a non-asset posting (typically a+-- fee paid in the lotful commodity) - and split it into a transfer portion+-- (matching the positive sum) and a dispose portion, so classification can+-- correctly tag the two roles. When the fee counterpart has a transacted+-- price, the dispose portion carries it (and a gain will be calculated);+-- otherwise the dispose portion is priceless (lots are still reduced, but+-- no gain is calculated).+--+-- If no such pattern is found, the transaction is returned unchanged.+-- The transfer portion inherits the original's identity (poriginal preserves+-- the unsplit quantity, so plain print shows the user's original entry).+-- The dispose portion is tagged `_feesplit-posting` so plain print hides it,+-- and `_generated-posting` to mark its provenance; -x or --verbose-tags+-- reveals it.+-- The dispose portion(s) come first, then the transfer portion, which keeps+-- the original posting's balance assertion, so it is still checked after+-- the full original quantity has been posted.+transactionAutoSplitFeeOutflows ::+ Bool+ -> (AccountName -> Maybe AccountType)+ -> (CommoditySymbol -> Bool)+ -> (AccountName -> Bool)+ -> Transaction -> Transaction+transactionAutoSplitFeeOutflows verbosetags lookupAccountType commodityIsLotful accountUsesNoLots t =+ t{tpostings = concatMap (\p -> fromMaybe [p] (trySplit p)) (tpostings t)}+ where+ ps = tpostings t+ isAsset acct = maybe False isAssetType (lookupAccountType (lotBaseAccount acct))+ -- A fee counterpart is in an account holding no lots (not a liability+ -- account either: those hold short lots).+ isNonAsset acct = isNothing (lotDirectionOf lookupAccountType acct)+ -- An account with a lots: NONE tag doesn't participate in lot tracking,+ -- unless the posting carries explicit cost basis annotations.+ optedOut p = accountUsesNoLots (lotBaseAccount (paccount p))+ && not (any (isJust . acostbasis) (amountsRaw (pamount p)))++ -- Try to split posting p into a transfer portion and dispose portion(s).+ -- Requires: a single unpriced negative asset amount, either bare in a+ -- lotful commodity or carrying a cost basis annotation, with matching+ -- non-asset counterpart(s). Positive postings naturally exclude p itself.+ -- Fee fragments from an earlier split (during balancing) are left alone.+ trySplit p = do+ guard $ not (postingHasTag feesplitPostingTagName p)+ guard $ isAsset (paccount p)+ guard $ not (optedOut p)+ [a] <- Just $ amountsRaw (pamount p)+ guard $ aquantity a < 0+ && (commodityIsLotful (acommodity a) || isJust (acostbasis a))+ && isNothing (acost a)+ let comm = acommodity a+ fromQty = negate (aquantity a)+ toQty = sum [ aquantity pa+ | q <- ps+ , isAsset (paccount q)+ , not (optedOut q)+ , pa <- amountsRaw (pamount q)+ , acommodity pa == comm+ , aquantity pa > 0+ , isNothing (acost pa)+ ]+ feeQty = fromQty - toQty+ guard $ toQty > 0 && feeQty > 0+ feeAmts <- findFeeCounterparts comm feeQty+ let origP = originalPosting p+ -- The fee portions come first, then the transfer portion, which+ -- keeps any balance assertion (checked after the full original+ -- quantity has been posted). This order also shows, and re-reads,+ -- the lot processing order (fee disposals before the transfer).+ p1 = p{ pamount = mixedAmount (amountSetQuantity (negate toQty) a)+ , poriginal = Just origP }+ mkFeePart fa+ = addTag feesplitPostingTagName+ $ addTag generatedPostingTagName+ $ p{ pamount = mixedAmount (amountSetQuantity (negate (aquantity fa)) a){ acost = acost fa }+ , poriginal = Just origP+ , pbalanceassertion = Nothing }+ Just (map mkFeePart feeAmts ++ [p1])++ addTag name = postingAddHiddenAndMaybeVisibleTag False verbosetags (name, "")++ -- Find non-lot-account counterpart posting amounts accounting for the given+ -- fee quantity in the given commodity: the first single amount equal to+ -- it, or otherwise all of the positive amounts, if they sum to it exactly.+ findFeeCounterparts comm qty+ | (fa:_) <- [fa | fa <- candidates, aquantity fa == qty] = Just [fa]+ | not (null candidates) && sum (map aquantity candidates) == qty = Just candidates+ | otherwise = Nothing+ where+ candidates =+ [ pa+ | q <- ps, isNonAsset (paccount q)+ , pa <- amountsRaw (pamount q)+ , acommodity pa == comm, aquantity pa > 0+ ]++-- | Classify lot-related postings by adding a ptype tag.+-- For each posting with a cost basis (any account type):+-- - determine if it's of type "acquire" or "dispose" (based on amount sign)+-- - or "transfer-from" or "transfer-to" (if counterposting with same commodity exists in a different account).+-- For asset postings without cost basis:+-- - a lotful posting can be classified as "transfer-to" (see shouldClassifyLotful)+-- - a bare positive posting can be classified as "transfer-to" if there's a+-- matching transfer-from counterpart (see shouldClassifyBareTransferTo).+-- The lookupAccountType function should typically be `journalAccountType journal`.+-- The commodityIsLotful function should typically be `journalCommodityUsesLots journal`.+-- The verbosetags parameter controls whether the tags are made visible in comments.+--+-- For more detail on classification rules, please see doc/SPEC-lots.md > Lot postings.+--+transactionClassifyLotPostings :: Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction+transactionClassifyLotPostings verbosetags lookupAccountType commodityIsLotful accountUsesNoLots t@Transaction{tpostings=ps}+ | not (any hasLotRelevantAmount ps)+ = lotDbg t "no lot-relevant amounts, skipping" t+ | otherwise = lotDbg t "classifying" $ t{tpostings=zipWith classifyAt [0..] ps}+ where+ hasCostBasis :: Posting -> Bool+ hasCostBasis p = let amts = amountsRaw (pamount p)+ result = any (isJust . acostbasis) amts+ in dbg5 ("classifyLotPostings: hasCostBasis " ++ show (paccount p) ++ " amts=" ++ show (length amts)) result++ -- An account with a lots: NONE tag doesn't participate in lot tracking:+ -- its postings are not classified and are invisible to counterpart+ -- detection - unless they carry explicit cost basis annotations+ -- (the more specific declaration wins).+ optedOut :: Posting -> Bool+ optedOut p = accountUsesNoLots (lotBaseAccount (paccount p)) && not (hasCostBasis p)++ -- Is this posting in a Short (liability) account, holding short lots ?+ -- Short lots take no part in transfer detection (transferring them is+ -- not supported yet): such postings are never transfer counterparts,+ -- and are classified only as acquire or dispose (see shouldClassifyShort).+ isShortPosting :: Posting -> Bool+ isShortPosting p = lotDirectionOf lookupAccountType (paccount p) == Just Short++ hasLotRelevantAmount :: Posting -> Bool+ hasLotRelevantAmount p = isReal p && not (hasBalancerCopiedBasis p) && not (optedOut p)+ && (hasCostBasis p || hasNegativeLotfulAmount p || hasPositiveLotfulAmount p)++ hasNegativeLotfulAmount :: Posting -> Bool+ hasNegativeLotfulAmount p =+ let amts = amountsRaw (pamount p)+ in not (any (isJust . acostbasis) amts)+ && any isNegativeAmount amts+ && amountsAreLotful amts++ hasPositiveLotfulAmount :: Posting -> Bool+ hasPositiveLotfulAmount p =+ let amts = amountsRaw (pamount p)+ in not (any (isJust . acostbasis) amts)+ && not (any isNegativeAmount amts)+ && any (\a -> aquantity a > 0) amts -- has a strictly positive amount (not zero or amountless)+ && amountsAreLotful amts++ -- Same-account transfer pairs: within each account, match positive and negative+ -- unpriced postings with the same commodity and absolute quantity as transfer pairs.+ -- When there are more of one sign than the other, the excess are left unmatched+ -- (and will be classified normally as acquire/dispose).+ -- Priced postings are excluded (a priced posting is a deliberate trade,+ -- eg a stock split's dispose/re-acquire postings; and lot transfers may+ -- not have a transacted price, so pairing one would only force an error).+ sameAcctTransferSet :: S.Set Int+ sameAcctTransferSet = S.fromList $ concatMap matchPairs $ M.elems grouped+ where+ grouped :: M.Map (AccountName, CommoditySymbol, Quantity) ([Int], [Int])+ grouped = foldl' addPosting M.empty (zip [0..] ps)+ addPosting m (i, p)+ | not (isReal p) = m+ | not (hasLotRelevantAmount p) = m+ | isShortPosting p = m+ | otherwise = foldl' (addAmt i (lotBaseAccount (paccount p))) m (amountsRaw (pamount p))+ addAmt i acct m a+ | isJust (acost a) = m+ | q < 0 = M.insertWith mergePair (acct, acommodity a, negate q) ([i], []) m+ | q > 0 = M.insertWith mergePair (acct, acommodity a, q) ([], [i]) m+ | otherwise = m+ where q = aquantity a+ mergePair (n1, p1) (n2, p2) = (n1++n2, p1++p2)+ matchPairs (negs, poss) =+ let n = min (length negs) (length poss)+ in take n negs ++ take n poss++ -- Could this balancer-copied-basis posting (see 'hasBalancerCopiedBasis')+ -- serve as the elided destination or source of a lot transfer? True for+ -- a nonzero, unpriced amount in a lot-tracking asset account. Such+ -- postings are otherwise invisible to classification, since they may be+ -- the artifact of a disposal missing its selling price (positive mirror)+ -- or an acquisition missing its cost (negative mirror); but those+ -- readings would fail anyway (no price / no lot cost), so preferring the+ -- transfer reading only makes otherwise-erroring entries work.+ -- (A forgotten-price disposal is thus read as a lot transfer to the+ -- elided account, quietly; print -a shows the result for checking.)+ isMirroredTransferCandidate :: Posting -> Bool+ isMirroredTransferCandidate p =+ let amts = amountsRaw (pamount p)+ baseAcct = lotBaseAccount (paccount p)+ in maybe False isAssetType (lookupAccountType baseAcct)+ && not (accountUsesNoLots baseAcct)+ && any ((/= 0) . aquantity) amts+ && not (any (isJust . acost) amts)++ -- Precompute per-commodity, per-quantity transfer counterpart info (O(n)).+ -- Keyed by (commodity, |quantity|) for exact quantity matching, the primary+ -- transfer detection; see negSums/posSums below for the sum-based fallback.+ -- For each key, which accounts have:+ -- negative postings with cost basis (transfer-from candidates; any account type)+ -- positive postings with cost basis (transfer-to candidates, standard path; any account type)+ -- positive asset postings without cost basis (transfer-to candidates, bare path; asset only)+ -- Account lists are deduplicated (typically 1-2 accounts per commodity).+ negCBAccts, posCBAccts, posNoCBAccts :: M.Map (CommoditySymbol, Quantity) [AccountName]+ (negCBAccts, posCBAccts, posNoCBAccts) = foldl' collect (M.empty, M.empty, M.empty) (zip [0..] ps)+ where+ collect (!neg, !pos, !noCB) (i, p)+ | not (isReal p) = (neg, pos, noCB) -- skip virtual postings+ -- skip balancer-copied basis annotations, except elided+ -- transfer source/destination candidates (isMirroredTransferCandidate)+ | hasBalancerCopiedBasis p, not (isMirroredTransferCandidate p) = (neg, pos, noCB)+ | i `S.member` sameAcctTransferSet = (neg, pos, noCB) -- skip same-account transfer pairs+ | optedOut p = (neg, pos, noCB) -- skip lots: NONE accounts' postings+ | isShortPosting p = (neg, pos, noCB) -- short lots don't transfer+ | otherwise =+ let baseAcct = lotBaseAccount (paccount p)+ isAsset = maybe False isAssetType (lookupAccountType baseAcct)+ amts = amountsRaw (pamount p)+ acct = baseAcct+ isNeg = any isNegativeAmount amts+ hasCB = any (isJust . acostbasis) amts+ isLotful = amountsAreLotful amts+ cbKeys = [(acommodity a, abs (aquantity a)) | a <- amts, isJust (acostbasis a)]+ allKeys = [(acommodity a, abs (aquantity a)) | a <- amts]+ -- Include cost-basis negatives (any account type) and bare lotful+ -- negatives on asset accounts. Non-asset bare lotful negatives+ -- (e.g. revenue) are excluded — they shouldn't be transfer counterparts.+ -- Equity transfers are handled separately via hasEquityCounterpart.+ neg' = if isNeg && (hasCB || (isLotful && isAsset))+ then foldl' (addAcct acct) neg (if hasCB then cbKeys else allKeys) else neg+ pos' = if not isNeg && hasCB+ then foldl' (addAcct acct) pos cbKeys else pos+ noCB' = if not isNeg && isAsset && not hasCB+ then foldl' (addAcct acct) noCB allKeys else noCB+ in (neg', pos', noCB')+ -- Add an account to a (commodity, quantity) key's account list, deduplicating.+ addAcct acct m k = M.insertWith (\_ old -> if acct `elem` old then old else acct : old) k [acct] m++ -- Is there a transfer counterpart for a posting in this account, with this sign,+ -- in this commodity and quantity?+ hasCounterpart :: AccountName -> Bool -> CommoditySymbol -> Quantity -> Bool+ hasCounterpart acct isNeg c q+ | isNeg = anyOtherAcct posCBAccts || anyOtherAcct posNoCBAccts+ | otherwise = anyOtherAcct negCBAccts+ where anyOtherAcct m = any (/= acct) (M.findWithDefault [] (c, abs q) m)++ -- Is there a transfer-from counterpart (negative with cost basis or lotful)+ -- for this commodity and quantity?+ hasTransferFromCounterpart :: AccountName -> CommoditySymbol -> Quantity -> Bool+ hasTransferFromCounterpart acct c q = any (/= acct) (M.findWithDefault [] (c, abs q) negCBAccts)++ -- Commodity-only transfer-from check (ignores quantity).+ -- Fallback for transfer+fee patterns where quantities don't match exactly.+ hasTransferFromCommodityMatch :: AccountName -> CommoditySymbol -> Bool+ hasTransferFromCommodityMatch acct c =+ any (\((c', _), accts) -> c' == c && any (/= acct) accts)+ (M.toList negCBAccts)++ -- Per-commodity totals of unpriced transfer-candidate amounts, with their+ -- accounts. Used for sum-based transfer detection when quantities don't+ -- pair one to one (a split or consolidating transfer, #2692).+ -- Priced amounts are excluded (a priced posting is a deliberate trade,+ -- eg a fee disposal), as are auto-split fee dispose fragments (feesplit+ -- tag), which would otherwise inflate the outflow total.+ -- Side criteria mirror the counterpart maps above: negatives need cost+ -- basis (any account type) or bare lotful in an asset account; positives+ -- need cost basis (any account type) or an asset account.+ negSums, posSums :: M.Map CommoditySymbol (Quantity, [AccountName])+ (negSums, posSums) = foldl' collectSums (M.empty, M.empty) (zip [0..] ps)+ where+ collectSums (!neg, !pos) (i, p)+ | not (isReal p) = (neg, pos)+ | hasBalancerCopiedBasis p = (neg, pos)+ | i `S.member` sameAcctTransferSet = (neg, pos)+ | postingHasTag feesplitPostingTagName p = (neg, pos)+ | optedOut p = (neg, pos)+ | isShortPosting p = (neg, pos)+ | otherwise = foldl' addAmt (neg, pos) amts+ where+ acct = lotBaseAccount (paccount p)+ isAsset = maybe False isAssetType (lookupAccountType acct)+ isLotful = amountsAreLotful amts+ amts = amountsRaw (pamount p)+ addAmt (!neg', !pos') a+ | isJust (acost a) = (neg', pos')+ | q < 0, hasCB || (isLotful && isAsset) = (addTo neg' (negate q), pos')+ | q > 0, hasCB || isAsset = (neg', addTo pos' q)+ | otherwise = (neg', pos')+ where+ q = aquantity a+ hasCB = isJust (acostbasis a)+ addTo m qty = M.insertWith merge (acommodity a) (qty, [acct]) m+ merge (newq, newaccts) (oldq, oldaccts) =+ (newq + oldq, foldr insertAcct oldaccts newaccts)+ insertAcct x xs = if x `elem` xs then xs else x : xs++ -- Is there a sum-matched transfer counterpart for this commodity ?+ -- True when the commodity's total unpriced outflow equals its total+ -- unpriced inflow (per the sum maps above), and the opposite side+ -- includes an account other than this posting's. Detects transfers+ -- whose postings don't pair one to one (#2692).+ hasSumCounterpart :: AccountName -> Bool -> CommoditySymbol -> Bool+ hasSumCounterpart acct isNeg c =+ case (M.lookup c negSums, M.lookup c posSums) of+ (Just (nq, naccts), Just (pq, paccts)) ->+ nq == pq && any (/= acct) (if isNeg then paccts else naccts)+ _ -> False++ classifyAt :: Int -> Posting -> Posting+ classifyAt i p+ | not (isReal p) = p -- skip virtual (parenthesised) postings+ | isClassifiedPosting p = p -- skip postings already carrying a ptype tag (eg gain postings tagged by transactionTagGainPostings)+ -- A balancer-copied basis posting is normally left unclassified,+ -- except when it can be read as the elided destination or source of+ -- a lot transfer (see isMirroredTransferCandidate).+ | hasBalancerCopiedBasis p =+ let baseAcct = lotBaseAccount (paccount p)+ cbPairs = [(acommodity a, aquantity a) | a <- amountsRaw (pamount p), isJust (acostbasis a)]+ isNeg = any isNegativeAmount (amountsRaw (pamount p))+ hasMatch+ | isNeg = any (\(c, q) -> hasCounterpart baseAcct True c q) cbPairs+ | otherwise = any (\(c, q) -> hasTransferFromCounterpart baseAcct c q) cbPairs+ in if isMirroredTransferCandidate p && hasMatch+ then addTag (if isNeg then "transfer-from" else "transfer-to") p+ else p+ | i `S.member` sameAcctTransferSet =+ let amts = amountsRaw (pamount p)+ cls = if any isNegativeAmount amts then "transfer-from" else "transfer-to"+ in addTag cls p+ | otherwise =+ case dbg5 ("classifyLotPostings: classifyPosting " ++ show (paccount p) ++ " result") $ shouldClassify p of+ Just classification -> addTag classification p+ Nothing -> p+ where addTag cls = postingAddHiddenAndMaybeVisibleTag True verbosetags (toHiddenTag ("ptype", cls))++ -- Check if posting should be classified and return the classification:+ -- one of acquire, dispose, transfer-from, transfer-to.+ shouldClassify :: Posting -> Maybe Text+ shouldClassify p = do+ let amts = amountsRaw $ pamount p+ baseAcct = lotBaseAccount (paccount p)+ -- Zero-amount postings (eg balance assertion carriers) move no lots and+ -- are left unclassified, consistent with isUnclassifiedLotfulPosting's+ -- zero exemption. (Eg a zero posting beside a transfer must not become+ -- a transfer-to via commodity matching.)+ guard $ any ((/= 0) . aquantity) amts+ guard $ not (optedOut p)+ if isShortPosting p+ then dbg5 ("classifyLotPostings: shouldClassify " ++ show (paccount p) ++ " short") $+ shouldClassifyShort p amts+ else if any (isJust . acostbasis) amts+ -- Cost basis present: classify regardless of account type (fix A)+ then dbg5 ("classifyLotPostings: shouldClassify " ++ show (paccount p) ++ " withCostBasis") $+ shouldClassifyWithCostBasis p amts+ else do+ -- No cost basis: require asset account type+ acctType <- dbg5 ("classifyLotPostings: shouldClassify " ++ show (paccount p) ++ " acctType") $+ lookupAccountType baseAcct+ guard $ isAssetType acctType+ dbg5 ("classifyLotPostings: shouldClassify " ++ show (paccount p) ++ " lotful/bare") $+ shouldClassifyNegativeLotful p amts <|> shouldClassifyLotful p amts <|> shouldClassifyBareTransferTo p amts <|> shouldClassifyPositiveLotful p amts++ -- True when the transaction has an equity posting with no explicit cost-basis amounts.+ -- This indicates an equity transfer: lots move to/from equity in two parts+ -- (e.g. close --clopen --lots generates a closing txn transferring lots into equity,+ -- and an opening txn transferring them back out), allowing the negative lot postings+ -- to be classified as transfer-from rather than dispose.+ hasEquityCounterpart :: Bool+ hasEquityCounterpart = any isEquityNonLotPosting ps+ where+ isEquityNonLotPosting q =+ maybe False isEquityType (lookupAccountType (lotBaseAccount (paccount q)))+ -- A balancer-copied basis annotation is not user-written+ -- (an elided equity posting still counts as an equity counterpart).+ && (hasBalancerCopiedBasis q || not (any (isJust . acostbasis) (amountsRaw (pamount q))))++ -- Classify a posting that has cost basis: acquire, dispose, transfer-from, or transfer-to.+ shouldClassifyWithCostBasis :: Posting -> [Amount] -> Maybe Text+ shouldClassifyWithCostBasis p amts = do+ let+ baseAcct = lotBaseAccount (paccount p)+ isNeg = any isNegativeAmount amts+ primaryType = if isNeg then "dispose" else "acquire"+ cbAmts = [(acommodity a, aquantity a) | a <- amts, isJust (acostbasis a)]+ -- A transfer counterpart can match by exact quantity, or by commodity+ -- sums when postings don't pair one to one (#2692). The sum fallback+ -- is only for unpriced postings (a priced posting is a deliberate+ -- trade) and not for auto-split fee fragments (which must remain+ -- disposals even though the remaining transfer sums match).+ isTransfer = any (\(c, q) -> hasCounterpart baseAcct isNeg c q) cbAmts+ || (not (any (isJust . acost) amts)+ && not (postingHasTag feesplitPostingTagName p)+ && any (hasSumCounterpart baseAcct isNeg . fst) cbAmts)+ -- Also treat as equity transfer when: no transacted price written,+ -- and an equity counterpart posting is present. This handles lots moving+ -- to/from equity (e.g. close --clopen --lots generates a closing txn with+ -- negative lot postings and an opening txn with positive lot postings).+ isEquityTransfer = not (any (isJust . acost) amts) && hasEquityCounterpart+ if isTransfer || isEquityTransfer+ then return $ if isNeg then "transfer-from" else "transfer-to"+ else do+ -- Don't classify income statement accounts (Revenue, Expense, Gain) as acquire/dispose.+ -- These are flow accounts that should not track lots or get lot subaccounts.+ -- E.g. expenses:fees 0.1 ETSY {$80} @ $90 in a stock-fee disposal.+ guard $ not $ maybe False isIncomeStatementAccountType (lookupAccountType baseAcct)+ return primaryType++ -- Classify a negative lotful posting without cost basis as dispose or transfer-from.+ -- If the posting has no transacted price and another asset account in the same+ -- transaction receives a positive lotful amount of the same commodity (even at+ -- different quantity), skip classification — it's a transfer+fee pattern and+ -- global FIFO will handle the lot reduction when the destination account trades.+ shouldClassifyNegativeLotful :: Posting -> [Amount] -> Maybe Text+ shouldClassifyNegativeLotful p amts = do+ guard $ amountsAreLotful amts+ guard $ any isNegativeAmount amts+ let baseAcct = lotBaseAccount (paccount p)+ hasPrice = any (isJust . acost) amts+ negAmts = [a | a <- amts, isNegativeAmount a]+ negCommodities = S.fromList [acommodity a | a <- negAmts]+ amtPairs = [(acommodity a, aquantity a) | a <- amts]+ isTransfer = any (\(c, q) -> hasCounterpart baseAcct True c q) amtPairs+ -- Check for positive lotful amounts in other asset accounts (same commodity).+ otherAssetReceives = any isOtherAssetWithLotful (filter (/= p) ps)+ isOtherAssetWithLotful q =+ let qAmts = amountsRaw (pamount q)+ qBase = lotBaseAccount (paccount q)+ in qBase /= baseAcct+ && maybe False isAssetType (lookupAccountType qBase)+ && not (optedOut q)+ && amountsAreLotful qAmts+ && any (\a -> aquantity a > 0 && acommodity a `S.member` negCommodities) qAmts+ -- Does a non-asset posting receive exactly this commodity+quantity?+ -- If so, this posting is likely a fee/dispose (e.g. paired with expenses:fees),+ -- not part of a transfer to another asset account.+ hasFeeCounterpart = any isFeeCounterpart (filter (/= p) ps)+ isFeeCounterpart q =+ let qAmts = amountsRaw (pamount q)+ qBase = lotBaseAccount (paccount q)+ in not (maybe False isAssetType (lookupAccountType qBase))+ && any (\a -> aquantity a > 0+ && any (\na -> acommodity na == acommodity a+ && abs (aquantity na) == aquantity a) negAmts) qAmts+ -- The other-asset-receives heuristic (transfer+fee pattern) applies only+ -- to unpriced postings: a transacted price signals dispose intent, eg an+ -- explicit priced fee disposal written alongside a matched transfer pair.+ if isTransfer || (otherAssetReceives && not hasFeeCounterpart && not hasPrice)+ then return "transfer-from"+ else do+ guard $ hasPrice || hasFeeCounterpart || not otherAssetReceives+ return "dispose"++ -- Classify a lotful posting without cost basis.+ -- A positive posting in a lotful commodity/account, with no transacted price,+ -- and with a matching transfer-from counterpart, is classified as transfer-to.+ shouldClassifyLotful :: Posting -> [Amount] -> Maybe Text+ shouldClassifyLotful p amts = do+ guard $ amountsAreLotful amts+ guard $ not $ any isNegativeAmount amts+ guard $ not $ any (isJust . acost) amts+ let baseAcct = lotBaseAccount (paccount p)+ amtPairs = [(acommodity a, aquantity a) | a <- amts]+ guard $ any (\(c, q) -> hasTransferFromCounterpart baseAcct c q) amtPairs+ || any (\(c, _) -> hasTransferFromCommodityMatch baseAcct c) amtPairs+ return "transfer-to"++ -- Classify a bare positive asset posting (no cost basis, not necessarily lotful)+ -- as transfer-to if there's a matching transfer-from counterpart (fix C).+ shouldClassifyBareTransferTo :: Posting -> [Amount] -> Maybe Text+ shouldClassifyBareTransferTo p amts = do+ guard $ not $ any isNegativeAmount amts+ guard $ not $ any (isJust . acost) amts+ let baseAcct = lotBaseAccount (paccount p)+ amtPairs = [(acommodity a, aquantity a) | a <- amts]+ guard $ any (\(c, q) -> hasTransferFromCounterpart baseAcct c q) amtPairs+ || any (\(c, _) -> hasTransferFromCommodityMatch baseAcct c) amtPairs+ return "transfer-to"++ -- Classify a positive lotful posting without cost basis as acquire.+ -- This is the fallback for positive lotful postings that aren't transfer-to.+ -- Requires a plausible cost source: transacted price, different-commodity posting+ -- (for balancer inference), or a transfer-from counterpart (whose lot cost is inherited).+ -- Without any of these, no lot can be created so we skip classification.+ shouldClassifyPositiveLotful :: Posting -> [Amount] -> Maybe Text+ shouldClassifyPositiveLotful p amts = do+ guard $ amountsAreLotful amts+ guard $ any (\a -> aquantity a > 0) amts+ let hasPrice = any (isJust . acost) amts+ baseAcct = lotBaseAccount (paccount p)+ hasTransferFrom = any (\(c, q) -> hasTransferFromCounterpart baseAcct c q)+ [(acommodity a, aquantity a) | a <- amts]+ guard $ hasPrice || hasOtherCommodityPosting p amts || hasTransferFrom+ return "acquire"++ -- Classify a posting in a Short (liability) account, which holds short+ -- positions: a negative amount opens a short lot (acquire), a positive+ -- one covers it (dispose). Short lots can't be transferred between+ -- accounts yet (see isShortPosting), but can be moved to or from+ -- equity (close --clopen --lots): with no transacted price and an+ -- equity counterpart, it is an equity transfer, like a long posting.+ -- Like a long posting, a bare open needs a cost source (a transacted+ -- price, or another commodity to infer it from); a bare cover without+ -- a price is a priceless disposal.+ shouldClassifyShort :: Posting -> [Amount] -> Maybe Text+ shouldClassifyShort p amts = do+ let hasCB = any (isJust . acostbasis) amts+ hasPrice = any (isJust . acost) amts+ isInflow = any (isLotInflow Short) amts+ isEquityTransfer = not hasPrice && hasEquityCounterpart+ guard $ hasCB || amountsAreLotful amts+ if isEquityTransfer+ then return $ if isInflow then "transfer-to" else "transfer-from"+ else if isInflow+ then do+ guard $ hasCB || hasPrice || hasOtherCommodityPosting p amts+ return "acquire"+ else return "dispose"++ -- Does another amountful posting in the transaction have a commodity+ -- other than this posting's ? (Then the balancer can infer a cost.)+ hasOtherCommodityPosting :: Posting -> [Amount] -> Bool+ hasOtherCommodityPosting p amts =+ any (\q -> any ((`S.notMember` commodities) . acommodity) (amountsRaw (pamount q)))+ (filter (\q -> q /= p && hasAmount q) ps)+ where commodities = S.fromList [acommodity a | a <- amts]++ -- Check if a posting's amounts are lotful: one of their commodities has a lots: tag.+ amountsAreLotful :: [Amount] -> Bool+ amountsAreLotful = any (commodityIsLotful . acommodity)++-- Lot calculation (pipeline stage 2)++-- | Calculate detailed lot movements by walking transactions in date order.+-- Handles acquire postings (generating lot names as subaccounts),+-- dispose postings (matching to existing lots using FIFO, splitting if needed),+-- and transfer postings (moving lots between accounts, preserving cost basis).+-- The verbosetags parameter controls whether generated-posting tags are made visible in comments.+-- All lot selection/classification failures are hard errors.+-- Same-date transactions are processed in parse order, never reordered.+journalCalculateLots :: Bool -> Journal -> Either String Journal+journalCalculateLots verbosetags j+ | not $ any (any isLotPosting . tpostings) txns = do+ mapM_ checkUnclassified [(t, i, p) | t <- txns, (i, p) <- zip [0..] (tpostings t)]+ Right j+ | otherwise = do+ validateUserLabels txns+ let needsLabels = findDatesNeedingLabels txns+ -- Transactions with no lotful amounts can't affect lots; pass them through untouched.+ -- An error gets a hint if a later transaction might have been meant to come first.+ process acc@(ls, done) t later+ | not $ transactionHasLotfulAmounts lotfulcomms t = Right (ls, t : done)+ | otherwise = first (appendPostingsReadAs t . (++ laterSupplyHint ls t later) . dropWhileEnd (== '\n'))+ $ processTransaction styles verbosetags j needsLabels acc t+ walk acc [] = Right acc+ walk acc (t:later) = process acc t later >>= \acc' -> walk acc' later+ (_, txns') <- walk (M.empty, []) (sortOn tdate txns)+ Right (journalTieTransactions $ j{jtxns = reverse txns'})+ where+ txns = jtxns j+ lotfulcomms = journalLotfulCommodities j+ -- Journal's canonical commodity styles, used for rendering the cost amount+ -- in lot subaccount names. NoRounding preserves the original decimal digits+ -- while still applying the canonical decimal mark, digit group separators,+ -- and commodity position/spacing.+ styles = journalCommodityStylesWith NoRounding j+ checkUnclassified (t, i, p)+ | isUnclassifiedLotfulPosting j p = Left (appendPostingsReadAs t $ unclassifiedLotWarning j t i p)+ | otherwise = Right ()++-- | A hint for a lot error in this transaction, explaining that a later entry+-- on the same date adds the commodity to an account which the transaction takes+-- it from, but which holds none of it yet. Same-date entries are processed in+-- parse order, so the later entry may have been meant to come first (eg the+-- other side of a transfer recorded through a clearing account, or a same-day+-- purchase). Starts with a newline; empty when there is no such entry.+laterSupplyHint :: LotState -> Transaction -> [Transaction] -> String+laterSupplyHint ls t later = case supplies of+ [] -> ""+ (a, c, f) : _ -> printf+ ("\n\nA later entry on the same date adds %s to %s:\n %s\n"+ ++ "Same-date entries are processed in the order they are read; perhaps that entry should come first.")+ (T.unpack c) (T.unpack a) (txnDbgPrefix f)+ where+ sameDate = takeWhile ((== tdate t) . tdate) later+ unheld = [ (a, acommodity x)+ | p <- tpostings t, isTransferFromPosting p || isDisposePosting p+ , let a = lotBaseAccount (paccount p)+ , x <- amountsRaw (pamount p), aquantity x < 0+ , not $ any (M.member a) (M.findWithDefault M.empty (acommodity x) ls) ]+ supplies = [ (a, c, f) | (a, c) <- unheld, f <- sameDate, any (addsTo a c) (tpostings f) ]+ addsTo a c q = (isAcquirePosting q || isTransferToPosting q)+ && lotBaseAccount (paccount q) == a+ && any ((== c) . acommodity) (amountsRaw (pamount q))++-- Disposal gain postings++-- | Make a generated realised-gain posting with the given account and amount,+-- tagged @_ptype:gain@ and @_generated-posting@ (the latter visible as+-- @generated-posting:@ in @print --verbose-tags@).+mkGeneratedGainPosting :: Bool -> AccountName -> MixedAmount -> Posting+mkGeneratedGainPosting verbosetags acc amt =+ tagGain verbosetags+ $ postingAddHiddenAndMaybeVisibleTag False verbosetags (generatedPostingTagName, "")+ $ nullposting{paccount = acc, pamount = amt}++-- | Tag a posting as a gain posting (@_ptype:gain@).+tagGain :: Bool -> Posting -> Posting+tagGain verbosetags = postingAddHiddenAndMaybeVisibleTag True verbosetags (toHiddenTag ("ptype", "gain"))++-- | Does this posting look like a lot disposal (or transfer source) ?+-- True if it has a lot outflow amount (negative, or positive in a liability+-- account, which holds short lots) with a cost basis annotation, or in a+-- lotful commodity (unless the account opts out with lots: NONE).+-- A shape check, usable before lot classification has run.+postingHasDisposeShape :: (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Posting -> Bool+postingHasDisposeShape lookupAccountType commodityIsLotful accountUsesNoLots p =+ any (\a -> isLotOutflow dir a+ && (isJust (acostbasis a)+ || (commodityIsLotful (acommodity a)+ && not (accountUsesNoLots (lotBaseAccount (paccount p))))))+ (amountsRaw (pamount p))+ where dir = fromMaybe Long (lotDirectionOf lookupAccountType (paccount p))++-- | In a disposal transaction, tag the user-written realised gain+-- postings with @_ptype:gain@, so that the transaction balancer sets them+-- aside (see 'Hledger.Data.Balancing.transactionCheckBalanced').+--+-- A disposal balances at cost basis: the dispose posting counts as its+-- quantity times its basis, and the gain posting accounts for the+-- difference from the transacted proceeds. The basis is not known until+-- lot matching, which runs after balancing; but since+-- @q*B + q*(T-B) == q*T@, balancing the non-gain postings at transacted+-- cost is equivalent, and that is what the balancer does. Whether the gain+-- amount is right is checked afterwards by 'journalAddOrCheckGainPostings'.+--+-- Disposal transactions are recognised by shape, since classification has+-- not run yet: a real posting with a negative lotful or cost-basis amount+-- ('postingHasDisposeShape'; this also matches transfer sources, where a+-- gain posting is later rejected by journalAddOrCheckGainPostings, the+-- gain being zero). Gain postings are recognised in one of two ways:+--+-- 1. By account type: real postings on a Gain-typed account. These may be+-- amountless (unless the first argument is false, in lenient --ignore-lots+-- mode, where there'll be no lot matching to fill the amount in): the+-- balancer leaves such a posting alone and 'journalAddOrCheckGainPostings'+-- sets its amount to the calculated gain.+--+-- 2. Heuristically, when there is no Gain-typed posting: real, amountful+-- postings whose account type is not Asset, Liability or Equity (or a+-- subtype), and which don't carry a lotful or cost-basis amount; accepted+-- only if all postings have amounts and the remaining postings sum to+-- zero at transacted cost (a well-formed disposal), or to an unpriced+-- sale: a lot commodity net sold plus one other commodity net received+-- (which balancing cost inference will resolve). A net purchase with a+-- cash fee posting is not mistaken for a disposal with a gain.+-- This lets a gain posting be written on any account without declaring+-- it type:G, for simple entries.+--+-- Virtual (parenthesised) postings are ignored throughout, as the balancer+-- and the lot machinery ignore them. A transaction which already has a+-- tagged gain posting is returned unchanged, so this is safe to run+-- repeatedly: it runs as a journalFinalise step, and again inside the+-- balancer for callers which balance single entries (hledger add, hledger-web).+transactionTagGainPostings+ :: Bool -- ^ also tag amountless Gain-typed postings (not in lenient mode)+ -> Bool -- ^ also add visible tags+ -> (AccountName -> Maybe AccountType) -- ^ account type lookup+ -> (CommoditySymbol -> Bool) -- ^ is this a lotful commodity ?+ -> (AccountName -> Bool) -- ^ does this account use lots: NONE ?+ -> Transaction -> Transaction+transactionTagGainPostings tagamountless verbosetags lookupAccountType commodityIsLotful accountUsesNoLots t+ | any isGainPosting realps = t+ | not (any hasDisposeShape realps) = t+ | any isGainTyped realps = tagPostings isGainTyped+ | heuristicOk = tagPostings isCandidate+ | otherwise = t+ where+ realps = filter isReal (tpostings t)+ hasDisposeShape = postingHasDisposeShape lookupAccountType commodityIsLotful accountUsesNoLots+ isGainTyped p = (tagamountless || hasAmount p) && lookupAccountType (paccount p) == Just Gain+ hasLotfulOrBasisAmount p =+ any (\a -> isJust (acostbasis a) || commodityIsLotful (acommodity a)) (amountsRaw (pamount p))+ tagPostings isgain = txnTieKnot t{tpostings = map tag (tpostings t)}+ where tag p = if isReal p && isgain p then tagGain verbosetags p else p++ -- Heuristic gain candidates, and whether the other postings balance without them.+ isCandidate p = hasAmount p && notALE p && not (hasLotfulOrBasisAmount p)+ where+ notALE q = case lookupAccountType (paccount q) of+ Just ty -> not (isAssetType ty || isLiabilityType ty || isEquityType ty)+ Nothing -> True+ heuristicOk =+ all hasAmount realps -- with an elided amount, leave it to the balancer+ && not (null candidates)+ && (if transactionHasCostPostings t+ -- with equity conversion postings, the gain counts (see isSetAsideGainPosting):+ -- the whole entry, candidates included, nets to zero+ then mixedAmountIsZero (residual `maPlus` foldMap balancingAmount candidates)+ else mixedAmountIsZero residual -- well-formed disposal: net zero+ || isPricelessClose nonzeroresidual) -- unpriced sale: cost inference will resolve+ where+ (candidates, noncandidates) = partition isCandidate realps+ residual = foldMap balancingAmount noncandidates+ -- as the balancer counts it: at cost, unless the cost is represented by conversion postings+ balancingAmount p+ | postingHasTag costPostingTagName p = mixedAmountStripCosts (pamount p)+ | otherwise = mixedAmountCost (pamount p)+ nonzeroresidual = filter ((/= 0) . aquantity) (amountsRaw residual)+ -- The residual is a lot commodity net closed (sold; or bought, to+ -- cover a short) and one other commodity net received (or paid).+ -- (A net purchase with a cash fee has the opposite signs; there the+ -- fee is not a gain.)+ isPricelessClose as = case partition (isLotCommodity . acommodity) as of+ ([closed], [other]) -> any (`isLotOutflow` closed) disposedirs+ && signum (aquantity other) == negate (signum (aquantity closed))+ _ -> False+ isLotCommodity c = commodityIsLotful c || c `elem` map acommodity disposeamounts+ disposeshaped = filter hasDisposeShape realps+ disposeamounts = concatMap (amountsRaw . pamount) disposeshaped+ disposedirs = [fromMaybe Long (lotDirectionOf lookupAccountType (paccount p)) | p <- disposeshaped]++-- | Apply 'transactionTagGainPostings' to each transaction. In lenient+-- (--ignore-lots) mode, amountless gain postings are left untagged, for the+-- balancer to infer like any other posting.+journalTagGainPostings :: Bool -> Bool -> Journal -> Either String Journal+journalTagGainPostings lenient verbosetags j = Right $ journalMapTransactions tag j+ where+ tag t+ | not $ transactionHasLotfulAmounts lotfulcomms t = t -- can't be a disposal+ | otherwise = transactionTagGainPostings (not lenient) verbosetags (journalAccountType j) (`S.member` lotfulcomms) (journalAccountUsesNoLots j) t+ lotfulcomms = journalLotfulCommodities j++-- | Error for a disposal with a gain posting whose amount was inferred by+-- the balancer because the disposal could only be recognised afterwards+-- (eg its amounts came from a balance assignment).+amountlessErr :: Transaction -> String+amountlessErr t =+ txnErrPrefix t+ ++ "This disposal has an amountless gain posting, which can't be inferred here.\n"+ ++ "Write the amount explicitly, or omit the posting entirely\n"+ ++ "(hledger will then infer the realised gain from the cost basis)."++-- | Error for a disposal with more than one amountless gain posting.+multipleAmountlessErr :: Transaction -> String+multipleAmountlessErr t =+ txnErrPrefix t+ ++ "This disposal has more than one amountless gain posting.\n"+ ++ "At most one gain posting can have its amount inferred."++-- | Check that no acquire-shaped posting (a real posting with a positive+-- amount, in an asset account) writes both a per-unit cost basis and a+-- transacted cost which disagree. In an acquisition these are the same+-- thing, what the units cost; a typo in either would silently miscalculate+-- gains. (Real-world cases of a basis differing from what was paid, like a+-- gift with carryover basis, are written with the difference funded by a+-- separate posting.)+--+-- They may agree only at the precision of the written basis: typically a+-- non-terminating unit cost rendered to 8 decimal places by print (as a+-- basis annotation or in a lot subaccount name), re-read alongside its+-- exact @@ total cost. Then the exact transacted unit cost replaces the+-- written basis, so nothing is lost in the round trip.+--+-- This runs before transaction balancing, so that such an entry gets this+-- error rather than an unbalanced-transaction error; it needs only the+-- amounts as written (after 'journalInferPostingsTransactedCost').+journalCheckAcquireBasis :: Journal -> Either String Journal+journalCheckAcquireBasis j = do+ ts <- mapM checkTxn (jtxns j)+ Right j{jtxns = ts}+ where+ checkTxn t = do+ ps <- mapM checkPosting (zip [0..] (tpostings t))+ Right $ txnTieKnot t{tpostings = ps}+ where+ checkPosting (idx, p)+ | isReal p, Just dir <- journalLotDirection j (paccount p) = do+ as <- mapM (checkAmount dir idx p) (amountsRaw (pamount p))+ Right p{pamount = mixed as}+ | otherwise = Right p+ checkAmount dir idx p a = case (acostbasis a, acost a) of+ (Just cb@CostBasis{cbCost = Just basis}, Just tc)+ | isLotInflow dir a -- acquire-shaped (a disposal's basis and sale price are expected to differ)+ , let transacted = amountCostToUnitCost (aquantity a) tc+ -> checkBasis cb basis transacted+ _ -> Right a+ where+ checkBasis cb basis transacted+ | aquantity basis == aquantity transacted = Right a+ | roundTo (writtenPlaces basis) (aquantity transacted) == aquantity basis+ = Right a{acostbasis = Just cb{cbCost = Just transacted}}+ | otherwise = Left (acquireBasisErr t idx p basis transacted)+ writtenPlaces = decimalPlaces . aquantity -- trailing zeros included: {$46.00} is not $45.56++ acquireBasisErr t idx p basis transacted =+ printf "%s:%d:\n%s\n" f l (T.unpack ex)+ ++ "This acquire posting's cost basis (" ++ basisStr+ ++ ") differs from its transacted cost (" ++ transactedStr ++ ").\n"+ ++ "Options:\n"+ ++ " - drop {} or {{}} so basis is inferred from the transacted cost\n"+ ++ " - drop @ or @@ so transacted cost is inferred from the basis\n"+ ++ " - use {{TotalCost}} or write the per-unit basis at higher precision\n"+ ++ " - if the difference is real (gift, NSO, RSU, etc.), fund it via a separate posting"+ where+ col1 = 5 + if isVirtual p then 1 else 0+ col2 = col1 + T.length (paccount $ originalPosting p) - 1+ (f, l, _mcols, ex) = makePostingErrorExcerptByIndex (transactionAsWritten t) (asWrittenPostingIndex t idx) (Just (col1, Just col2))+ (basisStr, transactedStr) =+ showAmountsDistinctly oneLineNoCostFmt{displayZeroCommodity=True} basis transacted++-- | For each disposal transaction with a transacted price, add a realised-gain+-- posting to a 'Gain'-type account (default @revenues:gain@) with+-- the negated gain amount; or if the transaction already has gain posting(s)+-- (user-written; see 'transactionTagGainPostings'), check that their sum+-- matches the calculated gain.+--+-- With the gain posting present, the disposal balances at cost basis, and+-- no counter posting is needed: hledger records gains by the historical cost+-- convention, in which unrealised gains are not posted (though they can be+-- reported from market prices).+--+-- The gain amount is the disposal gain: for each dispose posting amount with+-- both a cost basis and a transacted cost, contribute @aquantity * (B - T)@+-- (equivalently: cost-basis value minus transacted-cost value). Acquire and+-- other postings do not contribute. Eg for @-5 AAPL {$50} \@ $70@: gain+-- contribution is @-5 * ($50 - $70) = $100@.+--+-- Runs after 'journalCalculateLots' so that cost basis is populated on dispose+-- postings. The generated posting carries the @_generated-posting@ hidden tag,+-- visible as @generated-posting:@ in @print --verbose-tags@.+journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal+journalAddOrCheckGainPostings verbosetags j = do+ txns' <- mapM (\t -> first (appendPostingsReadAs t) $ addOrCheck t) (jtxns j)+ Right j{jtxns = txns'}+ where+ atypes = jaccounttypes j+ gainAccount = journalBaseGainAccount j++ -- Within a disposal, gain postings are identified by the _ptype:gain+ -- hidden tag (added by transactionTagGainPostings), or by account type+ -- (declared or inferred from name). Only real postings count, as in+ -- transactionTagGainPostings and the balancer.+ isGainTyped p = isReal p && accountNameType atypes (paccount p) == Just Gain+ isGain p = isReal p && (isGainPosting p || isGainTyped p)+ disposeHasPrice p = isDisposePosting p && any (isJust . acost) (amountsRaw (pamount p))++ addOrCheck t+ | any isGainPosting ps = fillOrCheck t -- tagged gain posting(s), possibly in a non-disposal (then the gain is zero)+ | not (any disposeHasPrice ps) = Right t+ | any isAmountlessGain ps = Left (amountlessErr t)+ | any isGainTyped ps = checkGain t+ | otherwise = Right (addGain t)+ where+ ps = tpostings t+ -- An untagged gain posting the user left amountless: the disposal was+ -- not recognisable when the balancer tagged gain postings, so it has+ -- inferred an amount for it by now, which can't be corrected; check+ -- the original posting. (Rare: balance assignments are resolved before+ -- tagging, so the #2686 shape no longer gets here.)+ isAmountlessGain p = isGainTyped p && not (hasAmount (originalPosting p))++ -- With tagged gain postings: if exactly one is amountless, set its amount+ -- to the calculated gain (less any other written gain amounts); otherwise+ -- check the written amount(s).+ fillOrCheck t = case filter (\p -> isGain p && not (hasAmount p)) (tpostings t) of+ [] -> checkGain t+ [_] -> Right (fillGain t)+ _ -> Left (multipleAmountlessErr t)++ fillGain t = txnTieKnot t{tpostings = map fill (tpostings t)}+ where+ ps = tpostings t+ gain = foldMap postingDisposalGain ps+ written = foldMap pamount (filter (\p -> isGain p && hasAmount p) ps)+ amt = setLocalGainPrecision t (maNegate gain <> maNegate written)+ fill p+ | isGain p && not (hasAmount p) = p{pamount = amt, poriginal = Just (originalPosting p)}+ | otherwise = p++ addGain t+ | mixedAmountIsZero gain = t+ | otherwise = txnTieKnot t{tpostings = tpostings t ++ [gainP]}+ where+ gain = foldMap postingDisposalGain (tpostings t)+ gainP = mkGeneratedGainPosting verbosetags gainAccount (setLocalGainPrecision t $ maNegate gain)++ -- Check that the user-written gain amount(s) sum to the calculated+ -- disposal gain (negated). The gain is zero when there is no priced+ -- disposal, eg a gain posting mistakenly written in a lot transfer.+ -- Like the balancer, this tolerates a difference below the precision+ -- chosen by setLocalGainPrecision; the written amounts are then made+ -- exact, so the difference isn't left unaccounted for.+ checkGain t+ | mixedAmountLooksZero (setLocalGainPrecision t diff) = Right exactGain+ | otherwise = Left (mismatchErr t gain writtenGain)+ where+ ps = tpostings t+ gain = foldMap postingDisposalGain ps+ writtenGain = foldMap pamount (filter isGain ps)+ diff = writtenGain <> gain -- writtenGain should equal -gain+ exactGain = case filter ((/= 0) . aquantity) (amountsRaw diff) of+ [] -> t+ as -> txnTieKnot t{tpostings = foldr subtractFromLastGain ps as}+ -- Subtract a small difference from the last gain posting in its commodity+ -- (or the last gain posting), keeping the written amount for print.+ subtractFromLastGain a qs = reverse $ case break target (reverse qs) of+ (xs, q:ys) -> xs ++ q{pamount = setLocalGainPrecision t (pamount q <> maNegate (mixedAmount a))+ ,poriginal = Just (originalPosting q)} : ys+ (xs, []) -> xs+ where+ target = if any inCommodity qs then inCommodity else isGain+ inCommodity q = isGain q && acommodity a `elem` map acommodity (amountsRaw (pamount q))++ -- Set each component amount's display precision to the entry's local+ -- precision for that commodity.+ -- Special rule for the 0 decimals case (when the local precision is 0,+ -- or there are no amounts of the commodity present):+ -- display with 2 decimals if either of them is non-zero, otherwise+ -- display with 0 decimals.+ -- The full precision is preserved internally, so reports like+ -- `print -c '$1.0000' --round=soft` can still reveal sub-cent detail.+ setLocalGainPrecision t = mapMixedAmount setOne+ where+ styles = transactionCommodityStyles t+ setOne a@Amount{aquantity = q, astyle = s} =+ case M.lookup (acommodity a) styles of+ Just AmountStyle{asprecision = Precision n} | n >= 1 ->+ a{astyle = s{asprecision = Precision n}}+ _ ->+ let q2 = roundTo 2 q+ in if roundTo 0 q2 == q2+ then a{astyle = s{asprecision = Precision 0}}+ else a{astyle = s{asprecision = Precision 2}}++ mismatchErr t gain writtenGain =+ txnErrPrefix t+ ++ "This disposal's realised gain amount is wrong.\n"+ ++ " written: " ++ writtenStr ++ "\n"+ ++ " calculated: " ++ calculatedStr+ where+ (writtenStr, calculatedStr) =+ showMixedAmountsDistinctly oneLineNoCostFmt{displayZeroCommodity=True}+ writtenGain (maNegate gain)++ -- | The realised-capital-gain contribution from a single posting.+ --+ -- Sums 'amountBasisVsTransactedGap' across the posting's amounts,+ -- treating each non-zero gap as realised gain on the lot units changing+ -- hands. Eg @assets:broker -5 AAPL {$50} \@ $70@ contributes+ -- @-5 * ($50 - $70) = $100@ — five shares sold at a $20 profit each.+ --+ -- Acquire postings are excluded: a fresh acquisition with+ -- @basis ≠ transacted@ is a carryover or bookkeeping imbalance, not+ -- realised gain, and is dealt with separately. Every other kind of+ -- posting contributes, including postings the lot classifier did not+ -- explicitly tag as @_ptype:dispose@ (eg a fee paid in lot-tracked+ -- stock — its disposal economics are real even without the tag).+ postingDisposalGain :: Posting -> MixedAmount+ postingDisposalGain p+ | isAcquirePosting p = nullmixedamt+ | not (hasAmount p) = nullmixedamt+ | otherwise = foldMap amountBasisVsTransactedGap (amountsRaw (pamount p))++ -- | The per-amount cost-basis-vs-transacted-cost gap.+ --+ -- An amount can carry two unit prices: its /cost basis/ from a @{...}@+ -- annotation, and its /transacted cost/ from @\@@ or @\@\@@. When both+ -- are present, this returns @aquantity * (basis - transacted)@,+ -- equivalently the amount's value at cost basis minus its value at+ -- transacted cost. Returns 'nullmixedamt' if either side is missing.+ --+ -- Pure arithmetic; the caller decides what the gap /means/ in context+ -- (realised gain on a disposal, carryover/imbalance on an acquire, etc).+ amountBasisVsTransactedGap :: Amount -> MixedAmount+ amountBasisVsTransactedGap a = case (acostbasis a >>= cbCost, acost a) of+ (Just basisCost, Just transactedCost) ->+ let basisVal = mixedAmount basisCost{aquantity = multiplyQuantities (aquantity a) (aquantity basisCost)}+ transactedVal = case transactedCost of+ UnitCost c -> mixedAmount c{aquantity = multiplyQuantities (aquantity a) (aquantity c)}+ TotalCost c -> mixedAmount c+ in basisVal <> maNegate transactedVal+ _ -> nullmixedamt++-- | Collapse lot-tracking detail from a journal for display when --lots is off.+-- Makes these targeted changes to each transaction:+--+-- * drops postings tagged @_lot-parent-assertion@ (synthetic balance-assertion+-- carriers added when splitting a posting into lot subaccounts);+-- * strips any lot subaccount (the trailing @{...}@ component) from each remaining+-- posting's account name;+-- * merges per-lot split fragments back into one posting (see mergeLotSplits).+--+-- Lot-inferred cost basis annotations (@acostbasis@) are kept on the amounts:+-- 'print' shows them, so that lot entries are self-describing and can be+-- re-read without the commodity's @lots:@ declaration (under the default+-- method). A merged multi-lot posting gets an unspecified basis (@{}@),+-- meaning "lots selected by the account's method".+--+-- Postings tagged @_feesplit-posting@ (synthetic fee fragments from auto-split) are+-- retained so transactions stay balanced in reports like 'print'.+--+-- 'print' relies on its existing 'transactionWithMostlyOriginalPostings' logic to+-- revert pamount to 'poriginal' when displaying non-explicit output (carrying+-- the inferred basis over).+--+-- Journals with no lot content are returned unchanged.+journalCollapseLotDetail :: Journal -> Journal+journalCollapseLotDetail j+ | any (any needsCollapse . tpostings) (jtxns j) = journalMapTransactions collapseTransaction j+ | otherwise = j+ where+ needsCollapse p = postingHasTag feesplitPostingTagName p+ || postingHasTag lotsplitPostingTagName p+ || postingHasTag lotParentAssertionTagName p+ || isJust (lotSubaccountName (paccount p))++ collapseTransaction t =+ txnTieKnot t{tpostings = mergeLotSplits (mapMaybe collapsePosting (tpostings t))}++ collapsePosting p+ | postingHasTag lotParentAssertionTagName p = Nothing+ | otherwise = Just p+ { paccount = newAcct+ -- An assertion originally written on the base account (eg by CSV+ -- balanceN rules) targets the parent, which is what this collapsed+ -- posting shows again; keep it, so writing out the collapsed view+ -- (eg by import) preserves it. But an assertion the user wrote on+ -- the lot subaccount itself asserts that lot's balance, which was+ -- checked against the pre-collapse paccount during journalFinalise;+ -- drop it here so the collapsed view isn't re-validated against+ -- the parent total.+ , pbalanceassertion =+ if newAcct == paccount p || originalAcct == newAcct+ then pbalanceassertion p+ else Nothing+ }+ where+ newAcct = lotBaseAccount (paccount p)+ -- The account the user actually wrote (before lot processing).+ originalAcct = paccount (originalPosting p)++ -- Merge consecutive lotsplit-tagged postings that share the same original+ -- (poriginal) into one. The survivor's pamount is taken from its+ -- 'poriginal' (the user's full original amount); the lotsplit tag (and+ -- its visible copy, if --verbose-tags added one) is removed, so the rest+ -- of the pipeline sees a normal single posting.+ -- Sharing 'poriginal' identifies siblings from the same per-lot split,+ -- distinguishing them from unrelated lotsplit postings (eg the from- and+ -- to-side runs of a same-account transfer).+ mergeLotSplits = go+ where+ go [] = []+ go (p:ps)+ | postingHasTag lotsplitPostingTagName p =+ let sameRun q = postingHasTag lotsplitPostingTagName q && poriginal q == poriginal p+ (run, rest) = span sameRun ps+ -- The merged posting's amount is the sum of the run's+ -- (already-collapsed) fragment amounts. This equals the+ -- original's amount, except when the original had no amount+ -- (elided or a balance assignment - using the original would+ -- lose the amount entirely) or when a fee portion was split+ -- off (using the original would double-count the retained+ -- feesplit posting's amount). (#2692)+ -- Summing several fragments drops their cost bases; show+ -- instead the basis fields on which all the fragments'+ -- lots agree (eg the date and cost, when only the labels+ -- differ), as a selector which re-reads equivalently: it+ -- is at least as specific as the user's, and the method+ -- still picks the same lots first (#2843).+ merged = maSum (map pamount (p:run))+ cbs = [cb | a <- concatMap (amountsRaw . pamount) (p:run), Just cb <- [acostbasis a]]+ survivor = (postingRemoveHiddenAndVisibleTag (lotsplitPostingTagName, "") p){pamount = if null run || null cbs then merged else mapMixedAmount commonBasis merged}+ commonBasis a = a{acostbasis = Just CostBasis+ { cbDate = agreed cbDate+ , cbLabel = agreed cbLabel+ , cbCost = agreed cbCost+ }}+ agreed f = case map f cbs of+ (v:vs) | all (== v) vs -> v+ _ -> Nothing+ in survivor : go rest+ | otherwise = p : go ps++-- Posting type predicates++-- | When an implicit-lot-subaccount posting (one whose account was a plain account,+-- not already a lot subaccount) is converted to explicit lot subaccount posting(s),+-- and it had a balance assertion, move the assertion to a new zero-amount generated+-- posting on the original parent account, making it subaccount-inclusive (=* style).+-- This preserves the assertion's meaning when the output is re-read without --lots:+-- the assertion checks the total of all lot subaccounts rather than the (empty)+-- direct balance of the parent.+-- If the original account was already a lot subaccount, the split postings are+-- returned unchanged (the assertion already targets the right account).+preserveParentAssertion :: Bool -> AccountName -> Maybe BalanceAssertion -> [Posting] -> [Posting]+preserveParentAssertion _ _ Nothing ps = ps+preserveParentAssertion _ origAcct (Just _) ps+ | lotBaseAccount origAcct /= origAcct = ps -- already an explicit lot subaccount; leave as-is+preserveParentAssertion verbosetags origAcct (Just ba) ps =+ map (\p -> p{pbalanceassertion = Nothing}) ps+ ++ [ postingAddHiddenAndMaybeVisibleTag False verbosetags (lotParentAssertionTagName, "")+ $ postingAddHiddenAndMaybeVisibleTag False verbosetags (generatedPostingTagName, "")+ nullposting+ { paccount = origAcct+ , pamount = mixedAmount (baamount ba){aquantity = 0}+ , pbalanceassertion = Just ba{bainclusive = True}+ } ]++-- | Check if a posting has any lot-related ptype tag.+isLotPosting :: Posting -> Bool+isLotPosting p = isAcquirePosting p || isDisposePosting p+ || isTransferFromPosting p || isTransferToPosting p+ || isGainPosting p++-- | True if this posting has any _ptype tag (was classified by lot classification,+-- or is a generated gain posting).+isClassifiedPosting :: Posting -> Bool+isClassifiedPosting p = any ((== "_ptype") . fst) (ptags p)++-- | Check if a posting is an acquire posting (has _ptype:acquire tag).+isAcquirePosting :: Posting -> Bool+isAcquirePosting p = ("_ptype", "acquire") `elem` ptags p++-- | Check if a posting is a dispose posting (has _ptype:dispose tag).+isDisposePosting :: Posting -> Bool+isDisposePosting p = ("_ptype", "dispose") `elem` ptags p++-- | Check if a posting is a transfer-from posting (has _ptype:transfer-from tag).+isTransferFromPosting :: Posting -> Bool+isTransferFromPosting p = ("_ptype", "transfer-from") `elem` ptags p++-- | Check if a posting is a transfer-to posting (has _ptype:transfer-to tag).+isTransferToPosting :: Posting -> Bool+isTransferToPosting p = ("_ptype", "transfer-to") `elem` ptags p++-- | Check if a posting is a gain posting (has _ptype:gain tag):+-- user-written and tagged by transactionTagGainPostings, or generated by+-- journalAddOrCheckGainPostings.+isGainPosting :: Posting -> Bool+isGainPosting p = ("_ptype", "gain") `elem` ptags p++-- | Is this a gain posting which the transaction balancer should set aside ?+-- A disposal's gain posting is set aside so that the entry, with the disposal+-- counted at transacted cost, balances at cost basis (see+-- 'transactionTagGainPostings'). But when the entry has equity conversion+-- postings (a posting tagged as a cost posting), the disposal's cost is+-- ignored and the conversion postings carry the cost basis instead, so the+-- gain posting counts like any other.+isSetAsideGainPosting :: Transaction -> Posting -> Bool+isSetAsideGainPosting t = \p -> isGainPosting p && not hascostpostings -- partially applied, the scan is shared+ where hascostpostings = transactionHasCostPostings t++-- | Does this transaction have a posting tagged as a cost posting,+-- ie one whose cost is represented by equity conversion postings ?+transactionHasCostPostings :: Transaction -> Bool+transactionHasCostPostings = any (postingHasTag costPostingTagName) . tpostings++-- | Does this posting carry a cost basis annotation that was copied into it+-- by the transaction balancer, rather than written by the user ?+-- True when the posting's amount was wholly inferred (its original had no+-- amount) yet carries a cost basis annotation: the balancer fills elided+-- postings with the negated sum of the other postings' amounts, and any+-- basis annotation rides along incidentally.+--+-- Such an annotation is not a lot selector - a cost basis annotation is+-- posting-specific user intent - but we deliberately keep it until lot+-- classification has run, when it identifies the elided destination or+-- source of a lot transfer (see 'isMirroredTransferCandidate' - the+-- mirrored posting of eg @stocks -5 AAPL {$50} / cash@ could equally be+-- the artifact of a sale missing its price, but the dispose reading would+-- fail for lack of a price, so the transfer reading is preferred).+-- Mirrored postings which can't be a transfer counterpart stay+-- unclassified and invisible to counterpart detection; afterwards+-- 'journalStripBalancerCopiedBases' removes their annotations, so+-- downstream code and reports only ever see user-written or+-- lot-machinery-derived cost bases.+hasBalancerCopiedBasis :: Posting -> Bool+hasBalancerCopiedBasis p =+ not (hasAmount (originalPosting p)) && any (isJust . acostbasis) (amountsRaw (pamount p))++-- | Remove balancer-copied cost basis annotations (see+-- 'hasBalancerCopiedBasis') from postings that lot classification left+-- unclassified, now that lot processing has used them as evidence.+-- Lot-processed (classified) postings are left alone: lot calculation+-- legitimately gives machinery-derived cost bases to postings whose amounts+-- were inferred, eg the per-lot fragments of an elided transfer source.+journalStripBalancerCopiedBases :: Journal -> Journal+journalStripBalancerCopiedBases = journalMapPostings strip+ where+ strip p+ | hasBalancerCopiedBasis p && not (isClassifiedPosting p) =+ p{pamount = mapMixedAmount (\a -> a{acostbasis = Nothing}) (pamount p)}+ | otherwise = p++-- | True if this posting involves a lotful commodity in an asset account+-- but has no _ptype tag (wasn't classified as acquire/dispose/transfer/gain).+-- Postings with zero amount in the lotful commodity are exempt (no lot tracking needed).+isUnclassifiedLotfulPosting :: Journal -> Posting -> Bool+isUnclassifiedLotfulPosting j p =+ isReal p+ && hasAmount p+ && not (isLotPosting p)+ && isJust (journalLotDirection j (paccount p)) -- an asset or liability account+ -- lots: NONE accounts' postings are exempt (not lot-tracked).+ && not (journalAccountUsesNoLots j (lotBaseAccount (paccount p)))+ && hasNonzeroLotfulAmount+ -- Postings with balancer-copied basis annotations are deliberately left+ -- unclassified (see 'hasBalancerCopiedBasis'); the posting they mirror+ -- produces the relevant error.+ && not (hasBalancerCopiedBasis p)+ where+ lotfulAmts = filter (journalCommodityUsesLots j . acommodity) (amountsRaw (pamount p))+ -- Flag only when the lotful commodity itself has nonzero quantity.+ hasNonzeroLotfulAmount = any ((/= 0) . aquantity) lotfulAmts++-- | Build an error message for an unclassified lotful posting.+-- Takes the transaction and the 0-based posting index for precise source location.+-- The excerpt shows the transaction as the user wrote it: postings are+-- reverted to their original (parse time) form and generated postings are+-- dropped, so it matches the journal file rather than the processed+-- in-memory entry (#2686). When the problem posting's amount was inferred+-- (and so is not visible in the excerpt), it is mentioned in the message.+unclassifiedLotWarning :: Journal -> Transaction -> Int -> Posting -> String+unclassifiedLotWarning j t idx p =+ let amts = amountsRaw (pamount p)+ lotfulCommodities = [acommodity a | a <- amts, journalCommodityUsesLots j (acommodity a)]+ source = case lotfulCommodities of+ (c:_) -> T.unpack c ++ " is declared lotful (commodity lots: tag)"+ [] -> "this posting involves a lotful commodity"+ inferrednote = if hasAmount (originalPosting p) then "" else+ " (with inferred amount " ++ showMixedAmountOneLine (pamount p) ++ ")"+ (f, line, _, ex) = makePostingErrorExcerptByIndex (transactionAsWritten t) (asWrittenPostingIndex t idx) Nothing+ shortnote+ | journalLotDirection j (paccount p) == Just Short =+ "\n(Liability accounts hold short positions, and transferring those between\n"+ ++ "accounts is not supported yet: cover the position in one account and\n"+ ++ "open it in the other, with prices.)"+ | otherwise = ""+ in printf "%s:%d:\n%s\n" f line ex+ ++ source ++ " but this posting" ++ inferrednote ++ " was not classified as\n"+ ++ "acquire, dispose, or transfer. Lot state will not be updated.\n"+ ++ "Possible fixes: add a cost basis ({$X}), a price (@ $X),\n"+ ++ "or check the account type declaration."+ ++ shortnote++-- Validation and label generation++-- | Validate that user-provided labels don't create duplicate lot ids.+validateUserLabels :: [Transaction] -> Either String ()+validateUserLabels txns =+ case M.toList duplicates of+ [] -> Right ()+ (((c, d, l), t2:_):_) ->+ let (f, line, _, ex) = makeTransactionErrorExcerpt t2 (const Nothing)+ in Left $ printf (unlines [+ "%s:%d:"+ ,"%s"+ ,"lot id is not unique: commodity %s, date %s, label \"%s\""+ ]) f line ex (T.unpack c) (show d) (T.unpack l)+ _ -> Right () -- shouldn't happen+ where+ labeled = [ ((acommodity a, getLotDate t cb, l), t)+ | t <- txns+ , p <- tpostings t+ , isAcquirePosting p+ , a <- amountsRaw (pamount p)+ , Just cb <- [acostbasis a]+ , Just l <- [cbLabel cb]+ ]+ txnsByKey = foldl' (\m (k, t) -> M.insertWith (++) k [t] m) M.empty labeled+ duplicates = M.filter (\ts -> length ts > 1) txnsByKey++-- | Find (commodity, date) pairs where there are multiple unlabeled+-- acquisitions, and thus need auto-generated labels to disambiguate.+-- Acquisitions with a user-provided label are already unique by that label,+-- so they don't force unlabeled siblings on the same date to be labelled.+-- (Duplicate user labels on the same date are caught later by the+-- duplicate-lot-id check in 'processAcquirePosting'.)+-- Bare acquire postings (no acostbasis) use the transaction date.+findDatesNeedingLabels :: [Transaction] -> S.Set (CommoditySymbol, Day)+findDatesNeedingLabels txns =+ M.keysSet $ M.filter (> 1) counts+ where+ counts = foldl' countAcquire M.empty+ [ (acommodity a, acquireDate t a)+ | t <- txns+ , p <- tpostings t+ , isAcquirePosting p+ , a <- amountsRaw (pamount p)+ , isNothing (acostbasis a >>= cbLabel) -- only count unlabeled+ ]+ countAcquire m (c, d) = M.insertWith (+) (c, d) (1 :: Int) m+ acquireDate t a = case acostbasis a of+ Just cb -> getLotDate t cb+ Nothing -> tdate t++-- | Revert a transaction to (approximately) the form the user wrote, for+-- error display: postings are reverted to their original parse-time form,+-- and generated postings are dropped. This keeps error excerpts looking+-- like the journal file rather than the processed in-memory entry (#2686).+transactionAsWritten :: Transaction -> Transaction+transactionAsWritten t =+ t{tpostings = [originalPosting q | q <- tpostings t, not (isGeneratedPosting q)]}++-- | Map a 0-based index into a transaction's postings to the corresponding+-- index in the 'transactionAsWritten' form (which omits generated postings).+asWrittenPostingIndex :: Transaction -> Int -> Int+asWrittenPostingIndex t idx = length [() | q <- take idx (tpostings t), not (isGeneratedPosting q)]++-- | True if this posting was generated by processing (has the _generated-posting tag).+isGeneratedPosting :: Posting -> Bool+isGeneratedPosting = postingHasTag generatedPostingTagName++-- | A one-line summary of how lot classification read a transaction's+-- postings, to include at the end of error messages about it (see 'appendPostingsReadAs'):+-- each non-generated posting's classification ("_ptype" tag value, or+-- "unclassified") in posting order, plus a count of any generated postings.+-- Returns "" when classification hasn't run yet (no posting has a ptype+-- tag), eg for errors raised at earlier pipeline stages.+-- The excerpt always shows what the user wrote; this line shows how+-- hledger interpreted it, since the interpretation (and any error arising+-- from it) may not be obvious from the entry alone.+postingsReadAs :: Transaction -> String+postingsReadAs t+ | not (any isClassifiedPosting ps) = ""+ | otherwise =+ "Postings were read as: " ++ intercalate ", " (map readAs written)+ ++ (case generated of+ [] -> ""+ gs -> "; and generated: " ++ intercalate ", " (map readAs gs))+ ++ "."+ where+ ps = tpostings t+ (generated, written) = partition isGeneratedPosting ps+ readAs p = case lookup "_ptype" (ptags p) of+ Just ptype -> T.unpack ptype+ Nothing | postingHasTag lotParentAssertionTagName p -> "balance-assertion"+ | otherwise -> "unclassified"++-- | Append a summary of how a transaction's postings were classified ('postingsReadAs'),+-- if they were, as the last line of a lot error message about that transaction.+-- (It goes last, so the explanation comes first, eg as the first line of a flycheck message.)+appendPostingsReadAs :: Transaction -> String -> String+appendPostingsReadAs t msg = case postingsReadAs t of+ "" -> msg+ r -> dropWhileEnd (== '\n') msg ++ "\n\n" ++ r++-- | Format a verbose error prefix for a transaction: "file:line:\nexcerpt\n\n".+-- Prepend to an error message to show source position and a transaction excerpt,+-- rendered as the user wrote it ('transactionAsWritten').+txnErrPrefix :: Transaction -> String+txnErrPrefix t = printf "%s:%d:\n%s\n" f line ex+ where (f, line, _, ex) = makeTransactionErrorExcerpt (transactionAsWritten t) (const Nothing)++-- | Format a verbose error prefix for a posting: "file:line:\nexcerpt\n\n",+-- like 'txnErrPrefix', but marking the+-- specific posting's line, found by comparing cost-stripped postings+-- (falling back to the transaction line if the posting can't be identified).+postingErrPrefix :: Posting -> String+postingErrPrefix p = case ptransaction p of+ Nothing -> printf "%s:%d:\n%s\n" ("-"::String) (0::Int) (""::Text)+ Just t -> case transactionFindPostingIndex ((== postingStripCosts p) . postingStripCosts) t of+ Nothing -> txnErrPrefix t+ Just i1 -> postingAtErrPrefix t (i1-1)++-- | Like 'postingErrPrefix', for the posting at this (0-based) index in the transaction.+postingAtErrPrefix :: Transaction -> Int -> String+postingAtErrPrefix t i = printf "%s:%d:\n%s\n" f line ex+ where (f, line, _, ex) = makePostingErrorExcerptByIndex (transactionAsWritten t) (asWrittenPostingIndex t i) Nothing++-- | Emit a dbg5 trace for a lot operation: "lots: FILE:LINE DATE DESC: message".+lotDbg :: Transaction -> String -> a -> a+lotDbg t msg = dbg5With (\_ -> "lots: " ++ txnDbgPrefix t ++ ": " ++ msg)++-- | Format a one-line transaction summary for debug traces: "FILE:LINE DATE DESC".+txnDbgPrefix :: Transaction -> String+txnDbgPrefix t = printf "%s:%d %s %s" f line (show (tdate t)) (T.unpack (tdescription t))+ where (f, line, _, _) = makeTransactionErrorExcerpt t (const Nothing)++-- | Get the lot date from cost basis, falling back to the transaction date.+getLotDate :: Transaction -> CostBasis -> Day+getLotDate t cb = fromMaybe (tdate t) (cbDate cb)++-- | Generate a label for a lot that needs one (due to same-date collision).+-- Uses the smallest sequence number, formatted as four (or more) digits+-- ("0001", "0002", ...), that isn't already a label of an existing same-date+-- lot. Skipping used numbers avoids colliding with user-provided labels+-- that happen to be in the same format. Fully disposed lots remain visible+-- here as tombstones (see 'reduceLotState'), so their labels are not reused.+generateLabel :: CommoditySymbol -> Day -> LotState -> T.Text+generateLabel commodity date lotState = nextFree 1+ where+ existingLots = M.findWithDefault M.empty commodity lotState+ -- Use takeWhileAntitone/dropWhileAntitone for O(log n) range extraction.+ -- LotId is ordered by date first, so same-date lots form a contiguous range.+ sameDate = M.takeWhileAntitone (\(LotId d _) -> d == date)+ $ M.dropWhileAntitone (\(LotId d _) -> d < date) existingLots+ usedLabels = S.fromList $ mapMaybe (\(LotId _ ml) -> ml) (M.keys sameDate)+ nextFree :: Int -> T.Text+ nextFree n =+ let l = T.pack (printf "%04d" n)+ in if S.notMember l usedLabels then l else nextFree (n + 1)++-- Transaction dispatch++-- | Process a single transaction: transform its acquire, dispose, and transfer postings.+-- Transfer pairs are processed first (so that transferred lots are available for+-- subsequent disposals in the same transaction), then acquire and dispose postings.+-- Accumulates (LotState, [Transaction]) — transactions in reverse order.+processTransaction :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> S.Set (CommoditySymbol, Day) -> (LotState, [Transaction]) -> Transaction+ -> Either String (LotState, [Transaction])+processTransaction styles verbosetags j needsLabels (ls, acc) t = do+ -- Partition postings into transfer pairs and others+ let (transferFroms, transferTos, otherPs) = partitionTransferPostings (tpostings t)+ hasEquityOther = any (isEquityPosting j) otherPs+ -- Closing equity transfer: transfer-from postings with no transfer-to counterpart,+ -- where an equity posting receives the lots (e.g. close --clopen --lots).+ -- Reduce lots from state, and rewrite each transfer-from posting onto the+ -- selected lots' subaccounts; pass other postings through unchanged (equity does not track lots).+ if not (null transferFroms) && null transferTos && hasEquityOther+ then do+ (ls', allPsR) <- foldM (\(st, qs) p ->+ if isTransferFromPosting p+ then do+ (st', ps') <- reduceLotTransferToEquity styles verbosetags j t st p+ return (st', reverse ps' ++ qs)+ else return (st, p : qs)+ ) (ls, []) (tpostings t)+ return (ls', t{tpostings = reverse allPsR} : acc)+ -- Opening equity transfer: transfer-to postings with no transfer-from counterpart,+ -- where an equity posting is the source (e.g. opening balances from close --clopen --lots).+ -- Process transfer-to postings as acquires to add lots to the state.+ else if null transferFroms && not (null transferTos) && hasEquityOther+ then do+ -- Build map of processed transfer-to postings, then reconstruct in original order.+ let indexedTos = [(i, p) | (i, p) <- zip [0..] (tpostings t), isTransferToPosting p]+ (ls', toMap) <- foldM (\(st, m) (i, p) -> do+ (st', p') <- processAcquirePosting styles j needsLabels txnDate t st i p+ return (st', M.insert i p' m)+ ) (ls, M.empty) indexedTos+ let allPs = [maybe p id (M.lookup i toMap) | (i, p) <- zip [0..] (tpostings t)]+ return (ls', t{tpostings = allPs} : acc)+ else do+ let indexedFroms = [(i, p) | (i, p) <- zip [0..] (tpostings t), isTransferFromPosting p]+ indexedTos = [(i, p) | (i, p) <- zip [0..] (tpostings t), isTransferToPosting p]+ -- Fee-split dispose postings, which are by construction in the+ -- transfer source account (where the lots already exist).+ indexedFeeDisposes =+ [(i, p) | (i, p) <- zip [0..] (tpostings t)+ , isDisposePosting p, postingHasTag feesplitPostingTagName p]+ -- Process fee-split disposes before the transfer pairs, so the+ -- disposal method in effect (FIFO, LIFO, ...) selects from the full+ -- pre-transfer lot set - eg under FIFO a transfer fee consumes the+ -- oldest lot - and the transfer carries the remainder. (#2692)+ (ls0, disposeMap) <- foldM processOneFeeDispose (ls, M.empty) indexedFeeDisposes+ groups <- groupIndexedTransferPostings t indexedFroms indexedTos+ -- Then walk all postings in original order, processing each transfer+ -- group when its first posting is reached, and substituting expanded results.+ let groupsByFirst = M.fromList [(i, g) | g@(_, ifroms, itos) <- groups, i <- take 1 (sort (map fst (ifroms ++ itos)))]+ (ls'', allPs) <- foldMPostings ls0 [] (zip [0..] (tpostings t)) disposeMap groupsByFirst+ return (ls'', t{tpostings = reverse allPs} : acc)+ where+ txnDate = tdate t++ -- Process a fee-split dispose posting; record expanded postings keyed by original index.+ processOneFeeDispose (st, m) (i, p) = do+ (st', newPs) <- processDisposePosting styles verbosetags j t st p+ return (st', M.insert i newPs m)++ -- Walk postings in original order, looking up already-processed results,+ -- processing a transfer group when its first posting is reached, or+ -- processing the posting normally.+ foldMPostings :: LotState -> [Posting] -> [(Int, Posting)] -> M.Map Int [Posting] -> M.Map Int (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])+ -> Either String (LotState, [Posting])+ foldMPostings st acc' [] _ _ = Right (st, acc')+ foldMPostings st acc' ips@((i,p):ps) tmap groups+ | Just g <- M.lookup i groups = do+ (st', m') <- processTransferGroup styles verbosetags j t st g+ foldMPostings st' acc' ips (M.union tmap m') (M.delete i groups)+ | Just expanded <- M.lookup i tmap =+ foldMPostings st (reverse expanded ++ acc') ps tmap groups+ | isAcquirePosting p = do+ (st', p') <- processAcquirePosting styles j needsLabels txnDate t st i p+ foldMPostings st' (p':acc') ps tmap groups+ | isDisposePosting p = do+ (st', newPs) <- processDisposePosting styles verbosetags j t st p+ foldMPostings st' (reverse newPs ++ acc') ps tmap groups+ | isUnclassifiedLotfulPosting j p =+ Left (unclassifiedLotWarning j t i p)+ | otherwise =+ foldMPostings st (p:acc') ps tmap groups++-- | True if the posting is in an equity account.+isEquityPosting :: Journal -> Posting -> Bool+isEquityPosting j p = maybe False isEquityType (journalAccountType j (lotBaseAccount (paccount p)))++-- | Reduce lots from the lot state for a transfer-from posting going to an equity account.+-- Used when lots are transferred to equity (e.g. close --clopen --lots): reduces the lots+-- without requiring a matching transfer-to posting, since equity does not track lots.+-- Like a paired transfer's source, the posting is rewritten onto the full name(s)+-- of the lot(s) it selects, so that account balances agree with the lot state+-- even when it was written with a partial lot subaccount name (eg without a label).+reduceLotTransferToEquity :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState -> Posting+ -> Either String (LotState, [Posting])+reduceLotTransferToEquity styles verbosetags j t ls p =+ case [(a, cb) | a <- amountsRaw (pamount p), Just cb <- [acostbasis a], isLotOutflow dir a] of+ [(a, cb)] -> do+ let commodity = acommodity a+ qty = abs (aquantity a)+ acct = lotBaseAccount (paccount p)+ (method, methodSource) = resolveReductionMethodWithSource j p commodity+ selected <- selectLots (method, methodSource) (postingErrPrefix p) "transfer" (tdate t) dir acct commodity qty cb+ (lotStateForDirection j dir commodity ls)+ ps <- mapM (mkLotPosting acct a method) selected+ let consumed = [(lotId, qty') | (lotId, _, qty') <- selected]+ ps' = case ps of+ [_] -> ps+ _ -> map (postingAddHiddenAndMaybeVisibleTag False verbosetags (lotsplitPostingTagName, "")) ps+ return $ lotDbg t ("equity-transfer " ++ show qty ++ " " ++ T.unpack commodity+ ++ " from " ++ T.unpack acct+ ++ " (lots: " ++ showSelectedLots selected ++ ")")+ (reduceLotState acct commodity consumed ls+ ,preserveParentAssertion verbosetags (paccount p) (pbalanceassertion p) ps')+ _ -> Right (ls, [p]) -- no single lot amount (e.g. cash posting): pass through+ where+ -- a liability account's short lots are sent to equity by a positive posting+ dir = journalLotDirectionOrLong j (paccount p)+ mkLotPosting acct a method (lotId, storedAmt, qty) = case acostbasis storedAmt >>= cbCost of+ Nothing -> Left $ txnErrPrefix t ++ "lot " ++ show lotId+ ++ " for commodity " ++ T.unpack (acommodity a)+ ++ " has no cost basis (internal error)"+ Just c ->+ let lotCb = CostBasis{cbDate = Just (lotDate lotId), cbLabel = lotLabel lotId, cbCost = Just c}+ lotName = showLotNameForMethod method (styleLotCbCost styles lotCb)+ in Right p{ paccount = acct <> ":" <> lotName+ , pamount = mixedAmount (amountSetQuantity (negate (lotDirectionSign dir) * qty) a){acostbasis = Just lotCb}+ , poriginal = Just (originalPosting p)+ }++-- | Partition a transaction's postings into transfer-from, transfer-to, and others.+partitionTransferPostings :: [Posting] -> ([Posting], [Posting], [Posting])+partitionTransferPostings = go [] [] []+ where+ go froms tos others [] = (reverse froms, reverse tos, reverse others)+ go froms tos others (p:ps)+ | isTransferFromPosting p = go (p:froms) tos others ps+ | isTransferToPosting p = go froms (p:tos) others ps+ | otherwise = go froms tos (p:others) ps++-- | Group indexed transfer-from and transfer-to postings by commodity, and+-- check each group's consistency: both sides present, and total from/to+-- quantities equal (#2692). Transfer postings need not pair up one to one:+-- one source posting can feed several destinations, or several sources one+-- destination, as long as the totals match. Within each group, froms and+-- tos are sorted by cost basis fields (date, label, cost) so explicit+-- per-lot annotations align. Cost basis mismatches are caught later by+-- validation, not here.+groupIndexedTransferPostings :: Transaction -> [(Int, Posting)] -> [(Int, Posting)]+ -> Either String [(CommoditySymbol, [(Int, Posting)], [(Int, Posting)])]+groupIndexedTransferPostings _ [] [] = Right []+groupIndexedTransferPostings t froms tos = do+ fromGroups <- groupByCommodity "transfer-from" froms+ toGroups <- groupByCommodity "transfer-to" tos+ let allComms = S.union (M.keysSet fromGroups) (M.keysSet toGroups)+ mapM (checkCommodityGroup fromGroups toGroups) (S.toList allComms)+ where+ showPos = txnErrPrefix t++ -- Group indexed postings by their lotful commodity.+ groupByCommodity :: String -> [(Int, Posting)] -> Either String (M.Map CommoditySymbol [(Int, Posting)])+ groupByCommodity label ips = do+ tagged <- mapM (\ip -> (,ip) <$> postingCommodity label ip) ips+ Right $ M.map reverse $ M.fromListWith (++) [(c, [ip]) | (c, ip) <- tagged]++ postingCommodity :: String -> (Int, Posting) -> Either String CommoditySymbol+ postingCommodity label (i, p) =+ case [acommodity a | a <- amountsRaw (pamount p), isJust (acostbasis a)] of+ [c] -> Right c+ -- Transfer-to postings without {} have no cost basis; use the raw commodity.+ _ -> case [acommodity a | a <- amountsRaw (pamount p)] of+ [c] -> Right c+ _ -> Left $ postingAtErrPrefix t i+ ++ "This " ++ label ++ " posting has amounts in several commodities ("+ ++ showMixedAmountOneLine (pamount p) ++ ").\n"+ ++ "In a lot transfer, each posting should have just one commodity;\n"+ ++ "please write these amounts on separate postings."++ -- Sort key for aligning explicit per-lot annotations within a commodity group.+ postingSortKey :: (Int, Posting) -> (Maybe Day, Maybe T.Text, Maybe (CommoditySymbol, Quantity))+ postingSortKey (_, p) =+ case [cb | a <- amountsRaw (pamount p), Just cb <- [acostbasis a]] of+ [cb] -> (cbDate cb, cbLabel cb,+ fmap (\a -> (acommodity a, aquantity a)) (cbCost cb))+ _ -> (Nothing, Nothing, Nothing)++ checkCommodityGroup fromGroups toGroups comm = do+ let fs = M.findWithDefault [] comm fromGroups+ ts = M.findWithDefault [] comm toGroups+ case (fs, ts) of+ ([], _) -> Left $ showPos ++ "transfer-to posting for " ++ T.unpack comm+ ++ " has no matching transfer-from posting"+ (_, []) -> Left $ showPos ++ "transfer-from posting for " ++ T.unpack comm+ ++ " has no matching transfer-to posting"+ _ -> do+ -- The total from/to quantities must agree; a difference indicates an+ -- analysis failure or an unrecorded fee (#2692). (Transfer fees+ -- should be recorded as their own posting(s) in the same commodity;+ -- hledger then splits off matching disposal(s) automatically.)+ let qtyTotal ips = sum [ abs (aquantity a)+ | (_, p) <- ips, a <- amountsRaw (pamount p)+ , acommodity a == comm ]+ fromTotal = qtyTotal fs+ toTotal = qtyTotal ts+ when (fromTotal /= toTotal) $+ Left $ showPos ++ "Mismatched transfer quantities for lot-tracked commodity " ++ T.unpack comm+ ++ ": " ++ show fromTotal ++ " transferred out but "+ ++ show toTotal ++ " received.\n"+ ++ if toTotal > fromTotal+ then "More was received than sent, which a fee can't explain;\n"+ ++ "check the entry for sign errors or rounding adjustments."+ else "If the difference is a fee, you can either\n"+ ++ "- record the fee expense in the lot-tracked commodity, with posting(s)\n"+ ++ " adding up to the missing quantity\n"+ ++ "- or split the sending posting into a transfer part and fee part(s)\n"+ ++ " matching the fee expense(s)."+ Right (comm, sortOn postingSortKey fs, sortOn postingSortKey ts)++-- | Extract a per-unit cost Amount from an AmountCost, normalising TotalCost by quantity.+-- (A TotalCost carries the amount's sign, so dividing by the signed quantity+-- gives a positive unit cost for a negative posting too.)+-- If quantity is zero, returns the TotalCost amount as-is (avoiding division by zero).+-- Uses 'divideAmountAndUpdatePrecision' so the derived unit cost renders with the+-- quotient's digits rather than inheriting the total cost's narrower display style.+amountCostToUnitCost :: Quantity -> AmountCost -> Amount+amountCostToUnitCost _ (UnitCost c) = c+amountCostToUnitCost qty (TotalCost c) = divideAmountAndUpdatePrecision qty c++-- | Normalize an amount's transacted cost to UnitCost form (converting TotalCost by dividing by quantity).+-- Returns Nothing if the amount has no transacted cost.+amountNormalizeCostToUnit :: Amount -> Maybe AmountCost+amountNormalizeCostToUnit a = fmap (UnitCost . amountCostToUnitCost (aquantity a)) (acost a)+++-- Per-type posting processing++-- | Process a single acquire posting (at this index in the transaction): generate a lot name and append it as a subaccount.+processAcquirePosting :: M.Map CommoditySymbol AmountStyle -> Journal -> S.Set (CommoditySymbol, Day) -> Day -> Transaction -> LotState -> Int -> Posting+ -> Either String (LotState, Posting)+processAcquirePosting styles j needsLabels txnDate t lotState idx p = do+ let lotAmts = [(a, cb) | a <- amountsRaw (pamount p), Just cb <- [acostbasis a]]+ -- Long (asset) accounts' lots are opened by positive postings,+ -- Short (liability) accounts' by negative ones.+ dir = journalLotDirectionOrLong j (paccount p)+ (lotAmt, cb, isBare) <- case lotAmts of+ [x] -> Right (fst x, snd x, False)+ _ -> do+ let bareAmts = [a | a <- amountsRaw (pamount p), not (isLotOutflow dir a)]+ case bareAmts of+ [a] -> Right (a, CostBasis Nothing Nothing Nothing, True)+ _ -> Left $ postingAtErrPrefix t idx ++ "acquire posting has no cost basis"++ let commodity = acommodity lotAmt+ date = fromMaybe txnDate (cbDate cb)++ -- Get the original (pre-balancing) amount to check for explicit transacted price.+ -- A unit cost on the original can be used directly as the cost basis;+ -- a total cost on the balanced amount is normalised to a per-unit cost basis.+ let origAmt = case poriginal p of+ Just orig -> case [a | a <- amountsRaw (pamount orig), acommodity a == commodity] of+ (a:_) -> a+ [] -> lotAmt+ Nothing -> lotAmt++ let maybeLotBasis = case cbCost cb of+ Just c -> Just c+ Nothing+ | Just (UnitCost c) <- acost origAmt -> Just c+ | Just cost <- acost lotAmt -> Just $ amountCostToUnitCost (aquantity lotAmt) cost+ | otherwise -> Nothing++ case maybeLotBasis of+ Nothing | isBare -> Left $ postingAtErrPrefix t idx ++ T.unpack commodity+ ++ " is lotful but this acquire posting has no cost basis or price.\n"+ ++ "No lot will be created."+ | otherwise -> Left $ postingAtErrPrefix t idx+ ++ "This posting creates a new " ++ T.unpack commodity ++ " lot, but its lot annotation "+ ++ T.unpack (showLotName cb) ++ " has no cost,\n"+ ++ "and there is no price (@ or @@) to infer one from.\n"+ ++ "Please add a per-unit cost to the annotation, eg " ++ withExampleCost (showLotName cb) ++ "."+ Just lotBasis -> do+ let cbInferred = isNothing (cbCost cb)+ needsLabel = S.member (commodity, date) needsLabels+ lotLabel' = cbLabel cb <|> if needsLabel then Just (generateLabel commodity date lotState) else Nothing+ -- If the lot id already exists (e.g. an equity transfer-to on the same date+ -- as a regular acquire, not predicted by findDatesNeedingLabels), auto-generate+ -- a label to disambiguate.+ existingLots = M.findWithDefault M.empty commodity lotState+ lotId0 = LotId date lotLabel'+ (lotId, lotLabel'')+ | isNothing (cbLabel cb) && M.member lotId0 existingLots+ = let l = generateLabel commodity date lotState+ in (LotId date (Just l), Just l)+ | otherwise = (lotId0, lotLabel')+ baseAcct = lotBaseAccount (paccount p)+ (method, _methodSource) = resolveReductionMethodWithSource j p commodity+ -- AVERAGEALL pools all same-direction accounts' lots, AVERAGE this account's.+ inPool acct | methodIsGlobal method = journalLotDirectionOrLong j acct == dir+ | otherwise = acct == baseAcct++ -- Under AVERAGE/AVERAGEALL, merge this acquisition into the running pool+ -- (returns the new shared per-unit cost and an updated LotState where+ -- every existing pool lot's cbCost has been rewritten to that new cost).+ (lotBasisStored, lotState0) <-+ if methodIsAverage method+ then updatePoolOnAcquire (postingAtErrPrefix t idx) inPool+ commodity (abs (aquantity lotAmt)) lotBasis lotState+ else Right (lotBasis, lotState)++ let -- For an inferred cost, widen precision to the commodity style's+ -- declared minimum (eg 2.5 -> 2.50 with 'commodity €1.00'); for+ -- a user-written explicit cost, preserve their formatting.+ widenIfInferred = if cbInferred then widenLotCbCost styles else id+ -- The stored cost basis is styled/widened the same way as the lot+ -- subaccount name, so that later renderings of this lot's name+ -- (on dispose and transfer postings) match the acquire's.+ fullCb = widenIfInferred $ styleLotCbCost styles+ CostBasis{cbDate = Just date, cbLabel = lotLabel'', cbCost = Just lotBasisStored}+ lotName = showLotNameForMethod method fullCb+ -- When cost basis was inferred, fill it in on the user's original cb+ -- so that print shows {$50} not {}. Style it the same way as the+ -- lot subaccount name.+ filledCb = widenIfInferred $ styleLotCbCost styles cb{cbCost = Just lotBasis}+ -- The lot state stores the full cost basis (date/label/cost).+ -- Under AVERAGE this is the running pool cost; under other methods+ -- it is the original per-acquisition cost.+ -- Lot quantities are stored unsigned (a short lot's posting is+ -- negative; the account's direction supplies the sign).+ lotStateAmt = lotAmt{aquantity = abs (aquantity lotAmt), acostbasis = Just fullCb}+ -- The displayed posting amount preserves the user's literal cost+ -- annotation (filling in only when they wrote `{}`). Under AVERAGE+ -- the running pool cost is a derived state — surfaced via bal -B+ -- and visible on disposal postings (where the user wrote `{}`+ -- and the system fills in the lot's stored cost).+ postingAmt = if cbInferred then lotAmt{acostbasis = Just filledCb} else lotAmt++ let hasExplicitLotAcct = baseAcct /= paccount p+ expectedAcct = baseAcct <> ":" <> lotName++ -- If the user wrote an explicit lot subaccount, check that its parsed+ -- CostBasis is compatible with the resolved lot's.+ when hasExplicitLotAcct $+ case mergeCostBasisForMethod method cb fullCb of+ Right _ -> Right ()+ Left _ -> Left $ postingAtErrPrefix t idx ++ "lot subaccount " ++ T.unpack (paccount p)+ ++ " does not match the resolved lot " ++ T.unpack expectedAcct++ -- Only a live lot (with account entries) is a duplicate; a tombstone+ -- (fully disposed lot, see 'reduceLotState') may be revived by an+ -- explicitly-labelled acquisition, eg re-opening balances after+ -- close --clopen --lots.+ when (maybe False (not . M.null) (M.lookup lotId existingLots)) $+ Left $ postingAtErrPrefix t idx ++ "duplicate lot id: " ++ T.unpack lotName+ ++ " for commodity " ++ T.unpack commodity++ let p' = p{paccount = expectedAcct+ ,pamount = mixedAmount postingAmt+ ,poriginal = Just (originalPosting p)}+ let lotState' = addLotState commodity lotId baseAcct lotStateAmt lotState0+ return $ lotDbg t ("acquired " ++ show (aquantity lotAmt) ++ " "+ ++ T.unpack commodity ++ " " ++ T.unpack lotName+ ++ " on " ++ T.unpack baseAcct)+ (lotState', p')+ where+ -- A lot name with an example cost added (cost is shown last), eg {2026-01-01} -> {2026-01-01, $50}.+ withExampleCost name+ | name == "{}" = "{$50}"+ | otherwise = T.unpack (T.dropEnd 1 name) ++ ", $50}"++-- | Process a dispose posting: match to existing lots using the resolved reduction method,+-- split into multiple postings if the disposal spans multiple lots.+-- Returns the list of resulting postings (one per matched lot).+processDisposePosting :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState -> Posting+ -> Either String (LotState, [Posting])+processDisposePosting styles verbosetags j t lotState p = do+ -- Extract lotful amount and lot selector. When cost basis is present, use it directly.+ -- When absent (bare dispose on a lotful commodity), use a wildcard selector.+ let lotAmts = [(a, cb) | a <- amountsRaw (pamount p), Just cb <- [acostbasis a]]+ -- Long (asset) accounts' lots are closed by negative postings,+ -- Short (liability) accounts' by positive ones (covering a short).+ dir = journalLotDirectionOrLong j (paccount p)+ -- The sign of this posting's lot-closing quantities.+ closesign = negate (lotDirectionSign dir)+ (lotAmt, cb, isBare) <- case lotAmts of+ [x] -> Right (fst x, snd x, False)+ _ -> do+ let bareAmts = [a | a <- amountsRaw (pamount p), isLotOutflow dir a]+ case bareAmts of+ [a] -> Right (a, CostBasis Nothing Nothing Nothing, True)+ _ -> Left $ showPos ++ "dispose posting has no cost basis"++ let commodity = acommodity lotAmt++ -- Non-bare dispose (explicit {}) without price is an error - unless the+ -- entry's non-lot-account postings (not asset or liability) receive the+ -- same commodity in the same total quantity as its priceless disposals+ -- (an in-kind outflow: a transfer fee, a donation, etc): then it+ -- proceeds as a priceless disposal, like a bare one, with no gain+ -- calculated. This also lets print --lots output of unpriced-fee+ -- transfers (whose fee dispose fragment carries an explicit lot+ -- reference) round-trip (#2692).+ -- Bare dispose without price proceeds to lot matching (but skips gain generation).+ let holdsLots acct = isJust (journalLotDirection j acct)+ nonLotAccountReceipts = sum [ aquantity a+ | q <- tpostings t, not (holdsLots (paccount q))+ , a <- amountsRaw (pamount q)+ , acommodity a == commodity, aquantity a > 0 ]+ pricelessDisposals = sum [ negate (aquantity a)+ | q <- tpostings t, isDisposePosting q+ , a <- amountsRaw (pamount q)+ , acommodity a == commodity, aquantity a < 0, isNothing (acost a) ]+ isInKindOutflow = nonLotAccountReceipts > 0 && nonLotAccountReceipts == pricelessDisposals+ case acost lotAmt of+ Nothing | not isBare && not isInKindOutflow ->+ Left $ showPos ++ "dispose posting has no transacted price ("+ ++ (if dir == Short then "buying price, to cover the short" else "selling price")+ ++ ") for " ++ T.unpack commodity+ _ -> do++ unless (isLotOutflow dir lotAmt) $+ Left $ showPos ++ "dispose posting has "+ ++ (if dir == Short then "non-positive quantity (a short position is covered by a positive posting)"+ else "non-negative quantity")+ ++ " for " ++ T.unpack commodity++ let posQty = abs (aquantity lotAmt)+ (method, methodSource) = resolveReductionMethodWithSource j p commodity+ -- All methods are per-account, scoped to the posting's base account+ -- (stripping any explicit lot subaccount the user may have written).+ scopeAcct = lotBaseAccount (paccount p)++ when (isBare && method == SPECID) $+ Left $ showPos ++ "SPECID requires a lot selector on dispose postings"+ ++ "\nUsing SPECID (" ++ methodSource ++ ")."++ selected <- selectLots (method, methodSource) (postingErrPrefix p) "disposal" (tdate t) dir scopeAcct commodity posQty cb+ (lotStateForDirection j dir commodity lotState)++ let baseAcct = lotBaseAccount (paccount p)+ hasExplicitLotAcct = baseAcct /= paccount p+ mkPosting (lotId, storedAmt, consumedQty) = do+ -- Under AVERAGE/AVERAGEALL the stored cost is already the running+ -- pool cost (maintained in lock-step on each acquisition); for+ -- other methods it's the per-acquisition cost. Either way, just+ -- read it from the stored lot.+ origBasis <- case acostbasis storedAmt >>= cbCost of+ Just c -> Right c+ Nothing -> Left $ showPos ++ "lot " ++ T.unpack (T.pack (show lotId))+ ++ " for commodity " ++ T.unpack commodity+ ++ " has no cost basis (internal error)"+ let lotCb = CostBasis+ { cbDate = Just (lotDate lotId)+ , cbLabel = lotLabel lotId+ , cbCost = Just origBasis+ }+ lotName = showLotNameForMethod method (styleLotCbCost styles lotCb)+ expectedAcct = baseAcct <> ":" <> lotName+ -- If the user wrote an explicit lot subaccount, check that its+ -- parsed CostBasis is compatible with the resolved lot's.+ when hasExplicitLotAcct $+ case mergeCostBasisForMethod method cb lotCb of+ Right _ -> Right ()+ Left _ -> Left $ showPos ++ "lot subaccount " ++ T.unpack (paccount p)+ ++ " does not match the resolved lot " ++ T.unpack expectedAcct+ let acctWithLot = expectedAcct+ -- Build the dispose amount: the consumed quantity with the+ -- closing sign (negative; positive when covering a short),+ -- keeping the original amount's commodity, style, cost, and cost basis.+ disposeAmt = (amountSetQuantity (closesign * consumedQty) lotAmt){acostbasis = Just lotCb}+ let -- For bare disposes without a price (e.g. fee deductions), keep no cost.+ -- When splitting across multiple lots, normalize TotalCost to UnitCost+ -- (since TotalCost would be wrong for the split quantity) (#2839).+ disposeAmt' | isNothing (acost lotAmt) = disposeAmt{acost = Nothing}+ | length selected > 1 = disposeAmt{acost = amountNormalizeCostToUnit lotAmt}+ | otherwise = disposeAmt+ Right p{ paccount = acctWithLot+ , pamount = mixedAmount disposeAmt'+ , poriginal = Just (originalPosting p)+ }++ newPostings0 <- mapM mkPosting selected+ -- For multi-lot disposals, tag each fragment as a per-lot split so+ -- journalCollapseLotDetail can merge them back to a single posting+ -- (when --lots is off). Single-lot disposals need no tag — they+ -- already represent the user's original posting.+ -- See also [better lot splitting].+ let taggedPostings = case newPostings0 of+ [_] -> newPostings0+ _ -> map (postingAddHiddenAndMaybeVisibleTag False verbosetags (lotsplitPostingTagName, "")) newPostings0+ let consumed = [(lotId, qty) | (lotId, _, qty) <- selected]+ lotState' = reduceLotState scopeAcct commodity consumed lotState+ -- A single-fragment dispose with no other lots remaining for this+ -- commodity on scopeAcct doesn't need the =* parent-assertion+ -- synthetic: the lot subaccount balance equals the parent balance,+ -- so the user's assertion is correct as-is on the single fragment.+ noOtherLots = all (M.notMember scopeAcct) $ M.elems+ $ M.findWithDefault M.empty commodity lotState'+ finalPostings = case taggedPostings of+ [_] | noOtherLots -> taggedPostings+ _ -> preserveParentAssertion verbosetags (paccount p) (pbalanceassertion p) taggedPostings++ return $ lotDbg t ("disposed " ++ show posQty ++ " " ++ T.unpack commodity+ ++ " from " ++ T.unpack scopeAcct+ ++ " (" ++ show method ++ ", lots: " ++ showSelectedLots selected ++ ")")+ (lotState', finalPostings)+ where+ showPos = txnErrPrefix t++-- [better lot splitting]+-- "If you want it bulletproof: the robust fix is a per-call group ID.+-- In processDisposePosting / the transfer caller, mint a small unique tag value +-- (e.g. the source position string of p, or a counter, or T.pack (show (psourcepos p)))+-- and store it on each fragment as (lotsplitPostingTagName, groupId).+-- Then mergeLotSplits groups by tag value, not poriginal equality.+-- That removes the "Eq Posting must include something distinguishing" invariant entirely.++-- | Process one commodity's transfer group: select lots from each source+-- (transfer-from) posting's account, in group order, then distribute the+-- selected lots across the destination (transfer-to) postings in group+-- order, splitting lots at destination boundaries. Sources and destinations+-- need not pair up one to one; the group's total from/to quantities have+-- already been checked equal by 'groupIndexedTransferPostings'.+-- Returns the updated LotState and each original posting index's expanded postings.+processTransferGroup :: M.Map CommoditySymbol AmountStyle -> Bool -> Journal -> Transaction -> LotState+ -> (CommoditySymbol, [(Int, Posting)], [(Int, Posting)])+ -> Either String (LotState, M.Map Int [Posting])+processTransferGroup styles verbosetags j t lotState0 (commodity, ifroms, itos) = do+ -- Select lots for each transfer-from posting, reducing the lot state.+ (lotState1, fromDoneR) <- foldM doFrom (lotState0, []) ifroms+ let fromDone = reverse fromDoneR+ -- All selected lot fragments, in group order, available for distribution.+ queue0 = [ (lotId, storedAmt, qty, fromAmt)+ | (_, _, fromAmt, selected) <- fromDone+ , (lotId, storedAmt, qty) <- selected ]+ -- Distribute the fragments across the transfer-to postings.+ (lotState2, toDoneR, rest) <- foldM doTo (lotState1, [], queue0) itos+ -- The group's totals are equal, so distribution must come out exact.+ unless (null rest) $+ Left $ showPos ++ "could not distribute transferred lots exactly (internal error)"+ fromEntries <- mapM mkFromEntry fromDone+ Right (lotState2, M.fromList (fromEntries ++ reverse toDoneR))+ where+ showPos = txnErrPrefix t++ -- Extract a from posting's lotful amount and lot selector, validate it,+ -- and select the lots it consumes from its account.+ doFrom (st, acc) (i, fromP) = do+ -- When cost basis is present, use it directly as the lot selector.+ -- When absent (bare transfer on a lotful commodity), use a wildcard selector.+ (fromAmt, fromCb) <- case [(a, cb) | a <- amountsRaw (pamount fromP), Just cb <- [acostbasis a]] of+ [x] -> Right x+ _ -> case [a | a <- amountsRaw (pamount fromP), isNegativeAmount a] of+ [a] -> Right (a, CostBasis Nothing Nothing Nothing)+ _ -> Left $ showPos ++ "transfer-from posting has no cost basis"+ checkNoTransactedPrice fromP+ when (aquantity fromAmt >= 0) $+ Left $ showPos ++ "transfer-from posting has non-negative quantity for " ++ T.unpack commodity+ let fromQty = negate (aquantity fromAmt)+ -- Transfers are always per-account (scoped to source), but ordering follows the method.+ (method, methodSource) = resolveReductionMethodWithSource j fromP commodity+ fromBaseAcct = lotBaseAccount (paccount fromP)+ selected <- selectLots (method, methodSource) (postingErrPrefix fromP) "transfer" (tdate t) Long fromBaseAcct commodity fromQty fromCb+ (lotStateForDirection j Long commodity st)+ let st' = reduceLotState fromBaseAcct commodity [(lid, qty) | (lid, _, qty) <- selected] st+ return $ lotDbg t ("transferred out " ++ show fromQty ++ " " ++ T.unpack commodity+ ++ " from " ++ T.unpack fromBaseAcct+ ++ " (lots: " ++ showSelectedLots selected ++ ")")+ (st', (i, fromP, fromAmt, selected) : acc)++ -- Generate a from posting's per-lot display fragments.+ mkFromEntry (i, fromP, fromAmt, selected) = do+ ps <- mapM mk selected+ Right (i, preserveParentAssertion verbosetags (paccount fromP) (pbalanceassertion fromP) (tagIfMulti ps))+ where+ mk (lotId, storedAmt, qty) = do+ lotCb <- lotCbOf lotId storedAmt+ let (fromMethod, _) = resolveReductionMethodWithSource j fromP commodity+ lotName = showLotNameForMethod fromMethod (styleLotCbCost styles lotCb)+ -- Use base accounts to avoid double-appending lot subaccounts.+ fromAcct = lotBaseAccount (paccount fromP) <> ":" <> lotName+ fromAmt' = (amountSetQuantity (negate qty) fromAmt){acostbasis = Just lotCb}+ -- poriginal preserves the user's original annotations, unmodified.+ Right fromP{ paccount = fromAcct+ , pamount = mixedAmount fromAmt'+ , poriginal = Just (originalPosting fromP)+ }++ -- Give a to posting its share of the selected lot fragments, generating+ -- its display fragments and re-adding the lots under its account.+ doTo (st, acc, queue) (i, toP) = do+ checkNoTransactedPrice toP+ toQty <- case [aquantity a | a <- amountsRaw (pamount toP), acommodity a == commodity, aquantity a > 0] of+ [q] -> Right q+ _ -> Left $ showPos ++ "transfer-to posting has no single positive "+ ++ T.unpack commodity ++ " amount"+ -- Extract the transfer-to cost basis for optional validation.+ let toCb = case [(a, cb) | a <- amountsRaw (pamount toP), Just cb <- [acostbasis a]] of+ [(_, cb)] -> Just cb+ _ -> Nothing+ (portions, queue') = drawFromQueue toQty queue+ (toMethod, _) = resolveReductionMethodWithSource j toP commodity+ toBaseAcct = lotBaseAccount (paccount toP)+ when (sum [qty | (_, _, qty, _) <- portions] /= toQty) $+ Left $ showPos ++ "could not distribute transferred lots exactly (internal error)"+ toPs <- mapM (mkToPosting toMethod toP toCb) portions+ st' <- foldM (addTransferredLot toMethod toBaseAcct) st+ [(lid, amt, qty) | (lid, amt, qty, _) <- portions]+ return $ lotDbg t ("transferred in " ++ show toQty ++ " " ++ T.unpack commodity+ ++ " to " ++ T.unpack toBaseAcct)+ (st', (i, preserveParentAssertion verbosetags (paccount toP) (pbalanceassertion toP) (tagIfMulti toPs)) : acc, queue')++ mkToPosting toMethod toP toCb (lotId, storedAmt, qty, fromAmt) = do+ lotCb <- lotCbOf lotId storedAmt+ -- Validate transfer-to cost basis if it has specific fields+ validateToCb toMethod toCb lotCb+ let lotName = showLotNameForMethod toMethod (styleLotCbCost styles lotCb)+ toAcct = lotBaseAccount (paccount toP) <> ":" <> lotName+ toAmt' = (amountSetQuantity qty fromAmt){acostbasis = Just lotCb}+ Right toP{ paccount = toAcct+ , pamount = mixedAmount toAmt'+ , poriginal = Just (originalPosting toP)+ }++ -- Take fragments totalling the given quantity from the front of the+ -- queue, splitting the boundary fragment if needed.+ drawFromQueue :: Quantity -> [(LotId, Amount, Quantity, Amount)]+ -> ([(LotId, Amount, Quantity, Amount)], [(LotId, Amount, Quantity, Amount)])+ drawFromQueue 0 queue = ([], queue)+ drawFromQueue _ [] = ([], [])+ drawFromQueue need ((lid, amt, qty, fa):rest)+ | need >= qty = let (taken, rest') = drawFromQueue (need - qty) rest+ in ((lid, amt, qty, fa):taken, rest')+ | otherwise = ([(lid, amt, need, fa)], (lid, amt, qty - need, fa):rest)++ -- Check that a transfer posting has no user-written transacted price (@ or @@).+ -- Use originalPosting to distinguish user-written @ from pipeline-inferred acost.+ checkNoTransactedPrice p =+ when (any (isJust . acost) (amountsRaw $ pamount $ originalPosting p)) $+ Left $ showPos ++ "lot transfers should have no transacted price"++ -- For multi-fragment postings, tag each fragment as a per-lot split so+ -- journalCollapseLotDetail can merge them back to a single posting when+ -- --lots is off. Single-fragment postings need no tag.+ tagIfMulti ps = case ps of+ [_] -> ps+ _ -> map (postingAddHiddenAndMaybeVisibleTag False verbosetags (lotsplitPostingTagName, "")) ps++ -- Reconstruct a lot's full cost basis from its id and stored amount.+ lotCbOf lotId storedAmt = case acostbasis storedAmt >>= cbCost of+ Just c -> Right CostBasis{cbDate = Just (lotDate lotId), cbLabel = lotLabel lotId, cbCost = Just c}+ Nothing -> Left $ showPos ++ "lot " ++ show lotId+ ++ " for commodity " ++ T.unpack commodity+ ++ " has no cost basis (internal error)"++ -- If the transfer-to posting has any attributes specified in a lot annotation,+ -- make sure they correspond to the source lot's attributes.+ -- Transfers are not allowed to change a lot's identity.+ -- Under an AVERAGE destination method the cost check is skipped:+ -- the pool's running cost legitimately differs from any written cost+ -- (cf mergeCostBasisForMethod).+ validateToCb _ Nothing _ = Right ()+ validateToCb method (Just toCb') lotCb =+ when (dateMismatch || labelMismatch || costMismatch) $+ Left $ showPos <> unlines+ ["Destination lot info " <> T.unpack (showLotName toCb') <> " does not match the source lot " <> T.unpack (showLotName lotCb) <> "."+ ,"Transfers must preserve the source lot's identity."+ ,"Remove the destination lot annotation, or make it match the source lot's info."+ ]++ where+ dateMismatch = case cbDate toCb' of+ Just d -> cbDate lotCb /= Just d+ Nothing -> False+ labelMismatch = case cbLabel toCb' of+ Just l -> cbLabel lotCb /= Just l+ Nothing -> False+ costMismatch = not (methodIsAverage method) &&+ case (cbCost toCb', cbCost lotCb) of+ (Just c, Just lc) -> not (lotCostsMatch c lc)+ _ -> False++ -- Re-add a transferred lot to LotState under the destination account.+ -- If the destination uses an AVERAGE method, first re-average its pool+ -- with the incoming quantity at its carried cost, like an acquisition;+ -- the incoming lot is then stored at the new pool cost. (Under+ -- AVERAGEALL this is a no-op: the lot never left the global pool, so+ -- the carried cost equals the pool cost.)+ addTransferredLot method destAcct ls (lotId, storedAmt, consumedQty)+ | methodIsAverage method = do+ lotCb <- lotCbOf lotId storedAmt+ carried <- maybe (Left $ showPos ++ "lot " ++ show lotId+ ++ " has no carried cost (internal error)") Right (cbCost lotCb)+ -- (transfers are of long lots only, so AVERAGEALL pools the Long accounts)+ let inPool acct | methodIsGlobal method = journalLotDirectionOrLong j acct == Long+ | otherwise = acct == destAcct+ (newAvg, ls') <- updatePoolOnAcquire showPos inPool commodity consumedQty carried ls+ let amt = storedAmt{aquantity = consumedQty, acostbasis = Just lotCb{cbCost = Just newAvg}}+ Right $ addLotState commodity lotId destAcct amt ls'+ | otherwise =+ let amt = storedAmt{aquantity = consumedQty}+ in Right $ addLotState commodity lotId destAcct amt ls++-- Lot state operations++-- | Add an amount to LotState for a specific account/commodity/lot.+-- If the lot already exists on that account, quantities are summed (not overwritten).+-- This can happen when the same lot is transferred to the same destination account+-- by multiple transactions (e.g. two transfers on the same date both move portions+-- of the same lot).+addLotState :: CommoditySymbol -> LotId -> AccountName -> Amount -> LotState -> LotState+addLotState commodity lotId account amt =+ M.insertWith (M.unionWith (M.unionWith addQty)) commodity+ (M.singleton lotId (M.singleton account amt))+ where addQty a1 a2 = a1{aquantity = aquantity a1 + aquantity a2}+++-- | Restrict one commodity's lots in a lot state to the accounts with the+-- given lot direction. Long lots (in asset accounts) and short lots (in+-- liability accounts) are separate pools: the global (*ALL) methods and the+-- "other accounts" error summaries should see only one of them.+lotStateForDirection :: Journal -> LotDirection -> CommoditySymbol -> LotState -> LotState+lotStateForDirection j dir commodity =+ M.adjust (M.map (M.filterWithKey (\acct _ -> journalLotDirectionOrLong j acct == dir))) commodity++-- | Select lots to consume using the given reduction method.+-- All methods select from the specified account only.+-- Ordering: FIFO\/FIFOALL oldest-first; LIFO\/LIFOALL newest-first;+-- HIFO\/HIFOALL highest per-unit cost first; AVERAGE\/AVERAGEALL FIFO order;+-- SPECID requires an explicit selector matching one lot.+-- The *ALL variants additionally validate that the selected lots would also be+-- chosen first if all accounts' lots were considered together (see 'validateGlobalCompliance').+-- The lot selector filters which lots are eligible: each non-Nothing field+-- in the selector must match the corresponding field in the lot's cost basis.+-- An all-Nothing selector (from @{}@) matches all lots.+-- Returns a list of (lot id, lot amount, quantity consumed from this lot).+-- Errors if total available quantity in matching lots is insufficient.+-- The lot direction is that of the account (the lot state should already be+-- restricted to that direction, see 'lotStateForDirection'); it is used to+-- suggest a liability account when a long account has no lots to dispose of.+selectLots :: (ReductionMethod, String) -> String -> String -> Day -> LotDirection -> AccountName -> CommoditySymbol+ -> Quantity -> CostBasis -> LotState+ -> Either String [(LotId, Amount, Quantity)]+selectLots (method, methodSource) posStr operation date direction account commodity qty selector lotState = do+ when (method == SPECID && isWildcardSelector selector) $+ Left $ posStr ++ "SPECID requires an explicit lot selector" ++ methodline+ let allLots = M.findWithDefault M.empty commodity lotState+ -- Flatten to (LotId, Amount) pairs, taking only the specified account's balance.+ flatLots = M.mapMaybe (M.lookup account) allLots+ matchingLots = M.filter (lotMatchesSelector selector) flatLots+ when (M.null matchingLots) $+ Left $ posStr +++ if M.null flatLots+ then "no " ++ T.unpack commodity+ ++ " lots available for " ++ operation+ ++ " from account " ++ T.unpack account+ ++ " on " ++ show date+ ++ showOtherAccountLots allLots+ ++ shorthint+ else "no lots matching " ++ T.unpack (showLotName selector)+ ++ " for commodity " ++ T.unpack commodity+ ++ " in account " ++ T.unpack account+ ++ " on " ++ show date+ ++ "\nAvailable lots in this account:" ++ showLotList flatLots+ when (method == SPECID && M.size matchingLots > 1) $+ Left $ posStr ++ "lot selector is ambiguous, matches " ++ show (M.size matchingLots)+ ++ " lots in account " ++ T.unpack account ++ ":"+ ++ showLotList matchingLots ++ methodline+ let available = sum [aquantity a | a <- M.elems matchingLots]+ when (available < qty) $+ Left $ posStr ++ "Insufficient lots for commodity " ++ T.unpack commodity+ ++ " in account " ++ T.unpack account+ ++ ": need " ++ show qty ++ " but only " ++ show available ++ " available"+ -- with an explicit lot selector, show what it matched;+ -- for a generic outflow the lot details wouldn't help+ ++ (if isWildcardSelector selector then ""+ else "\nLots matching " ++ T.unpack (showLotName selector) ++ ":"+ ++ showLotList matchingLots)+ ++ showOtherAccountLots allLots+ let base = methodBaseOrdering method+ orderedLots = case base of+ FIFO -> M.toAscList matchingLots+ LIFO -> M.toDescList matchingLots+ HIFO -> sortOn (Down . lotPerUnitCost) (M.toList matchingLots)+ AVERAGE -> M.toAscList matchingLots+ SPECID -> M.toAscList matchingLots+ _ -> M.toAscList matchingLots -- unreachable after methodBaseOrdering+ selected = go qty orderedLots+ when (methodIsGlobal method) $+ first (++ methodline) $+ validateGlobalCompliance method posStr account commodity qty selector lotState selected+ Right selected+ where+ -- The reduction method and where it came from; appended to the errors+ -- where the method matters (the availability errors omit it).+ methodline = "\nUsing " ++ show method ++ " (" ++ methodSource ++ ")."++ -- A sale from an asset account holding none of the commodity may be a+ -- short sale, which belongs in a liability account.+ shorthint+ | direction == Long && operation == "disposal" =+ "\n(To record a short position, use a liability account.)"+ | otherwise = ""++ go 0 _ = []+ go _ [] = [] -- shouldn't happen after the check above+ go remaining ((lotId, lotAmt):rest)+ | remaining >= lotBal = (lotId, lotAmt, lotBal) : go (remaining - lotBal) rest+ | otherwise = [(lotId, lotAmt, remaining)]+ where lotBal = aquantity lotAmt++ -- Show lots one per line, at most 10; a final line counts any more,+ -- and another shows the total quantity.+ showLotList :: M.Map LotId Amount -> String+ showLotList lots = concatMap fmt shown ++ more ++ totalline+ where+ (shown, rest) = splitAt 10 (M.toAscList lots)+ fmt (lid, a) = "\n " ++ T.unpack (showLotName (lotIdToCb lid a))+ ++ " " ++ show (aquantity a)+ more = case length rest of+ 0 -> ""+ 1 -> "\n ...and 1 more lot"+ n -> "\n ...and " ++ show n ++ " more lots"+ totalline = "\n Total: " ++ show (sum (map aquantity (M.elems lots)))+ ++ " " ++ T.unpack commodity++ -- Summarise this commodity's lots in accounts other than the specified+ -- one: for each account, the total quantity and number of lots; and+ -- when there are several accounts, the total quantity overall.+ showOtherAccountLots :: M.Map LotId (M.Map AccountName Amount) -> String+ showOtherAccountLots allLots' =+ let others = [(acct, a) | (_, acctMap) <- M.toAscList allLots'+ , (acct, a) <- M.toList acctMap, acct /= account]+ byAcct = M.fromListWith (\(q1, n1) (q2, n2) -> (q1 + q2, n1 + n2))+ [(acct, (aquantity a, 1 :: Int)) | (acct, a) <- others]+ totalline+ | M.size byAcct < 2 = ""+ | otherwise = "\n Total: " ++ show (sum [q | (q, _) <- M.elems byAcct])+ ++ " " ++ T.unpack commodity+ in if M.null byAcct then ""+ else "\nLots of " ++ T.unpack commodity ++ " in other accounts:"+ ++ concatMap fmtAcct (M.toAscList byAcct)+ ++ totalline+ where fmtAcct (acct, (q, n)) = "\n " ++ T.unpack acct ++ ": "+ ++ show q ++ " " ++ T.unpack commodity+ ++ " in " ++ show n ++ (if n == 1 then " lot" else " lots")++-- | Extract the per-unit cost quantity from a lot entry, for HIFO sorting.+lotPerUnitCost :: (LotId, Amount) -> Quantity+lotPerUnitCost (_, a) = maybe 0 aquantity (acostbasis a >>= cbCost)++-- | Whether a reduction method uses weighted average cost basis for disposals.+methodIsAverage :: ReductionMethod -> Bool+methodIsAverage AVERAGE = True+methodIsAverage AVERAGEALL = True+methodIsAverage _ = False++-- | Whether a reduction method requires global validation across all accounts.+methodIsGlobal :: ReductionMethod -> Bool+methodIsGlobal FIFOALL = True+methodIsGlobal LIFOALL = True+methodIsGlobal HIFOALL = True+methodIsGlobal AVERAGEALL = True+methodIsGlobal _ = False++-- | Map a *ALL method to its base ordering, or return the method unchanged.+methodBaseOrdering :: ReductionMethod -> ReductionMethod+methodBaseOrdering FIFOALL = FIFO+methodBaseOrdering LIFOALL = LIFO+methodBaseOrdering HIFOALL = HIFO+methodBaseOrdering AVERAGEALL = AVERAGE+methodBaseOrdering m = m++-- | Flatten lots across all accounts, summing quantities for shared lot IDs.+-- From @Map LotId (Map AccountName Amount)@ to @Map LotId Amount@,+-- combining quantities across accounts (taking the first Amount's metadata).+flattenAllAccountLots :: M.Map LotId (M.Map AccountName Amount) -> M.Map LotId Amount+flattenAllAccountLots = M.mapMaybe flattenAccts+ where+ flattenAccts acctMap =+ case M.elems acctMap of+ [] -> Nothing+ (a:rest) -> Just a{aquantity = aquantity a + sum (map aquantity rest)}++-- | Validate that the per-account selected lots would also be chosen first+-- under a global ordering across all accounts. Errors if lots on other accounts+-- have higher priority than the selected lots.+validateGlobalCompliance :: ReductionMethod -> String -> AccountName -> CommoditySymbol+ -> Quantity -> CostBasis -> LotState+ -> [(LotId, Amount, Quantity)] -> Either String ()+validateGlobalCompliance method posStr account commodity qty selector lotState selected = do+ let allLots = M.findWithDefault M.empty commodity lotState+ globalFlat = flattenAllAccountLots allLots+ globalMatching = M.filter (lotMatchesSelector selector) globalFlat+ base = methodBaseOrdering method+ globalOrdered = case base of+ FIFO -> M.toAscList globalMatching+ LIFO -> M.toDescList globalMatching+ HIFO -> sortOn (Down . lotPerUnitCost) (M.toList globalMatching)+ AVERAGE -> M.toAscList globalMatching+ _ -> M.toAscList globalMatching+ -- Greedily consume qty from the globally-ordered list+ globalSelectedIds = S.fromList $ map fst3 $ goConsume qty globalOrdered+ selectedIds = S.fromList [lid | (lid, _, _) <- selected]+ -- Lot IDs that would be globally selected but are NOT in the per-account selection+ -- (i.e. they exist on other accounts and have higher priority)+ higherPriorityElsewhere = S.difference globalSelectedIds selectedIds+ unless (S.null higherPriorityElsewhere) $ do+ -- Build detailed error showing which accounts hold the higher-priority lots+ let otherLots = [(acct, lid, a)+ | lid <- S.toList higherPriorityElsewhere+ , Just acctMap <- [M.lookup lid allLots]+ , (acct, a) <- M.toList acctMap]+ byAcct = M.fromListWith (++) [(acct, [(lid, a)]) | (acct, lid, a) <- otherLots]+ fmtAcct (acct, lots) = "\n " ++ T.unpack acct ++ ": "+ ++ intercalate ", " [T.unpack (showLotName (lotIdToCb lid a)) ++ " " ++ show (aquantity a)+ | (lid, a) <- lots]+ fmtSelected = concatMap (\(lid, a, q) -> "\n " ++ T.unpack (showLotName (lotIdToCb lid a))+ ++ " " ++ show q) selected+ Left $ posStr ++ show method ++ ": lot(s) on other account(s) have higher priority than the lots in "+ ++ T.unpack account ++ ":"+ ++ concatMap fmtAcct (M.toAscList byAcct)+ ++ "\nSelected from " ++ T.unpack account ++ ":"+ ++ fmtSelected+ ++ "\nConsider disposing from the account(s) listed above first, or use "+ ++ show (methodBaseOrdering method) ++ " for per-account scope."+ where+ goConsume 0 _ = []+ goConsume _ [] = []+ goConsume remaining ((lotId, lotAmt):rest)+ | remaining >= aquantity lotAmt = (lotId, lotAmt, aquantity lotAmt) : goConsume (remaining - aquantity lotAmt) rest+ | otherwise = [(lotId, lotAmt, remaining)]+ fst3 (x, _, _) = x++-- | Under AVERAGE / AVERAGEALL: integrate a new acquisition into the running+-- pool and return (new shared per-unit cost, lot state with every existing+-- pool lot's stored cbCost updated to that new cost).+--+-- @inPool@ says which accounts' lots make up the pool: for AVERAGEALL, all+-- accounts holding this commodity in the same lot direction (long lots in+-- asset accounts, or short lots in liability accounts); for AVERAGE, just+-- the acquiring account, other accounts having their own independent pools.+updatePoolOnAcquire+ :: String -- ^ error-message position prefix+ -> (AccountName -> Bool) -- ^ inPool: do this account's lots belong to the pool ?+ -> CommoditySymbol+ -> Quantity -- ^ this acquisition's quantity+ -> Amount -- ^ this acquisition's per-unit cost+ -> LotState+ -> Either String (Amount, LotState)+updatePoolOnAcquire posStr inPool commodity acqQty acqCost lotState = do+ let commLots = M.findWithDefault M.empty commodity lotState+ -- The per-LotId Amounts belonging to the pool.+ poolAmts accts = M.elems (M.filterWithKey (\acct _ -> inPool acct) accts)+ existingEntries = [(aquantity a, c) | accts <- M.elems commLots+ , a <- poolAmts accts+ , Just cb <- [acostbasis a]+ , Just c <- [cbCost cb]]+ -- All pool entries (including this acquisition) must agree on cost commodity.+ case listToMaybe existingEntries of+ Just (_, firstCost) | acommodity firstCost /= acommodity acqCost ->+ Left $ posStr ++ "cannot average lots with different cost commodities"+ _ -> Right ()+ let totalQty = acqQty + sum [q | (q, _) <- existingEntries]+ totalCost = multiplyQuantities acqQty (aquantity acqCost)+ + sum [multiplyQuantities q (aquantity c) | (q, c) <- existingEntries]+ when (totalQty == 0) $+ Left $ posStr ++ "cannot average lots with zero total quantity"+ let newAvg = acqCost{aquantity = totalCost / totalQty}+ rewriteAmt a = case acostbasis a of+ Nothing -> a+ Just cb -> a{acostbasis = Just cb{cbCost = Just newAvg}}+ rewriteAccts = M.mapWithKey (\acct a -> if inPool acct then rewriteAmt a else a)+ lotState' = M.insert commodity (M.map rewriteAccts commLots) lotState+ return (newAvg, lotState')++-- | Is this an all-Nothing (wildcard) lot selector, i.e. from @{}@?+isWildcardSelector :: CostBasis -> Bool+isWildcardSelector (CostBasis Nothing Nothing Nothing) = True+isWildcardSelector _ = False++-- | Does a lot match a lot selector?+-- Each non-Nothing field in the selector must match the lot's stored cost basis.+lotMatchesSelector :: CostBasis -> Amount -> Bool+lotMatchesSelector selector a =+ case acostbasis a of+ Nothing -> False+ Just lotCb -> matchCost (cbCost selector) (cbCost lotCb)+ && matchField cbDate selector lotCb+ && matchField cbLabel selector lotCb+ where+ matchField :: Eq b => (CostBasis -> Maybe b) -> CostBasis -> CostBasis -> Bool+ matchField f sel lot = case f sel of+ Nothing -> True -- selector doesn't constrain this field+ Just v -> f lot == Just v+ -- Compare costs by commodity and quantity, ignoring style differences+ -- (but accepting a display-rounded rendering, see 'lotCostsMatch').+ matchCost :: Maybe Amount -> Maybe Amount -> Bool+ matchCost Nothing _ = True+ matchCost (Just _) Nothing = False+ matchCost (Just sel) (Just lot) = lotCostsMatch sel lot++-- | Subtract consumed quantities from LotState for a specific account.+-- Removes lot-account entries whose balance reaches zero.+-- A fully consumed lot's id is kept as a tombstone (a lot with no account+-- entries), so that its label is never reused by a later same-date+-- acquisition ('generateLabel'), keeping lot histories unambiguous.+-- Tombstones are invisible elsewhere: lot selection, transfers, and pool+-- updates all look only at lots' per-account amounts.+reduceLotState :: AccountName -> CommoditySymbol -> [(LotId, Quantity)] -> LotState -> LotState+reduceLotState account commodity consumed = M.adjust adjustCommodity commodity+ where+ adjustCommodity lots = foldl' reduceLot lots consumed+ reduceLot lots (lotId, qty) = M.adjust shrinkLot lotId lots+ where+ shrinkLot = M.update (shrinkAmt qty) account+ shrinkAmt q a+ | aquantity a <= q = Nothing+ | otherwise = Just a{aquantity = aquantity a - q}++-- Debug trace helpers++-- | Reconstruct a CostBasis from a LotId and a stored Amount (for display in trace messages).+lotIdToCb :: LotId -> Amount -> CostBasis+lotIdToCb lid a = CostBasis (Just (lotDate lid)) (lotLabel lid) (acostbasis a >>= cbCost)++-- | Show selected lots for trace messages: "{2026-01-15, $50} 5, {2026-02-01, $60} 3"+showSelectedLots :: [(LotId, Amount, Quantity)] -> String+showSelectedLots = intercalate ", " . map fmt+ where fmt (lid, a, qty) = T.unpack (showLotName (lotIdToCb lid a)) ++ " " ++ show qty
− Hledger/Data/Matching.hs
@@ -1,324 +0,0 @@-{-|--More generic matching, done in one step, unlike FilterSpec and filterJournal*. -Currently used only by hledger-web.---}--module Hledger.Data.Matching-where-import Data.Either-import Data.List--- import Data.Map (findWithDefault, (!))-import Data.Maybe--- import Data.Ord-import Data.Time.Calendar--- import Data.Time.LocalTime--- import Data.Tree-import Safe (readDef, headDef)--- import System.Time (ClockTime(TOD))-import Test.HUnit-import Text.ParserCombinators.Parsec--- import Text.Printf--- import qualified Data.Map as Map--import Hledger.Utils-import Hledger.Data.Types-import Hledger.Data.AccountName-import Hledger.Data.Amount--- import Hledger.Data.Commodity (canonicaliseCommodities)-import Hledger.Data.Dates-import Hledger.Data.Posting-import Hledger.Data.Transaction--- import Hledger.Data.TimeLog---- | A matcher is a single, or boolean composition of, search criteria,--- which can be used to match postings, transactions, accounts and more.--- Currently used by hledger-web, will likely replace FilterSpec at some point.-data Matcher = MatchAny -- ^ always match- | MatchNone -- ^ never match- | MatchNot Matcher -- ^ negate this match- | MatchOr [Matcher] -- ^ match if any of these match- | MatchAnd [Matcher] -- ^ match if all of these match- | MatchDesc String -- ^ match if description matches this regexp- | MatchAcct String -- ^ match postings whose account matches this regexp- | MatchDate DateSpan -- ^ match if actual date in this date span- | MatchEDate DateSpan -- ^ match if effective date in this date span- | MatchStatus Bool -- ^ match if cleared status has this value- | MatchReal Bool -- ^ match if "realness" (involves a real non-virtual account ?) has this value- | MatchEmpty Bool -- ^ match if "emptiness" (from the --empty command-line flag) has this value.- -- Currently this means a posting with zero amount.- | MatchDepth Int -- ^ match if account depth is less than or equal to this value- deriving (Show, Eq)---- | A query option changes a query's/report's behaviour and output in some way.---- XXX could use regular CliOpts ?-data QueryOpt = QueryOptInAcctOnly AccountName -- ^ show an account register focussed on this account- | QueryOptInAcct AccountName -- ^ as above but include sub-accounts in the account register- -- | QueryOptCostBasis -- ^ show amounts converted to cost where possible- -- | QueryOptEffectiveDate -- ^ show effective dates instead of actual dates- deriving (Show, Eq)---- | The account we are currently focussed on, if any, and whether subaccounts are included.--- Just looks at the first query option.-inAccount :: [QueryOpt] -> Maybe (AccountName,Bool)-inAccount [] = Nothing-inAccount (QueryOptInAcctOnly a:_) = Just (a,False)-inAccount (QueryOptInAcct a:_) = Just (a,True)---- | A matcher for the account(s) we are currently focussed on, if any.--- Just looks at the first query option.-inAccountMatcher :: [QueryOpt] -> Maybe Matcher-inAccountMatcher [] = Nothing-inAccountMatcher (QueryOptInAcctOnly a:_) = Just $ MatchAcct $ accountNameToAccountOnlyRegex a-inAccountMatcher (QueryOptInAcct a:_) = Just $ MatchAcct $ accountNameToAccountRegex a---- -- | A matcher restricting the account(s) to be shown in the sidebar, if any.--- -- Just looks at the first query option.--- showAccountMatcher :: [QueryOpt] -> Maybe Matcher--- showAccountMatcher (QueryOptInAcctSubsOnly a:_) = Just $ MatchAcct True $ accountNameToAccountRegex a--- showAccountMatcher _ = Nothing---- | Convert a query expression containing zero or more space-separated--- terms to a matcher and zero or more query options. A query term is either:------ 1. a search criteria, used to match transactions. This is usually a prefixed pattern such as:--- acct:REGEXP--- date:PERIODEXP--- not:desc:REGEXP------ 2. a query option, which changes behaviour in some way. There is currently one of these:--- inacct:FULLACCTNAME - should appear only once------ Multiple search criteria are AND'ed together.--- When a pattern contains spaces, it or the whole term should be enclosed in single or double quotes.--- A reference date is required to interpret relative dates in period expressions.----parseQuery :: Day -> String -> (Matcher,[QueryOpt])-parseQuery d s = (m,qopts)- where- terms = words'' prefixes s- (matchers, qopts) = partitionEithers $ map (parseMatcher d) terms- m = case matchers of [] -> MatchAny- (m':[]) -> m'- ms -> MatchAnd ms---- | Quote-and-prefix-aware version of words - don't split on spaces which--- are inside quotes, including quotes which may have one of the specified--- prefixes in front, and maybe an additional not: prefix in front of that.-words'' :: [String] -> String -> [String]-words'' prefixes = fromparse . parsewith maybeprefixedquotedphrases -- XXX- where- maybeprefixedquotedphrases = choice' [prefixedQuotedPattern, quotedPattern, pattern] `sepBy` many1 spacenonewline- prefixedQuotedPattern = do- not' <- fromMaybe "" `fmap` (optionMaybe $ string "not:")- let allowednexts | null not' = prefixes- | otherwise = prefixes ++ [""]- next <- choice' $ map string allowednexts- let prefix = not' ++ next- p <- quotedPattern- return $ prefix ++ stripquotes p- quotedPattern = do- p <- between (oneOf "'\"") (oneOf "'\"") $ many $ noneOf "'\""- return $ stripquotes p- pattern = many (noneOf " \n\r\"")---- -- | Parse the query string as a boolean tree of match patterns.--- parseMatcher :: String -> Matcher--- parseMatcher s = either (const (MatchAny)) id $ runParser matcher () "" $ lexmatcher s---- lexmatcher :: String -> [String]--- lexmatcher s = words' s---- matcher :: GenParser String () Matcher--- matcher = undefined---- keep synced with patterns below, excluding "not"-prefixes = map (++":") [- "inacct","inacctonly",- "desc","acct","date","edate","status","real","empty","depth"- ]-defaultprefix = "acct"---- | Parse a single query term as either a matcher or a query option.-parseMatcher :: Day -> String -> Either Matcher QueryOpt-parseMatcher _ ('i':'n':'a':'c':'c':'t':'o':'n':'l':'y':':':s) = Right $ QueryOptInAcctOnly s-parseMatcher _ ('i':'n':'a':'c':'c':'t':':':s) = Right $ QueryOptInAcct s-parseMatcher d ('n':'o':'t':':':s) = case parseMatcher d s of- Left m -> Left $ MatchNot m- Right _ -> Left MatchAny -- not:somequeryoption will be ignored-parseMatcher _ ('d':'e':'s':'c':':':s) = Left $ MatchDesc s-parseMatcher _ ('a':'c':'c':'t':':':s) = Left $ MatchAcct s-parseMatcher d ('d':'a':'t':'e':':':s) =- case parsePeriodExpr d s of Left _ -> Left MatchNone -- XXX should warn- Right (_,span) -> Left $ MatchDate span-parseMatcher d ('e':'d':'a':'t':'e':':':s) =- case parsePeriodExpr d s of Left _ -> Left MatchNone -- XXX should warn- Right (_,span) -> Left $ MatchEDate span-parseMatcher _ ('s':'t':'a':'t':'u':'s':':':s) = Left $ MatchStatus $ parseStatus s-parseMatcher _ ('r':'e':'a':'l':':':s) = Left $ MatchReal $ parseBool s-parseMatcher _ ('e':'m':'p':'t':'y':':':s) = Left $ MatchEmpty $ parseBool s-parseMatcher _ ('d':'e':'p':'t':'h':':':s) = Left $ MatchDepth $ readDef 0 s-parseMatcher _ "" = Left $ MatchAny-parseMatcher d s = parseMatcher d $ defaultprefix++":"++s---- | Parse the boolean value part of a "status:" matcher, allowing "*" as--- another way to spell True, similar to the journal file format.-parseStatus :: String -> Bool-parseStatus s = s `elem` (truestrings ++ ["*"])---- | Parse the boolean value part of a "status:" matcher. A true value can--- be spelled as "1", "t" or "true".-parseBool :: String -> Bool-parseBool s = s `elem` truestrings--truestrings :: [String]-truestrings = ["1","t","true"]---- | Convert a match expression to its inverse.-negateMatcher :: Matcher -> Matcher-negateMatcher = MatchNot---- | Does the match expression match this posting ?-matchesPosting :: Matcher -> Posting -> Bool-matchesPosting (MatchNot m) p = not $ matchesPosting m p-matchesPosting (MatchAny) _ = True-matchesPosting (MatchNone) _ = False-matchesPosting (MatchOr ms) p = any (`matchesPosting` p) ms-matchesPosting (MatchAnd ms) p = all (`matchesPosting` p) ms-matchesPosting (MatchDesc r) p = regexMatchesCI r $ maybe "" tdescription $ ptransaction p-matchesPosting (MatchAcct r) p = regexMatchesCI r $ paccount p-matchesPosting (MatchDate span) p =- case d of Just d' -> spanContainsDate span d'- Nothing -> False- where d = maybe Nothing (Just . tdate) $ ptransaction p-matchesPosting (MatchEDate span) p =- case postingEffectiveDate p of Just d -> spanContainsDate span d- Nothing -> False-matchesPosting (MatchStatus v) p = v == postingCleared p-matchesPosting (MatchReal v) p = v == isReal p-matchesPosting (MatchEmpty v) Posting{pamount=a} = v == isZeroMixedAmount a-matchesPosting _ _ = False---- | Does the match expression match this transaction ?-matchesTransaction :: Matcher -> Transaction -> Bool-matchesTransaction (MatchNot m) t = not $ matchesTransaction m t-matchesTransaction (MatchAny) _ = True-matchesTransaction (MatchNone) _ = False-matchesTransaction (MatchOr ms) t = any (`matchesTransaction` t) ms-matchesTransaction (MatchAnd ms) t = all (`matchesTransaction` t) ms-matchesTransaction (MatchDesc r) t = regexMatchesCI r $ tdescription t-matchesTransaction m@(MatchAcct _) t = any (m `matchesPosting`) $ tpostings t-matchesTransaction (MatchDate span) t = spanContainsDate span $ tdate t-matchesTransaction (MatchEDate span) t = spanContainsDate span $ transactionEffectiveDate t-matchesTransaction (MatchStatus v) t = v == tstatus t-matchesTransaction (MatchReal v) t = v == hasRealPostings t-matchesTransaction _ _ = False--postingEffectiveDate :: Posting -> Maybe Day-postingEffectiveDate p = maybe Nothing (Just . transactionEffectiveDate) $ ptransaction p---- | Does the match expression match this account ?--- A matching in: clause is also considered a match.-matchesAccount :: Matcher -> AccountName -> Bool-matchesAccount (MatchNot m) a = not $ matchesAccount m a-matchesAccount (MatchAny) _ = True-matchesAccount (MatchNone) _ = False-matchesAccount (MatchOr ms) a = any (`matchesAccount` a) ms-matchesAccount (MatchAnd ms) a = all (`matchesAccount` a) ms-matchesAccount (MatchAcct r) a = regexMatchesCI r a-matchesAccount _ _ = False---- | What start date does this matcher specify, if any ?--- If the matcher is an OR expression, returns the earliest of the alternatives.--- When the flag is true, look for a starting effective date instead.-matcherStartDate :: Bool -> Matcher -> Maybe Day-matcherStartDate effective (MatchOr ms) = earliestMaybeDate $ map (matcherStartDate effective) ms-matcherStartDate effective (MatchAnd ms) = latestMaybeDate $ map (matcherStartDate effective) ms-matcherStartDate False (MatchDate (DateSpan (Just d) _)) = Just d-matcherStartDate True (MatchEDate (DateSpan (Just d) _)) = Just d-matcherStartDate _ _ = Nothing---- | Does this matcher specify a start date and nothing else (that would--- filter postings prior to the date) ?--- When the flag is true, look for a starting effective date instead.-matcherIsStartDateOnly :: Bool -> Matcher -> Bool-matcherIsStartDateOnly _ MatchAny = False-matcherIsStartDateOnly _ MatchNone = False-matcherIsStartDateOnly effective (MatchOr ms) = and $ map (matcherIsStartDateOnly effective) ms-matcherIsStartDateOnly effective (MatchAnd ms) = and $ map (matcherIsStartDateOnly effective) ms-matcherIsStartDateOnly False (MatchDate (DateSpan (Just _) _)) = True-matcherIsStartDateOnly True (MatchEDate (DateSpan (Just _) _)) = True-matcherIsStartDateOnly _ _ = False---- | Does this matcher match everything ?-matcherIsNull MatchAny = True-matcherIsNull (MatchAnd []) = True-matcherIsNull (MatchNot (MatchOr [])) = True-matcherIsNull _ = False---- | What is the earliest of these dates, where Nothing is earliest ?-earliestMaybeDate :: [Maybe Day] -> Maybe Day-earliestMaybeDate = headDef Nothing . sortBy compareMaybeDates---- | What is the latest of these dates, where Nothing is earliest ?-latestMaybeDate :: [Maybe Day] -> Maybe Day-latestMaybeDate = headDef Nothing . sortBy (flip compareMaybeDates)---- | Compare two maybe dates, Nothing is earliest.-compareMaybeDates :: Maybe Day -> Maybe Day -> Ordering-compareMaybeDates Nothing Nothing = EQ-compareMaybeDates Nothing (Just _) = LT-compareMaybeDates (Just _) Nothing = GT-compareMaybeDates (Just a) (Just b) = compare a b--tests_Hledger_Data_Matching :: Test-tests_Hledger_Data_Matching = TestList- [-- "parseQuery" ~: do- let d = parsedate "2011/1/1"- parseQuery d "a" `is` (MatchAcct "a", [])- parseQuery d "acct:a" `is` (MatchAcct "a", [])- parseQuery d "acct:a desc:b" `is` (MatchAnd [MatchAcct "a", MatchDesc "b"], [])- parseQuery d "\"acct:expenses:autres d\233penses\"" `is` (MatchAcct "expenses:autres d\233penses", [])- parseQuery d "not:desc:'a b'" `is` (MatchNot $ MatchDesc "a b", [])-- parseQuery d "inacct:a desc:b" `is` (MatchDesc "b", [QueryOptInAcct "a"])- parseQuery d "inacct:a inacct:b" `is` (MatchAny, [QueryOptInAcct "a", QueryOptInAcct "b"])-- parseQuery d "status:1" `is` (MatchStatus True, [])- parseQuery d "status:0" `is` (MatchStatus False, [])- parseQuery d "status:" `is` (MatchStatus False, [])- parseQuery d "real:1" `is` (MatchReal True, [])-- ,"matchesAccount" ~: do- assertBool "positive acct match" $ matchesAccount (MatchAcct "b:c") "a:bb:c:d"- -- assertBool "acct should match at beginning" $ not $ matchesAccount (MatchAcct True "a:b") "c:a:b"-- ,"matchesPosting" ~: do- -- matching posting status..- assertBool "positive match on true posting status" $- (MatchStatus True) `matchesPosting` nullposting{pstatus=True}- assertBool "negative match on true posting status" $- not $ (MatchNot $ MatchStatus True) `matchesPosting` nullposting{pstatus=True}- assertBool "positive match on false posting status" $- (MatchStatus False) `matchesPosting` nullposting{pstatus=False}- assertBool "negative match on false posting status" $- not $ (MatchNot $ MatchStatus False) `matchesPosting` nullposting{pstatus=False}- assertBool "positive match on true posting status acquired from transaction" $- (MatchStatus True) `matchesPosting` nullposting{pstatus=False,ptransaction=Just nulltransaction{tstatus=True}}- assertBool "real:1 on real posting" $ (MatchReal True) `matchesPosting` nullposting{ptype=RegularPosting}- assertBool "real:1 on virtual posting fails" $ not $ (MatchReal True) `matchesPosting` nullposting{ptype=VirtualPosting}- assertBool "real:1 on balanced virtual posting fails" $ not $ (MatchReal True) `matchesPosting` nullposting{ptype=BalancedVirtualPosting}-- ,"words''" ~: do- assertEqual "1" ["a","b"] (words'' [] "a b")- assertEqual "2" ["a b"] (words'' [] "'a b'")- assertEqual "3" ["not:a","b"] (words'' [] "not:a b")- assertEqual "4" ["not:a b"] (words'' [] "not:'a b'")- assertEqual "5" ["not:a b"] (words'' [] "'not:a b'")- assertEqual "6" ["not:desc:a b"] (words'' ["desc:"] "not:desc:'a b'")-- ]
+ Hledger/Data/Period.hs view
@@ -0,0 +1,360 @@+{-|++Manipulate the time periods typically used for reports with Period,+a richer abstraction than DateSpan. See also Types and Dates.++-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.Period (+ periodAsDateSpan+ ,dateSpanAsPeriod+ ,simplifyPeriod+ ,isLastDayOfMonth+ ,isStandardPeriod+ ,periodTextWidth+ ,showPeriod+ ,showPeriodAbbrev+ ,showPeriodAbbrevWith+ ,periodStart+ ,periodEnd+ ,periodNext+ ,periodPrevious+ ,periodNextIn+ ,periodPreviousIn+ ,periodMoveTo+ ,periodGrow+ ,periodShrink+ ,mondayBefore+ ,thursdayOfWeekContaining+ ,yearMonthContainingWeekStarting+ ,quarterContainingMonth+ ,firstMonthOfQuarter+ ,startOfFirstWeekInMonth+)+where++import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar+import Data.Time.Calendar.MonthDay+import Data.Time.Calendar.OrdinalDate+import Data.Time.Calendar.WeekDate+import Data.Time.Format+import Text.Printf++import Hledger.Data.Types++-- | Convert Periods to exact DateSpans.+--+-- >>> periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ Flex $ fromGregorian 2000 1 1) (Just $ Flex $ fromGregorian 2000 2 1)+-- True+periodAsDateSpan :: Period -> DateSpan+periodAsDateSpan (DayPeriod d) = DateSpan (Just $ Exact d) (Just $ Exact $ addDays 1 d)+periodAsDateSpan (WeekPeriod b) = DateSpan (Just $ Flex b) (Just $ Flex $ addDays 7 b)+periodAsDateSpan (MonthPeriod y m) = DateSpan (Just $ Flex $ fromGregorian y m 1) (Just $ Flex $ fromGregorian y' m' 1)+ where+ (y',m') | m==12 = (y+1,1)+ | otherwise = (y,m+1)+periodAsDateSpan (QuarterPeriod y q) = DateSpan (Just $ Flex $ fromGregorian y m 1) (Just $ Flex $ fromGregorian y' m' 1)+ where+ (y', q') | q==4 = (y+1,1)+ | otherwise = (y,q+1)+ quarterAsMonth q2 = (q2-1) * 3 + 1+ m = quarterAsMonth q+ m' = quarterAsMonth q'+periodAsDateSpan (YearPeriod y) = DateSpan (Just $ Flex $ fromGregorian y 1 1) (Just $ Flex $ fromGregorian (y+1) 1 1)+periodAsDateSpan (PeriodBetween b e) = DateSpan (Just $ Exact b) (Just $ Exact e)+periodAsDateSpan (PeriodFrom b) = DateSpan (Just $ Exact b) Nothing+periodAsDateSpan (PeriodTo e) = DateSpan Nothing (Just $ Exact e)+periodAsDateSpan (PeriodAll) = DateSpan Nothing Nothing++-- | Convert DateSpans to Periods.+--+-- >>> dateSpanAsPeriod $ DateSpan (Just $ Exact $ fromGregorian 2000 1 1) (Just $ Exact $ fromGregorian 2000 2 1)+-- MonthPeriod 2000 1+dateSpanAsPeriod :: DateSpan -> Period+dateSpanAsPeriod (DateSpan (Just b) (Just e)) = simplifyPeriod $ PeriodBetween (fromEFDay b) (fromEFDay e)+dateSpanAsPeriod (DateSpan (Just b) Nothing) = PeriodFrom (fromEFDay b)+dateSpanAsPeriod (DateSpan Nothing (Just e)) = PeriodTo (fromEFDay e)+dateSpanAsPeriod (DateSpan Nothing Nothing) = PeriodAll++-- | Convert PeriodBetweens to a more abstract period where possible.+--+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)+-- YearPeriod 1+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)+-- QuarterPeriod 2000 4+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)+-- MonthPeriod 2000 2+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)+-- WeekPeriod 2016-07-25+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)+-- DayPeriod 2000-01-01+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)+-- PeriodBetween 2000-02-28 2000-03-01+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)+-- DayPeriod 2000-02-29+-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)+-- DayPeriod 2000-12-31+--+simplifyPeriod :: Period -> Period+simplifyPeriod (PeriodBetween b e) =+ case (toGregorian b, toGregorian e) of+ -- a year+ ((by,1,1), (ey,1,1)) | by+1==ey -> YearPeriod by+ -- a half-year+ -- ((by,1,1), (ey,7,1)) | by==ey ->+ -- ((by,7,1), (ey,1,1)) | by+1==ey ->+ -- a quarter+ ((by,1,1), (ey,4,1)) | by==ey -> QuarterPeriod by 1+ ((by,4,1), (ey,7,1)) | by==ey -> QuarterPeriod by 2+ ((by,7,1), (ey,10,1)) | by==ey -> QuarterPeriod by 3+ ((by,10,1), (ey,1,1)) | by+1==ey -> QuarterPeriod by 4+ -- a month+ ((by,bm,1), (ey,em,1)) | by==ey && bm+1==em -> MonthPeriod by bm+ ((by,12,1), (ey,1,1)) | by+1==ey -> MonthPeriod by 12+ -- a week (two successive mondays),+ -- YYYYwN ("week N of year YYYY")+ -- _ | let ((by,bw,bd), (ey,ew,ed)) = (toWeekDate from, toWeekDate to) in by==ey && fw+1==tw && bd==1 && ed==1 ->+ -- a week starting on a monday+ _ | let ((by,bw,bd), (ey,ew,ed)) = (toWeekDate b, toWeekDate (addDays (-1) e))+ in by==ey && bw==ew && bd==1 && ed==7 -> WeekPeriod b+ -- a day+ ((by,bm,bd), (ey,em,ed)) |+ (by==ey && bm==em && bd+1==ed) ||+ (by+1==ey && bm==12 && em==1 && bd==31 && ed==1) || -- crossing a year boundary+ (by==ey && bm+1==em && isLastDayOfMonth by bm bd && ed==1) -- crossing a month boundary+ -> DayPeriod b+ _ -> PeriodBetween b e+simplifyPeriod p = p++isLastDayOfMonth y m d =+ case m of+ 1 -> d==31+ 2 | isLeapYear y -> d==29+ | otherwise -> d==28+ 3 -> d==31+ 4 -> d==30+ 5 -> d==31+ 6 -> d==30+ 7 -> d==31+ 8 -> d==31+ 9 -> d==30+ 10 -> d==31+ 11 -> d==30+ 12 -> d==31+ _ -> False++-- | Is this period a "standard" period, referencing a particular day, week, month, quarter, or year ?+-- Periods of other durations, or infinite duration, or not starting on a standard period boundary, are not.+isStandardPeriod = isStandardPeriod' . simplifyPeriod+ where+ isStandardPeriod' (DayPeriod _) = True+ isStandardPeriod' (WeekPeriod _) = True+ isStandardPeriod' (MonthPeriod _ _) = True+ isStandardPeriod' (QuarterPeriod _ _) = True+ isStandardPeriod' (YearPeriod _) = True+ isStandardPeriod' _ = False++-- | The width of a period of this type when displayed.+periodTextWidth :: Period -> Int+periodTextWidth = periodTextWidth' . simplifyPeriod+ where+ periodTextWidth' DayPeriod{} = 10 -- 2021-01-01+ periodTextWidth' WeekPeriod{} = 13 -- 2021-01-01W52+ periodTextWidth' MonthPeriod{} = 7 -- 2021-01+ periodTextWidth' QuarterPeriod{} = 6 -- 2021Q1+ periodTextWidth' YearPeriod{} = 4 -- 2021+ periodTextWidth' PeriodBetween{} = 22 -- 2021-01-01..2021-01-07+ periodTextWidth' PeriodFrom{} = 12 -- 2021-01-01..+ periodTextWidth' PeriodTo{} = 12 -- ..2021-01-01+ periodTextWidth' PeriodAll = 2 -- ..++-- | Render a period as a compact display string suitable for user output.+--+-- >>> showPeriod (WeekPeriod (fromGregorian 2016 7 25))+-- "2016-W30"+-- >>> showPeriod (WeekPeriod (fromGregorian 2024 12 30))+-- "2025-W01"+showPeriod :: Period -> Text+showPeriod (DayPeriod b) = T.pack $ formatTime defaultTimeLocale "%F" b -- DATE+showPeriod (WeekPeriod b) = T.pack $ y <> "-W" <> w -- YYYY-Www+ where+ y = formatTime defaultTimeLocale "%0Y" $ thursdayOfWeekContaining b -- be careful at year boundary+ w = formatTime defaultTimeLocale "%V" b+showPeriod (MonthPeriod y m) = T.pack $ printf "%04d-%02d" y m -- YYYY-MM+showPeriod (QuarterPeriod y q) = T.pack $ printf "%04dQ%d" y q -- YYYYQN+showPeriod (YearPeriod y) = T.pack $ printf "%04d" y -- YYYY+showPeriod (PeriodBetween b e) = T.pack $ formatTime defaultTimeLocale "%F" b+ ++ formatTime defaultTimeLocale "..%F" (addDays (-1) e) -- STARTDATE..INCLUSIVEENDDATE+showPeriod (PeriodFrom b) = T.pack $ formatTime defaultTimeLocale "%F.." b -- STARTDATE..+showPeriod (PeriodTo e) = T.pack $ formatTime defaultTimeLocale "..%F" (addDays (-1) e) -- ..INCLUSIVEENDDATE+showPeriod PeriodAll = ".."++-- | Like showPeriod, but if it's a month or week period show+-- an abbreviated form.+-- >>> showPeriodAbbrev (WeekPeriod (fromGregorian 2016 7 25))+-- "W30"+-- >>> showPeriodAbbrev (WeekPeriod (fromGregorian 2024 12 30))+-- "W01"+showPeriodAbbrev :: Period -> Text+showPeriodAbbrev = showPeriodAbbrevWith defaultTimeLocale++-- | Like showPeriodAbbrev, but take the month names from this time locale.+showPeriodAbbrevWith :: TimeLocale -> Period -> Text+showPeriodAbbrevWith loc (MonthPeriod _ m) -- Jan+ | m > 0 && m <= length monthnames = T.pack . snd $ monthnames !! (m-1)+ where monthnames = months loc+showPeriodAbbrevWith _ (WeekPeriod b) = T.pack $ formatTime defaultTimeLocale "W%V" b -- Www+showPeriodAbbrevWith _ p = showPeriod p++periodStart :: Period -> Maybe Day+periodStart p = fromEFDay <$> mb+ where+ DateSpan mb _ = periodAsDateSpan p++periodEnd :: Period -> Maybe Day+periodEnd p = fromEFDay <$> me+ where+ DateSpan _ me = periodAsDateSpan p++-- | Move a standard period to the following period of same duration.+-- Non-standard periods are unaffected.+periodNext :: Period -> Period+periodNext (DayPeriod b) = DayPeriod (addDays 1 b)+periodNext (WeekPeriod b) = WeekPeriod (addDays 7 b)+periodNext (MonthPeriod y 12) = MonthPeriod (y+1) 1+periodNext (MonthPeriod y m) = MonthPeriod y (m+1)+periodNext (QuarterPeriod y 4) = QuarterPeriod (y+1) 1+periodNext (QuarterPeriod y q) = QuarterPeriod y (q+1)+periodNext (YearPeriod y) = YearPeriod (y+1)+periodNext p = p++-- | Move a standard period to the preceding period of same duration.+-- Non-standard periods are unaffected.+periodPrevious :: Period -> Period+periodPrevious (DayPeriod b) = DayPeriod (addDays (-1) b)+periodPrevious (WeekPeriod b) = WeekPeriod (addDays (-7) b)+periodPrevious (MonthPeriod y 1) = MonthPeriod (y-1) 12+periodPrevious (MonthPeriod y m) = MonthPeriod y (m-1)+periodPrevious (QuarterPeriod y 1) = QuarterPeriod (y-1) 4+periodPrevious (QuarterPeriod y q) = QuarterPeriod y (q-1)+periodPrevious (YearPeriod y) = YearPeriod (y-1)+periodPrevious p = p++-- | Move a standard period to the following period of same duration, staying within enclosing dates.+-- Non-standard periods are unaffected.+periodNextIn :: DateSpan -> Period -> Period+periodNextIn (DateSpan _ (Just e0)) p =+ case mb of+ Just b -> if b < e then p' else p+ _ -> p+ where+ e = fromEFDay e0+ p' = periodNext p+ mb = periodStart p'+periodNextIn _ p = periodNext p++-- | Move a standard period to the preceding period of same duration, staying within enclosing dates.+-- Non-standard periods are unaffected.+periodPreviousIn :: DateSpan -> Period -> Period+periodPreviousIn (DateSpan (Just b0) _) p =+ case me of+ Just e -> if e > b then p' else p+ _ -> p+ where+ b = fromEFDay b0+ p' = periodPrevious p+ me = periodEnd p'+periodPreviousIn _ p = periodPrevious p++-- | Move a standard period stepwise so that it encloses the given date.+-- Non-standard periods are unaffected.+periodMoveTo :: Day -> Period -> Period+periodMoveTo d (DayPeriod _) = DayPeriod d+periodMoveTo d (WeekPeriod _) = WeekPeriod $ mondayBefore d+periodMoveTo d (MonthPeriod _ _) = MonthPeriod y m where (y,m,_) = toGregorian d+periodMoveTo d (QuarterPeriod _ _) = QuarterPeriod y q+ where+ (y,m,_) = toGregorian d+ q = quarterContainingMonth m+periodMoveTo d (YearPeriod _) = YearPeriod y where (y,_,_) = toGregorian d+periodMoveTo _ p = p++-- | Enlarge a standard period to the next larger enclosing standard period, if there is one.+-- Eg, a day becomes the enclosing week.+-- A week becomes whichever month the week's thursday falls into.+-- A year becomes all (unlimited).+-- Non-standard periods (arbitrary dates, or open-ended) are unaffected.+periodGrow :: Period -> Period+periodGrow (DayPeriod b) = WeekPeriod $ mondayBefore b+periodGrow (WeekPeriod b) = MonthPeriod y m+ where (y,m) = yearMonthContainingWeekStarting b+periodGrow (MonthPeriod y m) = QuarterPeriod y (quarterContainingMonth m)+periodGrow (QuarterPeriod y _) = YearPeriod y+periodGrow (YearPeriod _) = PeriodAll+periodGrow p = p++-- | Shrink a period to the next smaller standard period inside it,+-- choosing the subperiod which contains today's date if possible,+-- otherwise the first subperiod. It goes like this:+-- unbounded periods and nonstandard periods (between two arbitrary dates) ->+-- current year ->+-- current quarter if it's in selected year, otherwise first quarter of selected year ->+-- current month if it's in selected quarter, otherwise first month of selected quarter ->+-- current week if it's in selected month, otherwise first week of selected month ->+-- today if it's in selected week, otherwise first day of selected week,+-- unless that's in previous month, in which case first day of month containing selected week.+-- Shrinking a day has no effect.+periodShrink :: Day -> Period -> Period+periodShrink _ p@(DayPeriod _) = p+periodShrink today (WeekPeriod b)+ | today >= b && diffDays today b < 7 = DayPeriod today+ | m /= weekmonth = DayPeriod $ fromGregorian weekyear weekmonth 1+ | otherwise = DayPeriod b+ where+ (_,m,_) = toGregorian b+ (weekyear,weekmonth) = yearMonthContainingWeekStarting b+periodShrink today (MonthPeriod y m)+ | (y',m') == (y,m) = WeekPeriod $ mondayBefore today+ | otherwise = WeekPeriod $ startOfFirstWeekInMonth y m+ where (y',m',_) = toGregorian today+periodShrink today (QuarterPeriod y q)+ | quarterContainingMonth thismonth == q = MonthPeriod y thismonth+ | otherwise = MonthPeriod y (firstMonthOfQuarter q)+ where (_,thismonth,_) = toGregorian today+periodShrink today (YearPeriod y)+ | y == thisyear = QuarterPeriod y thisquarter+ | otherwise = QuarterPeriod y 1+ where+ (thisyear,thismonth,_) = toGregorian today+ thisquarter = quarterContainingMonth thismonth+periodShrink today _ = YearPeriod y+ where (y,_,_) = toGregorian today++mondayBefore d = addDays (1 - toInteger wd) d+ where+ (_,_,wd) = toWeekDate d++thursdayOfWeekContaining = (addDays 3).mondayBefore++yearMonthContainingWeekStarting weekstart = (y,m)+ where+ thu = addDays 3 weekstart+ (y,yd) = toOrdinalDate thu+ (m,_) = dayOfYearToMonthAndDay (isLeapYear y) yd++quarterContainingMonth m = (m-1) `div` 3 + 1++firstMonthOfQuarter q = (q-1)*3 + 1++startOfFirstWeekInMonth y m+ | monthstartday <= 4 = mon+ | otherwise = addDays 7 mon -- month starts with a fri/sat/sun+ where+ monthstart = fromGregorian y m 1+ mon = mondayBefore monthstart+ (_,_,monthstartday) = toWeekDate monthstart+
+ Hledger/Data/PeriodData.hs view
@@ -0,0 +1,138 @@+{-# LANGUAGE CPP #-}+{-|+++Data values for zero or more report periods, and for the pre-report period.+Report periods are assumed to be contiguous, and represented only by start dates+(as keys of an IntMap).++-}+module Hledger.Data.PeriodData+( periodDataFromList+, periodDataToList++, lookupPeriodData+, lookupPeriodDataOrHistorical+, insertPeriodData+, opPeriodData+, mergePeriodData+, padPeriodData++, tests_PeriodData+) where++#if MIN_VERSION_base(4,18,0)+import Data.Foldable1 (Foldable1(..))+#else+import Control.Applicative (liftA2)+#endif+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map qualified as M+import Data.Time (Day (..), fromGregorian)++import Hledger.Data.Amount+import Hledger.Data.Types+import Hledger.Utils+++instance Show a => Show (PeriodData a) where+ showsPrec d (PeriodData h ds) =+ showParen (d > 10) $+ showString "PeriodData"+ . showString "{ pdpre = " . shows h+ . showString ", pdperiods = "+ . showString "fromList " . shows (M.toList ds)+ . showChar '}'++instance Foldable PeriodData where+ foldr f z (PeriodData h as) = foldr f (f h z) as+ foldl f z (PeriodData h as) = foldl f (f z h) as+ foldl' f z (PeriodData h as) = let fzh = f z h in fzh `seq` foldl' f fzh as++#if MIN_VERSION_base(4,18,0)+instance Foldable1 PeriodData where+ foldrMap1 f g (PeriodData h as) = foldr g (f h) as+ foldlMap1 f g (PeriodData h as) = foldl g (f h) as+ foldlMap1' f g (PeriodData h as) = let fh = f h in fh `seq` foldl' g fh as+#endif++instance Traversable PeriodData where+ traverse f (PeriodData h as) = liftA2 PeriodData (f h) $ traverse f as++-- | The Semigroup instance for 'PeriodData' simply takes the union of+-- keys in the date map section. This may not be the result you want if the+-- keys are not identical.+instance Semigroup a => Semigroup (PeriodData a) where+ PeriodData h1 as1 <> PeriodData h2 as2 = PeriodData (h1 <> h2) $ M.unionWith (<>) as1 as2++instance Monoid a => Monoid (PeriodData a) where+ mempty = PeriodData mempty mempty++-- | Construct a 'PeriodData' from a historical data value and a list of (period start, period data) pairs.+periodDataFromList :: a -> [(Day, a)] -> PeriodData a+periodDataFromList h = PeriodData h . M.fromList++-- | Convert 'PeriodData' to a historical data value and a list of (period start, period data) pairs.+periodDataToList :: PeriodData a -> (a, [(Day, a)])+periodDataToList (PeriodData h as) = (h, M.toList as)++-- | Get the data for the period containing the given 'Day', and that period's start date.+-- If the day is after the end of the last period, it is assumed to be within the last period.+-- If the day is before the start of the first period (ie, in the historical period), return Nothing.+lookupPeriodData :: Day -> PeriodData a -> Maybe (Day, a)+lookupPeriodData d (PeriodData _ as) = M.lookupLE d as++-- | Get the data for the period containing the given 'Day', and that period's start date.+-- If the day is after the end of the last period, it is assumed to be within the last period.+-- If the day is before the start of the first period (ie, in the historical period),+-- return the data for the historical period and no start date.+lookupPeriodDataOrHistorical :: Day -> PeriodData a -> (Maybe Day, a)+lookupPeriodDataOrHistorical d pd@(PeriodData h _) = case lookupPeriodData d pd of+ Nothing -> (Nothing, h)+ Just (a, b) -> (Just a, b)++-- | Set historical or period data in the appropriate location in a 'PeriodData'.+insertPeriodData :: Semigroup a => Maybe Day -> a -> PeriodData a -> PeriodData a+insertPeriodData mday b balances = case mday of+ Nothing -> balances{pdpre = pdpre balances <> b}+ Just day -> balances{pdperiods = M.insertWith (<>) day b $ pdperiods balances}++-- | Merge two 'PeriodData', using the given operation to combine their data values.+--+-- This will drop keys if they are not present in both 'PeriodData'.+opPeriodData :: (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c+opPeriodData f (PeriodData h1 as1) (PeriodData h2 as2) =+ PeriodData (f h1 h2) $ M.intersectionWith f as1 as2++-- | Merge two 'PeriodData', using the given operations for combining data+-- that's only in the first, only in the second, or in both, respectively.+mergePeriodData :: (a -> c) -> (b -> c) -> (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c+mergePeriodData only1 only2 f = \(PeriodData h1 as1) (PeriodData h2 as2) ->+ PeriodData (f h1 h2) $ merge as1 as2+ where+ merge = M.mergeWithKey (\_ x y -> Just $ f x y) (fmap only1) (fmap only2)++-- | Pad out the date map of a 'PeriodData' so that every key from another 'PeriodData' is present.+padPeriodData :: a -> PeriodData b -> PeriodData a -> PeriodData a+padPeriodData x pad bal = bal{pdperiods = pdperiods bal <> (x <$ pdperiods pad)}+++-- tests++tests_PeriodData =+ let+ dayMap = periodDataFromList (mixed [usd 1]) [(fromGregorian 2000 01 01, mixed [usd 2]), (fromGregorian 2004 02 28, mixed [usd 3])]+ dayMap2 = periodDataFromList (mixed [usd 2]) [(fromGregorian 2000 01 01, mixed [usd 4]), (fromGregorian 2004 02 28, mixed [usd 6])]+ in testGroup "PeriodData" [++ testCase "periodDataFromList" $ do+ length dayMap @?= 3,++ testCase "Semigroup instance" $ do+ dayMap <> dayMap @?= dayMap2,++ testCase "Monoid instance" $ do+ dayMap <> mempty @?= dayMap+ ]
+ Hledger/Data/PeriodicTransaction.hs view
@@ -0,0 +1,263 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-|++A 'PeriodicTransaction' is a rule describing recurring transactions.++-}+module Hledger.Data.PeriodicTransaction (+ runPeriodicTransaction+ , periodicTransactionDates+ , checkPeriodicTransactionStartDate+)+where++import Data.Function ((&))+import Data.Maybe (isNothing)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Time (Day)+import Text.Printf++import Hledger.Data.Types+import Hledger.Data.Dates+import Hledger.Data.DayPartition+import Hledger.Data.Amount+import Hledger.Data.Posting (post, generatedTransactionTagName)+import Hledger.Data.Transaction++-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Hledger.Data.Posting+-- >>> import Hledger.Data.Journal++-- doctest helper, too much hassle to define in the comment+-- XXX duplicates some logic in periodictransactionp+_ptgen str = do+ let+ t = T.pack str+ (i,s) = parsePeriodExpr' nulldate t+ mapM_ (T.putStr . showTransaction) $+ runPeriodicTransaction True+ nullperiodictransaction{ ptperiodexpr=t , ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1] }+ nulldatespan++_ptgenspan str spn = do+ let+ t = T.pack str+ (i,s) = parsePeriodExpr' nulldate t+ mapM_ (T.putStr . showTransaction) $+ runPeriodicTransaction True+ nullperiodictransaction{ ptperiodexpr=t , ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1] }+ spn++--deriving instance Show PeriodicTransaction+-- for better pretty-printing:+instance Show PeriodicTransaction where+ show PeriodicTransaction{..} =+ printf "PeriodicTransactionPP {%s, %s, %s, %s, %s, %s, %s, %s, %s, %s}"+ -- Warning, be careful to keep these synced ^ v+ ("ptperiodexpr=" ++ show ptperiodexpr)+ ("ptinterval=" ++ show ptinterval)+ ("ptspan=" ++ show (show ptspan))+ ("ptsourcepos=" ++ show ptsourcepos)+ ("ptstatus=" ++ show (show ptstatus))+ ("ptcode=" ++ show ptcode)+ ("ptdescription=" ++ show ptdescription)+ ("ptcomment=" ++ show ptcomment)+ ("pttags=" ++ show pttags)+ ("ptpostings=" ++ show ptpostings)++-- A basic human-readable rendering.+--showPeriodicTransaction t = "~ " ++ T.unpack (ptperiodexpr t) ++ "\n" ++ unlines (map show (ptpostings t))++--nullperiodictransaction is defined in Types.hs++-- | Generate transactions from 'PeriodicTransaction' within a 'DateSpan'.+-- This should be a closed span with both start and end dates specified;+-- an open ended span will generate no transactions.+--+-- Note that new transactions require 'txnTieKnot' post-processing.+-- The new transactions will have three tags added: +-- - a recur:PERIODICEXPR tag whose value is the generating periodic expression+-- - a generated-transaction: tag+-- - a hidden _generated-transaction: tag which does not appear in the comment. +--+-- >>> import Data.Time (fromGregorian)+-- >>> _ptgen "monthly from 2017/1 to 2017/4"+-- 2017-01-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+-- 2017-02-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+-- 2017-03-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "monthly from 2017/1 to 2017/5"+-- 2017-01-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-02-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-03-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-04-01+-- ; generated-transaction: ~ monthly from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "every 2nd day of month from 2017/02 to 2017/04"+-- 2017-02-02+-- ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04+-- a $1.00+-- <BLANKLINE>+-- 2017-03-02+-- ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "every 30th day of month from 2017/1 to 2017/5"+-- 2017-01-30+-- ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-02-28+-- ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-03-30+-- ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+-- 2017-04-30+-- ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"+-- 2017-01-12+-- ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+-- 2017-02-09+-- ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+-- 2017-03-09+-- ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "every nov 29th from 2017 to 2019"+-- 2017-11-29+-- ; generated-transaction: ~ every nov 29th from 2017 to 2019+-- a $1.00+-- <BLANKLINE>+-- 2018-11-29+-- ; generated-transaction: ~ every nov 29th from 2017 to 2019+-- a $1.00+-- <BLANKLINE>+--+-- >>> _ptgen "2017/1"+-- 2017-01-01+-- ; generated-transaction: ~ 2017/1+-- a $1.00+-- <BLANKLINE>+--+-- >>> let reportperiod="daily from 2018/01/03" in let (i,s) = parsePeriodExpr' nulldate reportperiod in runPeriodicTransaction True (nullperiodictransaction{ptperiodexpr=reportperiod, ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1]}) (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03))+-- []+--+-- >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 01 01) (Just $ Flex $ fromGregorian 2020 02 01))+--+-- >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 02 01) (Just $ Flex $ fromGregorian 2020 03 01))+-- 2020-02-01+-- ; generated-transaction: ~ every 3 months from 2019-05+-- a $1.00+-- <BLANKLINE>+-- >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 05))+-- 2018-01-01+-- ; generated-transaction: ~ every 3 days from 2018+-- a $1.00+-- <BLANKLINE>+-- 2018-01-04+-- ; generated-transaction: ~ every 3 days from 2018+-- a $1.00+-- <BLANKLINE>+-- >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 02) (Just $ Flex $ fromGregorian 2018 01 05))+-- 2018-01-04+-- ; generated-transaction: ~ every 3 days from 2018+-- a $1.00+-- <BLANKLINE>++runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]+runPeriodicTransaction verbosetags pt@PeriodicTransaction{..} requestedspan =+ [ t{tdate=d} | d <- periodicTransactionDates pt requestedspan ]+ where+ t = nulltransaction{+ tsourcepos = ptsourcepos+ ,tstatus = ptstatus+ ,tcode = ptcode+ ,tdescription = ptdescription+ ,tcomment = ptcomment+ ,ttags = pttags+ ,tpostings = ptpostings+ }+ & transactionAddHiddenAndMaybeVisibleTag verbosetags (generatedTransactionTagName, period)+ period = "~ " <> ptperiodexpr++-- | The dates on which this periodic transaction rule generates a transaction within the+-- given span, as a lazily generated list (so counting or consuming them once uses constant+-- memory however many there are, cf #1683).+periodicTransactionDates :: PeriodicTransaction -> DateSpan -> [Day]+periodicTransactionDates PeriodicTransaction{ptspan, ptinterval} requestedspan =+ [ d | Just d <- map spanStart alltxnspans, spanContainsDate requestedspan d ]+ where+ -- All the date spans described by this periodic transaction rule.+ alltxnspans = splitSpanToDateSpans adjust ptinterval span'+ where+ -- If the PT does not specify start or end dates, we take them from the requestedspan.+ span' = ptspan `spanValidDefaultsFrom` requestedspan+ -- Unless the PT specified a start date explicitly, we will adjust the start date to the previous interval boundary.+ adjust = isNothing $ spanStart span'++-- | Check that this date span begins at a boundary of this interval,+-- or return an explanatory error message including the provided period expression+-- (from which the span and interval are derived).+checkPeriodicTransactionStartDate :: Interval -> DateSpan -> T.Text -> Maybe String+checkPeriodicTransactionStartDate i s periodexpr =+ case (i, spanStart s) of+ (Weeks _, Just d) -> checkStart d Week+ (Months _, Just d) -> checkStart d Month+ (Quarters _, Just d) -> checkStart d Quarter+ (Years _, Just d) -> checkStart d Year+ _ -> Nothing+ where+ checkStart d x =+ let firstDate = fromEFDay $ fixSmartDate d $ SmartRelative 0 x+ in+ if d == firstDate+ then Nothing+ else Just $+ "Unable to generate transactions according to "++show (T.unpack periodexpr)+ ++" because "++show d++" is not a first day of the "++show x++---- | What is the interval of this 'PeriodicTransaction's period expression, if it can be parsed ?+--periodTransactionInterval :: PeriodicTransaction -> Maybe Interval+--periodTransactionInterval pt =+-- let+-- expr = ptperiodexpr pt+-- err = error' $ "Current date cannot be referenced in " ++ show (T.unpack expr)+-- in+-- case parsePeriodExpr err expr of+-- Left _ -> Nothing+-- Right (i,_) -> Just i
Hledger/Data/Posting.hs view
@@ -1,168 +1,1000 @@ {-| -A 'Posting' represents a 'MixedAmount' being added to or subtracted from a-single 'Account'. Each 'Transaction' contains two or more postings which-should add up to 0. Postings also reference their parent transaction, so-we can get a date or description for a posting (from the transaction).-Strictly speaking, \"entry\" is probably a better name for these.---}--module Hledger.Data.Posting-where-import Data.List-import Data.Ord-import Data.Time.Calendar-import Safe-import Test.HUnit-import Text.Printf--import Hledger.Utils-import Hledger.Data.Types-import Hledger.Data.Amount-import Hledger.Data.AccountName-import Hledger.Data.Dates (nulldate, spanContainsDate)---instance Show Posting where show = showPosting--nullposting :: Posting-nullposting = Posting False "" nullmixedamt "" RegularPosting [] Nothing--showPosting :: Posting -> String-showPosting (Posting{paccount=a,pamount=amt,pcomment=com,ptype=t}) =- concatTopPadded [showaccountname a ++ " ", showamount amt, comment]- where- ledger3ishlayout = False- acctnamewidth = if ledger3ishlayout then 25 else 22- showaccountname = printf ("%-"++(show acctnamewidth)++"s") . bracket . elideAccountName width- (bracket,width) = case t of- BalancedVirtualPosting -> (\s -> "["++s++"]", acctnamewidth-2)- VirtualPosting -> (\s -> "("++s++")", acctnamewidth-2)- _ -> (id,acctnamewidth)- showamount = padleft 12 . showMixedAmount- comment = if null com then "" else " ; " ++ com--- XXX refactor-showPostingForRegister :: Posting -> String-showPostingForRegister (Posting{paccount=a,pamount=amt,ptype=t}) =- concatTopPadded [showaccountname a ++ " ", showamount amt]- where- ledger3ishlayout = False- acctnamewidth = if ledger3ishlayout then 25 else 22- showaccountname = printf ("%-"++(show acctnamewidth)++"s") . bracket . elideAccountName width- (bracket,width) = case t of- BalancedVirtualPosting -> (\s -> "["++s++"]", acctnamewidth-2)- VirtualPosting -> (\s -> "("++s++")", acctnamewidth-2)- _ -> (id,acctnamewidth)- showamount = padleft 12 . showMixedAmountWithoutPrice--isReal :: Posting -> Bool-isReal p = ptype p == RegularPosting--isVirtual :: Posting -> Bool-isVirtual p = ptype p == VirtualPosting--isBalancedVirtual :: Posting -> Bool-isBalancedVirtual p = ptype p == BalancedVirtualPosting--hasAmount :: Posting -> Bool-hasAmount = (/= missingamt) . pamount--accountNamesFromPostings :: [Posting] -> [AccountName]-accountNamesFromPostings = nub . map paccount--sumPostings :: [Posting] -> MixedAmount-sumPostings = sum . map pamount--postingDate :: Posting -> Day-postingDate p = maybe nulldate tdate $ ptransaction p---- |Is this posting cleared? If this posting was individually marked--- as cleared, returns True. Otherwise, return the parent--- transaction's cleared status or, if there is no parent--- transaction, return False.-postingCleared :: Posting -> Bool-postingCleared p = if pstatus p- then True- else maybe False tstatus $ ptransaction p---- | Does this posting fall within the given date span ?-isPostingInDateSpan :: DateSpan -> Posting -> Bool-isPostingInDateSpan s = spanContainsDate s . postingDate--isEmptyPosting :: Posting -> Bool-isEmptyPosting = isZeroMixedAmount . pamount---- | Get the minimal date span which contains all the postings, or--- DateSpan Nothing Nothing if there are none.-postingsDateSpan :: [Posting] -> DateSpan-postingsDateSpan [] = DateSpan Nothing Nothing-postingsDateSpan ps = DateSpan (Just $ postingDate $ head ps') (Just $ addDays 1 $ postingDate $ last ps')- where ps' = sortBy (comparing postingDate) ps---- AccountName stuff that depends on PostingType--accountNamePostingType :: AccountName -> PostingType-accountNamePostingType a- | null a = RegularPosting- | head a == '[' && last a == ']' = BalancedVirtualPosting- | head a == '(' && last a == ')' = VirtualPosting- | otherwise = RegularPosting--accountNameWithoutPostingType :: AccountName -> AccountName-accountNameWithoutPostingType a = case accountNamePostingType a of- BalancedVirtualPosting -> init $ tail a- VirtualPosting -> init $ tail a- RegularPosting -> a--accountNameWithPostingType :: PostingType -> AccountName -> AccountName-accountNameWithPostingType BalancedVirtualPosting a = "["++accountNameWithoutPostingType a++"]"-accountNameWithPostingType VirtualPosting a = "("++accountNameWithoutPostingType a++")"-accountNameWithPostingType RegularPosting a = accountNameWithoutPostingType a---- | Prefix one account name to another, preserving posting type--- indicators like concatAccountNames.-joinAccountNames :: AccountName -> AccountName -> AccountName-joinAccountNames a b = concatAccountNames $ filter (not . null) [a,b]---- | Join account names into one. If any of them has () or [] posting type--- indicators, these (the first type encountered) will also be applied to--- the resulting account name.-concatAccountNames :: [AccountName] -> AccountName-concatAccountNames as = accountNameWithPostingType t $ intercalate ":" $ map accountNameWithoutPostingType as- where t = headDef RegularPosting $ filter (/= RegularPosting) $ map accountNamePostingType as---- | Rewrite an account name using the first applicable alias from the given list, if any.-accountNameApplyAliases :: [(AccountName,AccountName)] -> AccountName -> AccountName-accountNameApplyAliases aliases a = withorigtype- where- (a',t) = (accountNameWithoutPostingType a, accountNamePostingType a)- firstmatchingalias = headDef Nothing $ map Just $ filter (\(orig,_) -> orig == a' || orig `isAccountNamePrefixOf` a') aliases- rewritten = maybe a' (\(orig,alias) -> alias++drop (length orig) a') firstmatchingalias- withorigtype = accountNameWithPostingType t rewritten--tests_Hledger_Data_Posting = TestList [-- "accountNamePostingType" ~: do- accountNamePostingType "a" `is` RegularPosting- accountNamePostingType "(a)" `is` VirtualPosting- accountNamePostingType "[a]" `is` BalancedVirtualPosting-- ,"accountNameWithoutPostingType" ~: do- accountNameWithoutPostingType "(a)" `is` "a"-- ,"accountNameWithPostingType" ~: do- accountNameWithPostingType VirtualPosting "[a]" `is` "(a)"-- ,"joinAccountNames" ~: do- "a" `joinAccountNames` "b:c" `is` "a:b:c"- "a" `joinAccountNames` "(b:c)" `is` "(a:b:c)"- "[a]" `joinAccountNames` "(b:c)" `is` "[a:b:c]"- "" `joinAccountNames` "a" `is` "a"-- ,"concatAccountNames" ~: do- concatAccountNames [] `is` ""- concatAccountNames ["a","(b)","[c:d]"] `is` "(a:b:c:d)"+A 'Posting' represents a change (by some 'MixedAmount') of the balance in+some 'Account'. Each 'Transaction' contains two or more postings which+should add up to 0. Postings reference their parent transaction, so we can+look up the date or description there.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.Posting (+ -- * Posting+ nullposting,+ posting,+ post,+ vpost,+ post',+ vpost',+ nullassertion,+ balassert,+ balassertTot,+ balassertParInc,+ balassertTotInc,+ -- * operations+ originalPosting,+ postingStatus,+ isReal,+ isVirtual,+ isBalancedVirtual,+ isEmptyPosting,+ hasBalanceAssignment,+ hasAmount,+ isExplicitAmount,+ postingAllTags,+ transactionAllTags,+ relatedPostings,+ postingStripCosts,+ postingApplyAliases,+ postingApplyCommodityStyles,+ postingStyleAmounts,+ postingAddTags,+ postingAddHiddenAndMaybeVisibleTag,+ postingRemoveHiddenAndVisibleTag,+ -- * date operations+ postingDate,+ postingDate2,+ postingDateOrDate2,+ -- * account name operations+ accountNamesFromPostings,+ -- * comment/tag operations+ commentJoin,+ commentAddTag,+ commentAddTagUnspaced,+ commentAddTagNextLine,+ commentPrependTag,+ generatedTransactionTagName,+ modifiedTransactionTagName,+ generatedPostingTagName,+ feesplitPostingTagName,+ lotsplitPostingTagName,+ lotParentAssertionTagName,+ postingHasTag,+ costPostingTagName,+ conversionPostingTagName,+ imbalancePostingTagName,++ -- * arithmetic+ sumPostings,+ postingNegate,+ postingNegateMainAmount,+ -- * rendering+ showPosting,+ showPostingLines,+ postingAsLines,+ postingsAsLines,+ postingsAsLinesWithLayout,+ postingIndent,+ showAccountName,+ renderCommentLines,+ showBalanceAssertion,+ balanceAssertionOperatorB,+ balanceAssertionAmountB,+ PostingLayout(..),+ defaultPostingLayout,+ defaultDecimalMarkColumn,+ PostingWidths(..),+ AmountCols(..),+ amountIntegerWidth,+ -- * misc.+ postingTransformAmount,+ postingApplyValuation,+ postingToCost,+ postingAddInferredEquityPostings,+ postingsAddInferredEquityPostings,+ postingPriceDirectivesFromCost,+ postingCommodities,+ tests_Posting+)+where++import Data.Default (def)+import Data.Foldable (asum)+import Data.Function ((&))+import Data.Map qualified as M+import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.List (nub, sort, union)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Set qualified as S+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.Calendar (Day)+import Safe (maximumBound)+import Text.DocLayout (realLength)+import Text.Tabular.AsciiWide hiding (render)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.Amount+import Hledger.Data.AccountName+import Hledger.Data.Dates (nulldate)+import Hledger.Data.Valuation+++-- | Special tags hledger sometimes adds to mark various things.+-- These should be hidden tag names, beginning with _.+-- With --verbose-tags, the equivalent visible tags will also be added.+-- These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.+generatedTransactionTagName, modifiedTransactionTagName, costPostingTagName, conversionPostingTagName, imbalancePostingTagName, generatedPostingTagName, feesplitPostingTagName, lotsplitPostingTagName, lotParentAssertionTagName :: TagName+generatedTransactionTagName = "_generated-transaction" -- transactions generated by a periodic txn rule+modifiedTransactionTagName = "_modified-transaction" -- transactions modified by an auto posting rule+generatedPostingTagName = "_generated-posting" -- postings generated by hledger for one reason or another+costPostingTagName = "_cost-posting" -- postings which have or could have a cost that's equivalent to nearby conversion postings+conversionPostingTagName = "_conversion-posting" -- postings to an equity account of Conversion type which have an amount that's equivalent to a nearby costful or potentially costful posting+imbalancePostingTagName = "_imbalance-posting" -- postings generated by --infer-imbalance, showing a transaction's tolerated imbalance+feesplitPostingTagName = "_feesplit-posting" -- a synthetic posting carved off an existing posting by lot transfer auto-split (the fee fragment); hidden by default in print+lotsplitPostingTagName = "_lotsplit-posting" -- a tail fragment from a per-lot split, dropped when collapsing to the user's original form+lotParentAssertionTagName = "_lot-parent-assertion" -- a synthetic zero-amount posting on the parent account, carrying a balance assertion relocated from a posting that was split into lot subaccounts++-- | True if the posting has a tag with the given name (hidden or visible).+postingHasTag :: TagName -> Posting -> Bool+postingHasTag name p = any ((==name) . fst) (ptags p)++instance HasAmounts BalanceAssertion where+ styleAmounts styles ba@BalanceAssertion{baamount} = ba{baamount=styleAmounts styles baamount}++instance HasAmounts Posting where+ styleAmounts styles p@Posting{pamount, pbalanceassertion} =+ p{ pamount=styleAmounts styles pamount+ ,pbalanceassertion=styleAmounts styles pbalanceassertion + }++{-# DEPRECATED postingApplyCommodityStyles "please use styleAmounts instead" #-}+-- | Find and apply the appropriate display style to the posting amounts+-- in each commodity (see journalCommodityStyles).+-- Main amount precisions may be set or not according to the styles, but cost precisions are not set.+postingApplyCommodityStyles :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting+postingApplyCommodityStyles = styleAmounts++{-# DEPRECATED postingStyleAmounts "please use styleAmounts instead" #-}+-- | Like postingApplyCommodityStyles, but neither+-- main amount precisions or cost precisions are set.+postingStyleAmounts :: M.Map CommoditySymbol AmountStyle -> Posting -> Posting+postingStyleAmounts = styleAmounts++nullposting, posting :: Posting+nullposting = Posting+ {pdate=Nothing+ ,pdate2=Nothing+ ,pstatus=Unmarked+ ,paccount=""+ ,pamount=nullmixedamt+ ,pcomment=""+ ,preal=RealPosting+ ,ptags=[]+ ,pbalanceassertion=Nothing+ ,ptransaction=Nothing+ ,poriginal=Nothing+ }+posting = nullposting++-- constructors++-- | Make a posting to an account.+post :: AccountName -> Amount -> Posting+post acc amt = posting {paccount=acc, pamount=mixedAmount amt}++-- | Make a virtual (unbalanced) posting to an account.+vpost :: AccountName -> Amount -> Posting+vpost acc amt = (post acc amt){preal=VirtualPosting}++-- | Make a posting to an account, maybe with a balance assertion.+post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting+post' acc amt ass = posting {paccount=acc, pamount=mixedAmount amt, pbalanceassertion=ass}++-- | Make a virtual (unbalanced) posting to an account, maybe with a balance assertion.+vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting+vpost' acc amt ass = (post' acc amt ass){preal=VirtualPosting, pbalanceassertion=ass}++nullassertion :: BalanceAssertion+nullassertion = BalanceAssertion+ {baamount=nullamt+ ,batotal=False+ ,bainclusive=False+ ,baposition=initialPos ""+ }++-- | Make a partial, exclusive balance assertion.+balassert :: Amount -> Maybe BalanceAssertion+balassert amt = Just $ nullassertion{baamount=amt}++-- | Make a total, exclusive balance assertion.+balassertTot :: Amount -> Maybe BalanceAssertion+balassertTot amt = Just $ nullassertion{baamount=amt, batotal=True}++-- | Make a partial, inclusive balance assertion.+balassertParInc :: Amount -> Maybe BalanceAssertion+balassertParInc amt = Just $ nullassertion{baamount=amt, bainclusive=True}++-- | Make a total, inclusive balance assertion.+balassertTotInc :: Amount -> Maybe BalanceAssertion+balassertTotInc amt = Just $ nullassertion{baamount=amt, batotal=True, bainclusive=True}++-- | Render the balance-assertion operator glyph: \"=\", \"==\", \"=*\", or \"==*\".+balanceAssertionOperatorB :: BalanceAssertion -> WideBuilder+balanceAssertionOperatorB ba =+ singleton '=' <> eq <> ast+ where+ eq = if batotal ba then singleton '=' else mempty+ ast = if bainclusive ba then singleton '*' else mempty+ singleton c = WideBuilder (TB.singleton c) 1++-- | Render a balance assertion's expected amount, using the given AmountFormat.+balanceAssertionAmountB :: AmountFormat -> BalanceAssertion -> WideBuilder+balanceAssertionAmountB fmt = showAmountB fmt . baamount++-- | Render a balance assertion, as the =[=][*] symbol and expected amount,+-- separated by a single space. Used by the legacy hledger 1.x layout path;+-- the decimal-aligned path renders the operator and amount separately so it+-- can pad between them.+showBalanceAssertion :: BalanceAssertion -> WideBuilder+showBalanceAssertion ba =+ balanceAssertionOperatorB ba+ <> WideBuilder (TB.singleton ' ') 1+ <> balanceAssertionAmountB def{displayZeroCommodity=True, displayForceDecimalMark=True} ba++-- Get the original posting, if any.+originalPosting :: Posting -> Posting+originalPosting p = fromMaybe p $ poriginal p++showPosting :: Posting -> String+showPosting p = T.unpack . T.unlines $ postingsAsLines defaultFmt False [p]++-- | How posting lines should be aligned by 'postingsAsLines' / 'showTransaction'.+data PostingLayout+ = LayoutHledger1 -- ^ Right-align amounts in a 12+-char field, as in hledger 1.x.+ | LayoutDecimal !Int -- ^ Align the first decimal mark of each amount at the given target column.+ deriving (Eq, Show)++-- | Default visible column (1-indexed) where posting amount decimal marks+-- should be aligned in `print` output. Used as the target unless a+-- transaction's account names + amount widths force amounts further right.+defaultDecimalMarkColumn :: Int+defaultDecimalMarkColumn = 53++-- | Default posting layout: decimal-mark alignment at column 'defaultDecimalMarkColumn'.+defaultPostingLayout :: PostingLayout+defaultPostingLayout = LayoutDecimal defaultDecimalMarkColumn++-- | Visible-character widths derived from one posting, for cross-posting+-- alignment in 'postingsAsLinesDecimal'. All fields are independent of+-- layout (decimalcol etc.), so they can be safely consumed inside the+-- lazy knot that decides those columns.+data PostingWidths = PostingWidths+ { pwAcct :: !Int+ -- ^ Account-name visible width. Used to size the account/status field+ -- so all postings' account names line up.+ , pwLeft :: !Int+ -- ^ Main amount's integer-side width: characters from the start of the+ -- rendered amount up to (but not including) the decimal mark.+ -- Includes any L-side commodity prefix (e.g. \"$\") and sign.+ -- Computed by 'amountIntegerWidth'. For a multi-commodity amount+ -- rendered on multiple lines, this is the max across rows.+ -- Used to position the decimal mark column.+ , pwRight :: !Int+ -- ^ Main amount's post-decimal width: characters from the decimal mark+ -- (inclusive) to the end of the rendered amount, including any cost+ -- annotation (\"\@ 1.20 USD\") and any R-side commodity suffix.+ -- Equivalent to @wbWidth wb - lw@ per amount row, taken as the max+ -- across rows. Used to position the assertion @=@ column one space+ -- past the rightmost amount.+ , pwOperator :: !Int+ -- ^ Visible width of this posting's balance-assertion operator:+ -- 1 (@=@), 2 (@==@ or @=*@), 3 (@==*@), or 0 if the posting has no+ -- @pbalanceassertion@. Used to position the assertion-amount column+ -- one space past the widest operator.+ , pwAsnLeft :: !Int+ -- ^ Assertion amount's integer-side width, computed via+ -- 'amountIntegerWidth' on @baamount@ with the same display options+ -- used for the main amount. 0 if no assertion. Used to decimal-align+ -- the assertion amounts.+ }+ deriving (Eq, Show)++-- | The three target columns derived in the knot of 'postingsAsLinesDecimal'+-- and consumed by 'postingAsLines' for aligning the main amount, the @=@ glyph,+-- and the assertion amount. @acEquals@ and @acAssDecMark@ are 0 when no posting in+-- the group has a balance assertion (in which case the renderer never+-- consults them).+data AmountCols = AmountCols+ { acDecMark :: !Int -- ^ Column for the main amount's decimal mark.+ , acEquals :: !Int -- ^ Column for the first @=@ of the balance assertion/assignment.+ , acAssDecMark :: !Int -- ^ Column for the assertion amount's decimal mark.+ }+ deriving (Eq, Show)++-- | Visible width of the part of a rendered amount that appears before its+-- (real or virtual) decimal mark — i.e. from the start of the amount through+-- the last digit of the integer portion (including any L-side commodity+-- prefix). Computed structurally from the 'Amount' data rather than by+-- parsing the rendered text, so it is unaffected by trailing cost annotations,+-- lot syntax, comments, or digits that may appear inside a commodity name.+-- Used to align integer-ends across postings at decimalcol-1.+amountIntegerWidth :: AmountFormat -> Amount -> Int+amountIntegerWidth opts a+ -- The "AUTO" commodity marks a missing amount; showAmountB renders it as+ -- empty, so its left-width is 0.+ | acommodity a == "AUTO" = 0+ | otherwise = commodityPrefixW + quantityIntegerW+ where+ s = astyle a+ -- Width of the integer portion of the rendered quantity. Renders the amount+ -- truncated to integer with precision 0; the result has no decimal mark or+ -- fractional digits, so its width is exactly sign + integer-digits + group-seps.+ -- Sign is added explicitly to handle the -0.x → 0 truncation case — but only+ -- when the rendered amount will actually show a sign (i.e., it has fractional+ -- digits). At Precision 0 a value rounding to 0 shows as "0" with no sign,+ -- so no extra slot is reserved.+ quantityIntegerW =+ let intAmt = a{ aquantity = fromInteger (truncate (aquantity a) :: Integer)+ , astyle = s{asprecision = Precision 0}+ }+ w = wbWidth (showAmountQuantity False intAmt)+ showsFractional = case asprecision s of+ Precision 0 -> False+ _ -> True+ signLost = aquantity a < 0 && (truncate (aquantity a) :: Integer) == 0+ && showsFractional+ in w + (if signLost then 1 else 0)+ -- Width of the commodity portion when it appears as a prefix (L-side).+ commodityPrefixW+ | ascommodityside s == L =+ let comm = (if displayQuotes opts then quoteCommoditySymbolIfNeeded else id) (acommodity a)+ spaceW = if not (T.null comm) && ascommodityspaced s then 1 else 0+ in realLength comm + spaceW+ | otherwise = 0++-- | Visible width of a posting's status prefix (e.g. \"* \" or \"! \"), or 0+-- if it has no status flag. Used to compute account-field width per transaction.+postingStatusWidth :: Posting -> Int+postingStatusWidth p = case pstatus p of+ Unmarked -> 0+ _ -> 2++-- | Render a posting, at the appropriate width for aligning with+-- its siblings if any. Used by the rewrite command.+showPostingLines :: Posting -> [Text]+showPostingLines p = fst $ postingAsLines defaultFmt False False maxstatuswidth maxacctwidth dc p+ where+ siblings = maybe [p] tpostings $ ptransaction p+ linesWithWidths = map (postingAsLines defaultFmt False False maxstatuswidth maxacctwidth dc) siblings+ maxstatuswidth = maximumBound 0 $ map postingStatusWidth siblings+ pws = map snd linesWithWidths+ maxacctwidth = maximumBound 0 $ map pwAcct pws+ maxleftwidth = maximumBound 0 $ map pwLeft pws+ maxrightwidth = maximumBound 0 $ map pwRight pws+ maxoperatorwidth = maximumBound 0 $ map pwOperator pws+ maxasnleftwidth = maximumBound 0 $ map pwAsnLeft pws+ decimalcol = max defaultDecimalMarkColumn (maxacctwidth + maxstatuswidth + 7 + maxleftwidth)+ eqcol = decimalcol + maxrightwidth + 1+ asndecimalcol = eqcol + maxoperatorwidth + 1 + maxasnleftwidth+ dc = AmountCols decimalcol eqcol asndecimalcol++-- | Render a transaction's postings as indented lines, suitable for `print` output,+-- using the default posting layout (decimal-mark alignment at column 53).+--+-- Normally these will be in valid journal syntax which hledger can reparse+-- (though they may include no-longer-valid balance assertions).+-- Explicit amounts are shown, implicit amounts are not.+--+-- Postings with multicommodity explicit amounts are handled as follows:+-- if onelineamounts is true, these amounts are shown on one line,+-- comma-separated, and the output will not be valid journal syntax.+-- Otherwise, they are shown as several similar postings, one per commodity.+-- When the posting has a balance assertion, it is attached to the last of these postings.+--+-- Note: a few fields of the caller's @AmountFormat@ are overridden internally;+-- see 'postingAsLines' for details.+--+postingsAsLines :: AmountFormat -> Bool -> [Posting] -> [Text]+postingsAsLines basefmt onelineamounts =+ postingsAsLinesWithLayout basefmt onelineamounts defaultPostingLayout++-- | Like 'postingsAsLines' but with an explicit 'PostingLayout': either the+-- new decimal-mark alignment (with a target column) or the older hledger 1.x+-- right-aligned layout.+postingsAsLinesWithLayout :: AmountFormat -> Bool -> PostingLayout -> [Posting] -> [Text]+postingsAsLinesWithLayout basefmt onelineamounts layout ps = case layout of+ LayoutDecimal targetcol -> postingsAsLinesDecimal basefmt onelineamounts targetcol ps+ LayoutHledger1 -> postingsAsLinesHledger1 basefmt onelineamounts ps++-- | Decimal-mark-aligned layout (the new default). The target column is bumped+-- right per-transaction if needed to keep at least 2 spaces between each+-- account name and amount.+postingsAsLinesDecimal :: AmountFormat -> Bool -> Int -> [Posting] -> [Text]+postingsAsLinesDecimal basefmt onelineamounts targetcol ps = concatMap fst linesWithWidths+ where+ -- Lazy knot: postingAsLines takes the layout columns (AmountCols) and+ -- returns this posting's PostingWidths; the layout columns are computed+ -- from the cross-posting maxes of those widths. This terminates only+ -- because PostingWidths fields do NOT depend on AmountCols — they are+ -- structural widths of the posting's amount/account/assertion data, while+ -- AmountCols only affects the rendered text (the first element of each+ -- linesWithWidths pair, which we don't force until concatMap fst above).+ -- If any PostingWidths field ever started depending on AmountCols this+ -- would diverge. Keep that invariant when changing postingAsLines.+ linesWithWidths = map (postingAsLines basefmt False onelineamounts maxstatuswidth maxacctwidth dc) ps+ maxstatuswidth = maximumBound 0 $ map postingStatusWidth ps+ pws = map snd linesWithWidths+ maxacctwidth = maximumBound 0 $ map pwAcct pws+ maxleftwidth = maximumBound 0 $ map pwLeft pws+ maxrightwidth = maximumBound 0 $ map pwRight pws+ maxoperatorwidth = maximumBound 0 $ map pwOperator pws+ maxasnleftwidth = maximumBound 0 $ map pwAsnLeft pws+ decimalcol = max targetcol (maxacctwidth + maxstatuswidth + 7 + maxleftwidth)+ -- eqcol / asndecimalcol are 0 (and unused by the renderer) when no+ -- posting in the group has a balance assertion.+ hasAssertion = maxoperatorwidth > 0+ eqcol = if hasAssertion then decimalcol + maxrightwidth + 1 else 0+ asndecimalcol = if hasAssertion then eqcol + maxoperatorwidth + 1 + maxasnleftwidth else 0+ dc = AmountCols decimalcol eqcol asndecimalcol++-- | hledger 1.x layout: right-align amounts within a 12+-char field, lifted+-- verbatim from the pre-decimal-alignment code. Kept as an escape hatch for+-- users who prefer the old appearance via @print --layout=hledger1@.+postingsAsLinesHledger1 :: AmountFormat -> Bool -> [Posting] -> [Text]+postingsAsLinesHledger1 basefmt onelineamounts ps = concatMap first3 linesWithWidths+ where+ linesWithWidths = map (postingAsLinesHledger1 basefmt False onelineamounts maxacctwidth maxamtwidth) ps+ maxacctwidth = maximumBound 0 $ map second3 linesWithWidths+ maxamtwidth = maximumBound 0 $ map third3 linesWithWidths++-- | hledger 1.x per-posting renderer: right-aligned amounts.+-- This is the pre-decimal-alignment 'postingAsLines' body, restored verbatim.+postingAsLinesHledger1 :: AmountFormat -> Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)+postingAsLinesHledger1 basefmt elideamount onelineamounts acctwidth amtwidth p =+ (concatMap (++ newlinecomments) postingblocks, thisacctwidth, thisamtwidth)+ where+ postingblocks = [map T.stripEnd . T.lines . TL.toStrict $+ render [ textCell BottomLeft statusandaccount+ , textCell BottomLeft " "+ , Cell BottomLeft [pad amt]+ , Cell BottomLeft [assertion]+ , textCell BottomLeft samelinecomment+ ]+ | (amt,assertion) <- shownAmountsAssertions]+ render = renderRow def{tableBorders=False, borderSpaces=False} . Group NoLine . map Header+ pad amt = WideBuilder (TB.fromText $ T.replicate w " ") w <> amt+ where w = max 12 amtwidth - wbWidth amt -- min. 12 for backwards compatibility++ pacctstr p' = showAccountName Nothing (preal p') (paccount p')+ pstatusandacct p' = pstatusprefix p' <> pacctstr p'+ pstatusprefix p' = case pstatus p' of+ Unmarked -> ""+ s -> T.pack (show s) <> " "++ -- prices are considered part of the amount string when right-aligning amounts.+ -- The knot between amtwidth and thisamtwidth is tied via lazy evaluation, so+ -- thisamtwidth must not depend on amtwidth.+ shownAmounts+ | elideamount = [mempty]+ | otherwise = showMixedAmountLinesB displayopts $ pamount p+ where displayopts = basefmt{+ displayZeroCommodity=True, displayForceDecimalMark=True, displayOneLine=onelineamounts+ }+ thisamtwidth = maximumBound 0 $ map wbWidth shownAmounts++ shownAmountsAssertions = zip shownAmounts shownAssertions+ where+ shownAssertions = replicate (length shownAmounts - 1) mempty ++ [assertion]+ assertion = maybe mempty ((WideBuilder (TB.singleton ' ') 1 <>).showBalanceAssertion) $ pbalanceassertion p++ statusandaccount = postingIndent . fitText (Just $ 2 + acctwidth) Nothing False True $ pstatusandacct p+ thisacctwidth = realLength $ pacctstr p++ (samelinecomment, newlinecomments) =+ case renderCommentLines (pcomment p) of [] -> ("",[])+ c:cs -> (c,cs)++-- | Render one posting, on one or more lines, suitable for `print` output.+-- Also returns the 'PostingWidths' computed from this posting's structural+-- data (account name, main amount, assertion operator / amount), used by the+-- caller's lazy knot to derive the layout columns.+--+-- There will be an indented account name, plus one or more of status flag,+-- posting amount, balance assertion, same-line comment, next-line comments.+--+-- If the posting's amount is implicit or if elideamount is true, no amount is shown.+-- If the posting's amount is explicit and multi-commodity, multiple similar+-- postings are shown, one for each commodity, to help produce parseable journal syntax.+-- Or if onelineamounts is true, such amounts are shown on one line, comma-separated+-- (and the output will not be valid journal syntax).+--+-- If an amount is zero, any commodity symbol attached to it is shown+-- (and the corresponding commodity display style is used).+--+-- Three target columns are supplied via 'AmountCols':+--+-- * @acDecMark@ — the main amount's decimal mark is left-padded to land here.+-- With multi-commodity postings rendered on multiple lines, every line is+-- aligned at this column. Callers (postingsAsLines, showPostingLines) pick+-- it so that at least 2 spaces remain between the widest account name and+-- the start of the amount area.+-- * @acEquals@ — the first @=@ of any balance-assertion operator (@=@, @==@, @=*@,+-- or @==*@) is padded to land here, one space past the rightmost main+-- amount across all postings.+-- * @acAssDecMark@ — the assertion amount's decimal mark is padded to land+-- here. The leftmost assertion amount starts one space past the widest+-- operator; narrower-operator postings get extra space so all assertion+-- amounts line up on their decimals.+--+-- @acEquals@ and @acAssDecMark@ are unused (and may be 0) when no posting in the+-- group has a balance assertion.+--+-- Note: this function overrides four fields of the caller's @AmountFormat@:+--+-- * @displayZeroCommodity = True@ — always show the commodity on zero amounts+-- so they participate in alignment.+-- * @displayForceDecimalMark = True@ — force a decimal mark when digit groups+-- are shown, for unambiguous display.+-- * @displayOneLine = onelineamounts@ — driven by this function's parameter.+-- * @displayMinWidth = Nothing@ — disable the legacy right-alignment of+-- multi-commodity amount lines, since this function provides its own+-- decimal-mark alignment.+--+postingAsLines :: AmountFormat -> Bool -> Bool -> Int -> Int -> AmountCols -> Posting -> ([Text], PostingWidths)+postingAsLines basefmt elideamount onelineamounts statuswidth acctwidth dc p =+ (concatMap (++ newlinecomments) postingblocks, widths)+ where+ AmountCols{acDecMark=decimalcol, acEquals=eqcol, acAssDecMark=asndecimalcol} = dc++ widths = PostingWidths+ { pwAcct = thisacctwidth+ , pwLeft = thisleftwidth+ , pwRight = thisrightwidth+ , pwOperator = thisoperatorwidth+ , pwAsnLeft = thisasnleftwidth+ }++ -- This needs to be converted to strict Text in order to strip trailing+ -- spaces. This adds a small amount of inefficiency, and the only difference+ -- is whether there are trailing spaces in print (and related) reports. This+ -- could be removed and we could just keep everything as a Text Builder, but+ -- would require adding trailing spaces to 42 failing tests.+ postingblocks = [map T.stripEnd . T.lines . TL.toStrict $+ render [ textCell BottomLeft statusandaccount+ , textCell BottomLeft " "+ , Cell BottomLeft [padLeft (decimalcol - acctwidth - statuswidth - 7 - lw) amt]+ , Cell BottomLeft [asn]+ , textCell BottomLeft samelinecomment+ ]+ | (amt, lw, asn) <- amountAssertionRows]+ render = renderRow def{tableBorders=False, borderSpaces=False} . Group NoLine . map Header++ -- Prepend N space characters to a WideBuilder; N is floored at 0.+ -- The amount area starts at column (acctwidth + statuswidth + 7) (1-indexed):+ -- 4 indent + (statuswidth + acctwidth) status/account field + 2 separator.+ -- For the main amount, a pre-decimal width lw means we want the decimal+ -- at column (acctwidth + statuswidth + 7 + lw + N), so N =+ -- decimalcol - (acctwidth + statuswidth + 7 + lw).+ padLeft n b = WideBuilder (TB.fromText $ T.replicate w " ") w <> b+ where w = max 0 n++ pacctstr p' = showAccountName Nothing (preal p') (paccount p')+ pstatusandacct p' = pstatusprefix p' <> pacctstr p'+ pstatusprefix p' = case pstatus p' of+ Unmarked -> ""+ s -> T.pack (show s) <> " "++ -- Display options used to render BOTH the main amount and the assertion+ -- amount, so their lw / rw computations match the rendered text and the+ -- two amounts share commodity styling within a transaction.+ -- See postingAsLines's haddock for which fields of basefmt are overridden.+ displayopts = basefmt{+ displayZeroCommodity = True+ , displayForceDecimalMark = True+ , displayOneLine = onelineamounts+ , displayMinWidth = Nothing+ }++ -- Per-amount-row triples (wb, lw, rw): the rendered builder, its+ -- integer-side visible width left of the decimal, and its post-decimal+ -- visible width (rw = wbWidth wb - lw). All structural; must remain+ -- independent of any layout column (see the lazy knot in+ -- postingsAsLinesDecimal).+ amountRows+ | elideamount = [(mempty, 0, 0)]+ | otherwise = case showMixedAmountLinesPartsB displayopts (pamount p) of+ [] -> [(mempty, 0, 0)]+ xs -> [ (wb, lw, wbWidth wb - lw)+ | (wb, a) <- xs+ , let lw = amountIntegerWidth displayopts a]++ thisleftwidth = maximumBound 0 [lw | (_, lw, _) <- amountRows]+ thisrightwidth = maximumBound 0 [rw | (_, _, rw) <- amountRows]++ -- Per-posting balance-assertion widths (0 if the posting has no assertion).+ (thisoperatorwidth, thisasnleftwidth) = case pbalanceassertion p of+ Nothing -> (0, 0)+ Just ba -> ( wbWidth (balanceAssertionOperatorB ba)+ , amountIntegerWidth displayopts (baamount ba)+ )++ -- The balance-assertion cell on the last amount row (if there's an+ -- assertion). Lays out as: pad1 + operator + pad2 + amount, where pad1+ -- lifts the operator to eqcol and pad2 lifts the assertion amount's+ -- decimal mark to asndecimalcol. By construction in the knot, pad1 and+ -- pad2 are >= 1 when any sibling has the maximum value; floor at 1+ -- defensively in case of a single-posting context with no cross-sibling+ -- alignment to satisfy.+ assertionWB = case pbalanceassertion p of+ Nothing -> mempty+ Just ba ->+ let pad1Len = max 1 (eqcol - decimalcol - thisrightwidth)+ pad2Len = max 1 (asndecimalcol - eqcol - thisoperatorwidth - thisasnleftwidth)+ in padLeft pad1Len (balanceAssertionOperatorB ba)+ <> padLeft pad2Len (balanceAssertionAmountB displayopts ba)++ -- Pair each amount row with its assertion (only on the last row).+ amountAssertionRows =+ [(wb, lw, asn) | ((wb, lw, _), asn) <- zip amountRows shownAssertions]+ where+ shownAssertions = replicate (length amountRows - 1) mempty ++ [assertionWB]++ -- pad to the maximum account name width, plus statuswidth chars to leave+ -- room for status flags (where any sibling has one), to keep amounts aligned+ statusandaccount = postingIndent . fitText (Just $ statuswidth + acctwidth) Nothing False True $ pstatusandacct p+ thisacctwidth = realLength $ pacctstr p++ (samelinecomment, newlinecomments) =+ case renderCommentLines (pcomment p) of [] -> ("",[])+ c:cs -> (c,cs)++-- | Show an account name, clipped to the given width if any, and+-- appropriately bracketed/parenthesised for the given posting realness.+showAccountName :: Maybe Int -> PostingRealness -> AccountName -> Text+showAccountName w = fmt+ where+ fmt RealPosting = maybe id T.take w+ fmt VirtualPosting = wrap "(" ")" . maybe id (T.takeEnd . subtract 2) w+ fmt BalancedVirtualPosting = wrap "[" "]" . maybe id (T.takeEnd . subtract 2) w++-- | Render a transaction or posting's comment as indented, semicolon-prefixed comment lines.+-- The first line (unless empty) will have leading space, subsequent lines will have a larger indent.+renderCommentLines :: Text -> [Text]+renderCommentLines t =+ case T.lines t of+ [] -> []+ [l] -> [commentSpace $ comment l] -- single-line comment+ ("":ls) -> "" : map (postingIndent . comment) ls -- multi-line comment with empty first line+ (l:ls) -> commentSpace (comment l) : map (postingIndent . comment) ls+ where+ comment = ("; "<>)++-- | Prepend a suitable indent for a posting (or transaction/posting comment) line.+postingIndent :: Text -> Text+postingIndent = (" "<>)++-- | Prepend the space required before a same-line comment.+commentSpace :: Text -> Text+commentSpace = (" "<>)+++isReal :: Posting -> Bool+isReal p = preal p == RealPosting++isVirtual :: Posting -> Bool+isVirtual p = preal p == VirtualPosting++isBalancedVirtual :: Posting -> Bool+isBalancedVirtual p = preal p == BalancedVirtualPosting++hasAmount :: Posting -> Bool+hasAmount = not . isMissingMixedAmount . pamount++-- | Was this posting's amount explicitly written by the user, rather than+-- inferred by hledger ? Amounts inferred from a balance assignment are+-- also counted as explicit, since they are the same as what the user wrote.+-- Inferred postings are recognised by their preserved original posting having a missing amount.+isExplicitAmount :: Posting -> Bool+isExplicitAmount p =+ let orig = originalPosting p+ in not (isMissingMixedAmount (pamount orig)) || isJust (pbalanceassertion orig)++hasBalanceAssignment :: Posting -> Bool+hasBalanceAssignment p = not (hasAmount p) && isJust (pbalanceassertion p)++-- | Sorted unique account names referenced by these postings.+accountNamesFromPostings :: [Posting] -> [AccountName]+accountNamesFromPostings = S.toList . S.fromList . map paccount++-- | Sum all amounts from a list of postings.+sumPostings :: [Posting] -> MixedAmount+sumPostings = foldl' (\amt p -> maPlus amt $ pamount p) nullmixedamt++-- | Negate the posting's main amount and balance assertion amount if any.+postingNegate :: Posting -> Posting+postingNegate p@Posting{pamount=a, pbalanceassertion=mb} =+ p{pamount=negate a, pbalanceassertion=fmap balanceAssertionNegate mb}+ where+ balanceAssertionNegate b@BalanceAssertion{baamount=ba} = b{baamount=negate ba}++-- | Negate the posting's main amount but not the balance assertion amount.+postingNegateMainAmount :: Posting -> Posting+postingNegateMainAmount p@Posting{pamount=a} = p{pamount=negate a}++-- | Strip all prices from a Posting.+postingStripCosts :: Posting -> Posting+postingStripCosts = postingTransformAmount mixedAmountStripCosts++-- | Get a posting's (primary) date - it's own primary date if specified,+-- otherwise the parent transaction's primary date, or the null date if+-- there is no parent transaction.+postingDate :: Posting -> Day+postingDate p = fromMaybe nulldate $ asum dates+ where dates = [ pdate p, tdate <$> ptransaction p ]++-- | Get a posting's secondary (secondary) date, which is the first of:+-- posting's secondary date, transaction's secondary date, posting's+-- primary date, transaction's primary date, or the null date if there is+-- no parent transaction.+postingDate2 :: Posting -> Day+postingDate2 p = fromMaybe nulldate $ asum dates+ where dates = [ pdate2 p+ , tdate2 =<< ptransaction p+ , pdate p+ , tdate <$> ptransaction p+ ]++-- | Get a posting's primary or secondary date, as specified.+postingDateOrDate2 :: WhichDate -> Posting -> Day+postingDateOrDate2 PrimaryDate = postingDate+postingDateOrDate2 SecondaryDate = postingDate2++-- | Get a posting's status. This is cleared or pending if those are+-- explicitly set on the posting, otherwise the status of its parent+-- transaction, or unmarked if there is no parent transaction. (Note+-- the ambiguity, unmarked can mean "posting and transaction are both+-- unmarked" or "posting is unmarked and don't know about the transaction".+postingStatus :: Posting -> Status+postingStatus Posting{pstatus=s, ptransaction=mt} = case s of+ Unmarked -> maybe Unmarked tstatus mt+ _ -> s++-- | Get the commodity symbols used in a posting's amounts (not including costs).+postingCommodities :: Posting -> [CommoditySymbol]+postingCommodities = map acommodity . filter (not . isMissingAmount) . amountsRaw . pamount+ where isMissingAmount a = acommodity a == "AUTO"++-- | Tags for this posting including any inherited from its parent transaction.+postingAllTags :: Posting -> [Tag]+postingAllTags p = ptags p ++ maybe [] ttags (ptransaction p)++-- | Tags for this transaction including any from its postings (which includes any from the postings' accounts).+transactionAllTags :: Transaction -> [Tag]+transactionAllTags t = ttags t ++ concatMap ptags (tpostings t)++-- Get the other postings from this posting's transaction.+relatedPostings :: Posting -> [Posting]+relatedPostings p@Posting{ptransaction=Just t} = filter (/= p) $ tpostings t+relatedPostings _ = []++isEmptyPosting :: Posting -> Bool+isEmptyPosting = mixedAmountLooksZero . pamount++-- | Apply some account aliases to the posting's account name, as described by accountNameApplyAliases.+-- This can fail due to a bad replacement pattern in a regular expression alias.+postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting+postingApplyAliases aliases p@Posting{paccount} =+ case accountNameApplyAliases aliases paccount of+ Right a -> Right p{paccount=a}+ Left e -> Left err+ where+ err = "problem while applying account aliases:\n" ++ pshow aliases+ ++ "\n to account name: "++T.unpack paccount++"\n "++e++-- | Add tags to a posting, discarding any for which the posting already has a value.+-- Note this does not add tags to the posting's comment.+postingAddTags :: Posting -> [Tag] -> Posting+postingAddTags p@Posting{ptags} tags = p{ptags=ptags `union` tags}++-- | Add the given hidden tag to a posting; and with a true argument,+-- also add the equivalent visible tag to the posting's tags and comment fields.+-- If the posting already has these tags (with any value), do nothing.+postingAddHiddenAndMaybeVisibleTag :: Bool -> Bool -> HiddenTag -> Posting -> Posting+postingAddHiddenAndMaybeVisibleTag prepend verbosetags ht p@Posting{pcomment=c, ptags} =+ (p `postingAddTags` ([ht] <> [vt |verbosetags]))+ {pcomment=if verbosetags && not hadtag then addFn c vt else c}+ where+ addFn = if prepend then commentPrependTag else commentAddTag+ vt@(vname,_) = toVisibleTag ht+ hadtag = any ((== (T.toLower vname)) . T.toLower . fst) ptags -- XXX should regex-quote vname++-- | Remove the given hidden tag from a posting, and the equivalent visible tag+-- if 'postingAddHiddenAndMaybeVisibleTag' added one: from the posting's tags,+-- and from its comment, where it appears as @NAME: VALUE@, comma-separated from+-- any other content.+postingRemoveHiddenAndVisibleTag :: HiddenTag -> Posting -> Posting+postingRemoveHiddenAndVisibleTag (hname,_) p@Posting{pcomment, ptags} =+ p{ptags = filter ((`notElem` [hname, vname]) . fst) ptags, pcomment = maybe pcomment removeFromComment $ lookup vname ptags}+ where+ vname = toVisibleTagName hname+ removeFromComment v+ | c' /= pcomment = c'+ | otherwise = T.intercalate "\n" $ map (dropCommaPrefix . T.replace t "") $ T.lines pcomment+ where+ t = vname <> ": " <> v+ c' = T.replace (", " <> t) "" pcomment+ dropCommaPrefix l = fromMaybe l $ T.stripPrefix ", " l++-- | Apply a specified valuation to this posting's amount, using the+-- provided price oracle, commodity styles, and reference dates.+-- See amountApplyValuation.+postingApplyValuation :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting+postingApplyValuation priceoracle styles periodlast today v p =+ postingTransformAmount (mixedAmountApplyValuation priceoracle styles periodlast today (postingDate p) v) p++-- | Maybe convert this 'Posting's amount to cost: to cost basis where known,+-- else transacted cost (ToCost); or to transacted cost (ToTransactedCost).+postingToCost :: ConversionOp -> Posting -> Maybe Posting+postingToCost NoConversionOp p = Just p+postingToCost ToCost p = postingToCostWith mixedAmountCostBasis p+postingToCost ToTransactedCost p = postingToCostWith mixedAmountCost p++postingToCostWith :: (MixedAmount -> MixedAmount) -> Posting -> Maybe Posting+postingToCostWith tocost p+ -- If this is an equity conversion posting with an associated cost nearby, ignore it+ | conversionPostingTagName `elem` map fst (ptags p) && nocosts = Nothing+ | otherwise = Just $ postingTransformAmount tocost p+ where+ nocosts = (not . any (isJust . acost) . amountsRaw) $ pamount p++-- | Given a posting with costs, tag it as a cost posting and add+-- equity conversion postings after it, one pair per cost: one removing+-- the quantity transacted, one adding what it cost. See+-- 'postingsAddInferredEquityPostings'.+postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]+postingAddInferredEquityPostings verbosetags equityAcct p = postingsAddInferredEquityPostings verbosetags equityAcct [p]++-- | Like 'postingAddInferredEquityPostings', for a posting or for the+-- consecutive per-lot fragments of one posting (cf 'transactionInferEquityPostings'):+-- postings with costs are tagged as cost postings, and one pair of equity+-- conversion postings is added after them for each (commodity, cost commodity)+-- pair, with the fragments' quantities and costs summed, so that collapsing+-- lot detail can still merge the fragments.+--+-- The cost used is the cost basis where known (a lot disposal, after lot+-- processing), otherwise the transacted cost. So a disposal's conversion+-- postings record the disposed units at what they cost, keeping the entry+-- balanced at cost basis, and the difference from the proceeds stays in the+-- realised gain posting.+--+-- Postings already tagged as cost postings (having conversion postings) are left alone.+postingsAddInferredEquityPostings :: Bool -> Text -> [Posting] -> [Posting]+postingsAddInferredEquityPostings _ _ [] = []+postingsAddInferredEquityPostings verbosetags equityAcct ps@(p:_)+ | null costfulamounts = ps+ | otherwise = map tagIfCostful ps ++ concatMap makeConversionPostings (nub $ map commodityPair costfulamounts)+ where+ costfulamounts = concatMap postingCostfulAmounts ps+ postingCostfulAmounts q+ | costPostingTagName `elem` map fst (ptags q) = []+ | otherwise = filter (isJust . acost) . amountsRaw $ pamount q+ tagIfCostful q+ | null (postingCostfulAmounts q) = q+ | otherwise = postingAddHiddenAndMaybeVisibleTag False verbosetags (costPostingTagName,"") q+ commodityPair a = (commodity a, commodity (amountCost a))+ makeConversionPostings pair@(amtCommodity, costCommodity) =+ [ convp{ paccount = accountPrefix <> amtCommodity+ , pamount = maNegate $ maSum [mixedAmount (amountStripCost a){acostbasis = Nothing} | a <- as]+ }+ , convp{ paccount = accountPrefix <> costCommodity+ , pamount = maSum [mixedAmount (amountCostBasis a) | a <- as]+ }+ ]+ where+ as = filter ((== pair) . commodityPair) costfulamounts+ accountPrefix = mconcat [ equityAcct, ":", T.intercalate "-" $ sort [amtCommodity, costCommodity], ":"]+ convp = nullposting{pdate=pdate p, pdate2=pdate2 p, pstatus=pstatus p, ptransaction=ptransaction p}+ & postingAddHiddenAndMaybeVisibleTag False verbosetags (conversionPostingTagName,"")+ & postingAddHiddenAndMaybeVisibleTag False verbosetags (generatedPostingTagName, "")+ -- Take the commodity of an amount and collapse consecutive spaces to a single space+ commodity = T.unwords . filter (not . T.null) . T.words . acommodity++-- | Make a market price equivalent to this posting's amount's unit+-- price, if any.+postingPriceDirectivesFromCost :: Posting -> [PriceDirective]+postingPriceDirectivesFromCost p@Posting{pamount} =+ mapMaybe (amountPriceDirectiveFromCost $ postingDate p) $ amountsRaw pamount++-- | Apply a transform function to this posting's main amount (but not its balance assertion amount).+postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting+postingTransformAmount f p@Posting{pamount=a} = p{pamount=f a}++-- | Join two parts of a comment, eg a tag and another tag, or a tag+-- and a non-tag, on a single line. Interpolates a comma and space+-- unless one of the parts is empty.+commentJoin :: Text -> Text -> Text+commentJoin c1 c2+ | T.null c1 = c2+ | T.null c2 = c1+ | otherwise = c1 <> ", " <> c2++-- | Add a tag to a comment, comma-separated from any prior content.+-- A space is inserted following the colon, before the value.+commentAddTag :: Text -> Tag -> Text+commentAddTag c (t,v)+ | T.null c' = tag+ | otherwise = c' `commentJoin` tag+ where+ c' = T.stripEnd c+ tag = t <> ": " <> v++-- | Add a tag at the start of a comment, comma-separated from any prior content.+-- A space is inserted following the colon, before the value.+commentPrependTag :: Text -> Tag -> Text+commentPrependTag c (t,v)+ | T.null c' = tag+ | otherwise = tag `commentJoin` c'+ where+ c' = T.stripEnd c+ tag = t <> ": " <> v++-- | Like commentAddTag, but omits the space after the colon.+commentAddTagUnspaced :: Text -> Tag -> Text+commentAddTagUnspaced c (t,v)+ | T.null c' = tag+ | otherwise = c' `commentJoin` tag+ where+ c' = T.stripEnd c+ tag = t <> ":" <> v++-- | Add a tag on its own line to a comment, preserving any prior content.+-- A space is inserted following the colon, before the value.+commentAddTagNextLine :: Text -> Tag -> Text+commentAddTagNextLine cmt (t,v) =+ cmt <> (if "\n" `T.isSuffixOf` cmt then "" else "\n") <> t <> ": " <> v+++-- tests++tests_Posting = testGroup "Posting" [++ testCase "accountNamePostingType" $ do+ accountNamePostingType "a" @?= RealPosting+ accountNamePostingType "(a)" @?= VirtualPosting+ accountNamePostingType "[a]" @?= BalancedVirtualPosting++ ,testCase "accountNameWithoutPostingType" $ do+ accountNameWithoutPostingType "(a)" @?= "a"++ ,testCase "accountNameWithPostingType" $ do+ accountNameWithPostingType VirtualPosting "[a]" @?= "(a)"++ ,testCase "joinAccountNames" $ do+ "a" `joinAccountNames` "b:c" @?= "a:b:c"+ "a" `joinAccountNames` "(b:c)" @?= "(a:b:c)"+ "[a]" `joinAccountNames` "(b:c)" @?= "[a:b:c]"+ "" `joinAccountNames` "a" @?= "a"++ ,testCase "concatAccountNames" $ do+ concatAccountNames [] @?= ""+ concatAccountNames ["a","(b)","[c:d]"] @?= "(a:b:c:d)"++ ,testCase "commentAddTag" $ do+ commentAddTag "" ("a","") @?= "a: "+ commentAddTag "[1/2]" ("a","") @?= "[1/2], a: "++ ,testCase "commentAddTagNextLine" $ do+ commentAddTagNextLine "" ("a","") @?= "\na: "+ commentAddTagNextLine "[1/2]" ("a","") @?= "[1/2]\na: " ]
+ Hledger/Data/RawOptions.hs view
@@ -0,0 +1,166 @@+{-|++hledger's cmdargs modes parse command-line arguments to an+intermediate format, RawOpts (an association list), rather than a+fixed ADT like CliOpts. This allows the modes and flags to be reused+more easily by hledger commands/scripts in this and other packages.++-}++module Hledger.Data.RawOptions (+ RawOpts,+ mkRawOpts,+ overRawOpts,+ dropRawOpt,+ setopt,+ setboolopt,+ unsetboolopt,+ appendopts,+ boolopt,+ toggleopt,+ choiceopt,+ collectopts,+ stringopt,+ maybestringopt,+ listofstringopt,+ intopt,+ posintopt,+ maybeintopt,+ maybeposintopt,+ maybecharopt,+ maybeynopt,+ maybeynaopt,+)+where++import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.Default (Default(..))+import Safe (headMay, lastMay, readDef)++import Hledger.Utils+import Data.Char (toLower)+import Data.List (intercalate)+++-- | The result of running cmdargs: an association list of option names to string values.+newtype RawOpts = RawOpts { unRawOpts :: [(String,String)] }+ deriving (Show)++instance Default RawOpts where def = RawOpts []++mkRawOpts :: [(String,String)] -> RawOpts+mkRawOpts = RawOpts++overRawOpts :: ([(String,String)] -> [(String,String)]) -> RawOpts -> RawOpts+overRawOpts f = RawOpts . f . unRawOpts++dropRawOpt :: String -> RawOpts -> RawOpts+dropRawOpt a = overRawOpts $ filter (not.(==a).fst)++setopt :: String -> String -> RawOpts -> RawOpts+setopt name val = overRawOpts (++ [(name, val)])++setboolopt :: String -> RawOpts -> RawOpts+setboolopt name = overRawOpts (++ [(name,"")])++unsetboolopt :: String -> RawOpts -> RawOpts+unsetboolopt name = overRawOpts (filter ((/=name).fst))++appendopts :: [(String,String)] -> RawOpts -> RawOpts+appendopts new = overRawOpts (++new)++-- | Is the named flag present ?+boolopt :: String -> RawOpts -> Bool+boolopt name = isJust . lookup name . unRawOpts++-- | Like boolopt, except if the flag is repeated on the command line it toggles the value.+-- An even number of repetitions is equivalent to none.+toggleopt :: String -> RawOpts -> Bool+toggleopt name rawopts = odd $ length [ n | (n,_) <- unRawOpts rawopts, n==name]++-- | From a list of RawOpts, get the last one (ie the right-most on the command line)+-- for which the given predicate returns a Just value.+-- Useful for exclusive choice flags like --daily|--weekly|--quarterly...+--+-- >>> import Safe (readMay)+-- >>> choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])+-- Just "c"+-- >>> choiceopt (const Nothing) (RawOpts [("a","")])+-- Nothing+-- >>> choiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe Ordering+-- Just EQ+choiceopt :: (String -> Maybe a) -- ^ "parser" that returns 'Just' value for valid choice+ -> RawOpts -- ^ actual options where to look for flag+ -> Maybe a -- ^ exclusive choice among those returned as 'Just' from "parser"+choiceopt f = lastMay . collectopts (f . fst)++-- | Collects processed and filtered list of options preserving their order+--+-- >>> collectopts (const Nothing) (RawOpts [("x","")])+-- []+-- >>> collectopts Just (RawOpts [("a",""),("b","")])+-- [("a",""),("b","")]+collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]+collectopts f = mapMaybe f . unRawOpts++maybestringopt :: String -> RawOpts -> Maybe String+maybestringopt name = lookup name . reverse . unRawOpts++stringopt :: String -> RawOpts -> String+stringopt name = fromMaybe "" . maybestringopt name++maybecharopt :: String -> RawOpts -> Maybe Char+maybecharopt name (RawOpts rawopts) = lookup name rawopts >>= headMay++listofstringopt :: String -> RawOpts -> [String]+listofstringopt name (RawOpts rawopts) = [v | (k,v) <- rawopts, k==name]++-- | Reads the named option's Int argument, if it is present.+-- An argument that is too small or too large will raise an error.+maybeintopt :: String -> RawOpts -> Maybe Int+maybeintopt = maybeclippedintopt minBound maxBound++-- | Reads the named option's natural-number argument, if it is present.+-- An argument that is negative or too large will raise an error.+maybeposintopt :: String -> RawOpts -> Maybe Int+maybeposintopt = maybeclippedintopt 0 maxBound++-- | Reads the named option's Int argument. If not present it will+-- return 0. An argument that is too small or too large will raise an error.+intopt :: String -> RawOpts -> Int+intopt name = fromMaybe 0 . maybeintopt name++-- | Reads the named option's natural-number argument. If not present it will+-- return 0. An argument that is negative or too large will raise an error.+posintopt :: String -> RawOpts -> Int+posintopt name = fromMaybe 0 . maybeposintopt name++-- | Reads the named option's Int argument, if it is present. An argument+-- that does not fit within the given bounds will raise an error.+maybeclippedintopt :: Int -> Int -> String -> RawOpts -> Maybe Int+maybeclippedintopt minVal maxVal name =+ fmap (intOrError . readOrError) . maybestringopt name+ where+ readOrError s = readDef (usageError $ "could not parse " ++ name ++ " number: " ++ s) s+ intOrError n | n >= toInteger minVal && n <= toInteger maxVal = fromInteger n+ | otherwise = usageError $ "argument to " ++ name+ ++ " must lie in the range "+ ++ show minVal ++ " to " ++ show maxVal+ ++ ", but is " ++ show n++maybeynopt :: String -> RawOpts -> Maybe Bool+maybeynopt name rawopts =+ case maybestringopt name rawopts of+ Just v | map toLower v `elem` ["y","yes","always"] -> Just True+ Just v | map toLower v `elem` ["n","no","never"] -> Just False+ Just _ -> error' $ name <> " value should be one of " <> (intercalate ", " ["y","yes","n","no"])+ _ -> Nothing++maybeynaopt :: String -> RawOpts -> Maybe YNA+maybeynaopt name rawopts =+ case maybestringopt name rawopts of+ Just v | map toLower v `elem` ["y","yes","always"] -> Just Yes+ Just v | map toLower v `elem` ["n","no","never"] -> Just No+ Just v | map toLower v `elem` ["a","auto"] -> Just Auto+ Just _ -> error' $ name <> " value should be one of " <> (intercalate ", " ["y","yes","n","no","a","auto"])+ _ -> Nothing
+ Hledger/Data/StringFormat.hs view
@@ -0,0 +1,192 @@+-- | Parse format strings provided by --format, with awareness of+-- hledger's report item fields. The formats are used by+-- report-specific renderers like renderBalanceReportItem.++{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeFamilies #-}++module Hledger.Data.StringFormat (+ parseStringFormat+ , defaultStringFormatStyle+ , StringFormat(..)+ , StringFormatComponent(..)+ , ReportItemField(..)+ , defaultBalanceLineFormat+ , tests_StringFormat+ ) where++import Numeric (readDec)+import Data.Char (isPrint)+import Data.Default (Default(..))+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Text.Megaparsec+import Text.Megaparsec.Char (char, digitChar, string)++import Hledger.Utils.Parse (SimpleTextParser)+import Hledger.Utils.Text (formatText)+import Hledger.Utils.Test++-- | A format specification/template to use when rendering a report line item as text.+--+-- A format is a sequence of components; each is either a literal+-- string, or a hledger report item field with specified width and+-- justification whose value will be interpolated at render time.+--+-- A component's value may be a multi-line string (or a+-- multi-commodity amount), in which case the final string will be+-- either single-line or a top or bottom-aligned multi-line string+-- depending on the StringFormat variant used.+--+-- Currently this is only used in the balance command's single-column+-- mode, which provides a limited StringFormat renderer.+--+data StringFormat =+ OneLine [StringFormatComponent] -- ^ multi-line values will be rendered on one line, comma-separated+ | TopAligned [StringFormatComponent] -- ^ values will be top-aligned (and bottom-padded to the same height)+ | BottomAligned [StringFormatComponent] -- ^ values will be bottom-aligned (and top-padded)+ deriving (Show, Eq)++data StringFormatComponent =+ FormatLiteral Text -- ^ Literal text to be rendered as-is+ | FormatField Bool+ (Maybe Int)+ (Maybe Int)+ ReportItemField -- ^ A data field to be formatted and interpolated. Parameters:+ --+ -- - Left justify ? Right justified if false+ -- - Minimum width ? Will be space-padded if narrower than this+ -- - Maximum width ? Will be clipped if wider than this+ -- - Which of the standard hledger report item fields to interpolate+ deriving (Show, Eq)++-- | An id identifying which report item field to interpolate. These+-- are drawn from several hledger report types, so are not all+-- applicable for a given report.+data ReportItemField =+ AccountField -- ^ A posting or balance report item's account name+ | DefaultDateField -- ^ A posting or register or entry report item's date+ | DescriptionField -- ^ A posting or register or entry report item's description+ | TotalField -- ^ A balance or posting report item's balance or running total.+ -- Always rendered right-justified.+ | DepthSpacerField -- ^ A balance report item's indent level (which may be different from the account name depth).+ -- Rendered as this number of spaces, multiplied by the minimum width spec if any.+ | FieldNo Int -- ^ A report item's nth field. May be unimplemented.+ deriving (Show, Eq)++instance Default StringFormat where def = defaultBalanceLineFormat++-- | Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)"+defaultBalanceLineFormat :: StringFormat+defaultBalanceLineFormat = BottomAligned [+ FormatField False (Just 20) Nothing TotalField+ , FormatLiteral " "+ , FormatField True (Just 2) Nothing DepthSpacerField+ , FormatField True Nothing Nothing AccountField+ ]+----------------------------------------------------------------------++-- renderStringFormat :: StringFormat -> Map String String -> String+-- renderStringFormat fmt params =++----------------------------------------------------------------------++-- | Parse a string format specification, or return a parse error.+parseStringFormat :: Text -> Either String StringFormat+parseStringFormat input = case (runParser (stringformatp <* eof) "(unknown)") input of+ Left y -> Left $ show y+ Right x -> Right x++defaultStringFormatStyle = BottomAligned++stringformatp :: SimpleTextParser StringFormat+stringformatp = do+ alignspec <- optional (try $ char '%' >> oneOf ("^_,"::String))+ let constructor =+ case alignspec of+ Just '^' -> TopAligned+ Just '_' -> BottomAligned+ Just ',' -> OneLine+ _ -> defaultStringFormatStyle+ constructor <$> many componentp++componentp :: SimpleTextParser StringFormatComponent+componentp = formatliteralp <|> formatfieldp++formatliteralp :: SimpleTextParser StringFormatComponent+formatliteralp = do+ s <- T.pack <$> some c+ return $ FormatLiteral s+ where+ isPrintableButNotPercentage x = isPrint x && x /= '%'+ c = (satisfy isPrintableButNotPercentage <?> "printable character")+ <|> try (string "%%" >> return '%')++formatfieldp :: SimpleTextParser StringFormatComponent+formatfieldp = do+ char '%'+ leftJustified <- optional (char '-')+ minWidth <- optional (some $ digitChar)+ maxWidth <- optional (do char '.'; some $ digitChar) -- TODO: Can this be (char '1') *> (some digitChar)+ char '('+ f <- fieldp+ char ')'+ return $ FormatField (isJust leftJustified) (parseDec minWidth <|> Just 0) (parseDec maxWidth) f+ where+ parseDec s = case s of+ Just text -> Just m where ((m,_):_) = readDec text+ _ -> Nothing++fieldp :: SimpleTextParser ReportItemField+fieldp = do+ try (string "account" >> return AccountField)+ <|> try (string "depth_spacer" >> return DepthSpacerField)+ <|> try (string "date" >> return DescriptionField)+ <|> try (string "description" >> return DescriptionField)+ <|> try (string "total" >> return TotalField)+ <|> try ((FieldNo . read) <$> some digitChar)++----------------------------------------------------------------------++formatStringTester fs value expected = actual @?= expected+ where+ actual = case fs of+ FormatLiteral l -> formatText False Nothing Nothing l+ FormatField leftJustify mn mx _ -> formatText leftJustify mn mx value++tests_StringFormat = testGroup "StringFormat" [++ testCase "formatStringHelper" $ do+ formatStringTester (FormatLiteral " ") "" " "+ formatStringTester (FormatField False Nothing Nothing DescriptionField) "description" "description"+ formatStringTester (FormatField False (Just 20) Nothing DescriptionField) "description" " description"+ formatStringTester (FormatField False Nothing (Just 20) DescriptionField) "description" "description"+ formatStringTester (FormatField True Nothing (Just 20) DescriptionField) "description" "description"+ formatStringTester (FormatField True (Just 20) Nothing DescriptionField) "description" "description "+ formatStringTester (FormatField True (Just 20) (Just 20) DescriptionField) "description" "description "+ formatStringTester (FormatField True Nothing (Just 3) DescriptionField) "description" "des"++ ,let s `gives` expected = testCase s $ parseStringFormat (T.pack s) @?= Right expected+ in testGroup "parseStringFormat" [+ "" `gives` (defaultStringFormatStyle [])+ , "D" `gives` (defaultStringFormatStyle [FormatLiteral "D"])+ , "%(date)" `gives` (defaultStringFormatStyle [FormatField False (Just 0) Nothing DescriptionField])+ , "%(total)" `gives` (defaultStringFormatStyle [FormatField False (Just 0) Nothing TotalField])+ -- TODO+ -- , "^%(total)" `gives` (TopAligned [FormatField False Nothing Nothing TotalField])+ -- , "_%(total)" `gives` (BottomAligned [FormatField False Nothing Nothing TotalField])+ -- , ",%(total)" `gives` (OneLine [FormatField False Nothing Nothing TotalField])+ , "Hello %(date)!" `gives` (defaultStringFormatStyle [FormatLiteral "Hello ", FormatField False (Just 0) Nothing DescriptionField, FormatLiteral "!"])+ , "%-(date)" `gives` (defaultStringFormatStyle [FormatField True (Just 0) Nothing DescriptionField])+ , "%20(date)" `gives` (defaultStringFormatStyle [FormatField False (Just 20) Nothing DescriptionField])+ , "%.10(date)" `gives` (defaultStringFormatStyle [FormatField False (Just 0) (Just 10) DescriptionField])+ , "%20.10(date)" `gives` (defaultStringFormatStyle [FormatField False (Just 20) (Just 10) DescriptionField])+ , "%20(account) %.10(total)" `gives` (defaultStringFormatStyle [FormatField False (Just 20) Nothing AccountField+ ,FormatLiteral " "+ ,FormatField False (Just 0) (Just 10) TotalField+ ])+ , testCase "newline not parsed" $ assertLeft $ parseStringFormat "\n"+ ]+ ]
− Hledger/Data/TimeLog.hs
@@ -1,129 +0,0 @@-{-|--A 'TimeLogEntry' is a clock-in, clock-out, or other directive in a timelog-file (see timeclock.el or the command-line version). These can be-converted to 'Transactions' and queried like a ledger.---}--module Hledger.Data.TimeLog-where-import Data.Maybe-import Data.Time.Calendar-import Data.Time.Clock-import Data.Time.Format-import Data.Time.LocalTime-import System.Locale (defaultTimeLocale)-import Test.HUnit-import Text.Printf--import Hledger.Utils-import Hledger.Data.Types-import Hledger.Data.Dates-import Hledger.Data.Commodity-import Hledger.Data.Transaction--instance Show TimeLogEntry where - show t = printf "%s %s %s" (show $ tlcode t) (show $ tldatetime t) (tlcomment t)--instance Show TimeLogCode where - show SetBalance = "b"- show SetRequiredHours = "h"- show In = "i"- show Out = "o"- show FinalOut = "O"--instance Read TimeLogCode where - readsPrec _ ('b' : xs) = [(SetBalance, xs)]- readsPrec _ ('h' : xs) = [(SetRequiredHours, xs)]- readsPrec _ ('i' : xs) = [(In, xs)]- readsPrec _ ('o' : xs) = [(Out, xs)]- readsPrec _ ('O' : xs) = [(FinalOut, xs)]- readsPrec _ _ = []---- | Convert time log entries to journal transactions. When there is no--- clockout, add one with the provided current time. Sessions crossing--- midnight are split into days to give accurate per-day totals.-timeLogEntriesToTransactions :: LocalTime -> [TimeLogEntry] -> [Transaction]-timeLogEntriesToTransactions _ [] = []-timeLogEntriesToTransactions now [i]- | odate > idate = entryFromTimeLogInOut i o' : timeLogEntriesToTransactions now [i',o]- | otherwise = [entryFromTimeLogInOut i o]- where- o = TimeLogEntry Out end ""- end = if itime > now then itime else now- (itime,otime) = (tldatetime i,tldatetime o)- (idate,odate) = (localDay itime,localDay otime)- o' = o{tldatetime=itime{localDay=idate, localTimeOfDay=TimeOfDay 23 59 59}}- i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}-timeLogEntriesToTransactions now (i:o:rest)- | odate > idate = entryFromTimeLogInOut i o' : timeLogEntriesToTransactions now (i':o:rest)- | otherwise = entryFromTimeLogInOut i o : timeLogEntriesToTransactions now rest- where- (itime,otime) = (tldatetime i,tldatetime o)- (idate,odate) = (localDay itime,localDay otime)- o' = o{tldatetime=itime{localDay=idate, localTimeOfDay=TimeOfDay 23 59 59}}- i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}---- | Convert a timelog clockin and clockout entry to an equivalent journal--- transaction, representing the time expenditure. Note this entry is not balanced,--- since we omit the \"assets:time\" transaction for simpler output.-entryFromTimeLogInOut :: TimeLogEntry -> TimeLogEntry -> Transaction-entryFromTimeLogInOut i o- | otime >= itime = t- | otherwise = - error' $ "clock-out time less than clock-in time in:\n" ++ showTransaction t- where- t = Transaction {- tdate = idate,- teffectivedate = Nothing,- tstatus = True,- tcode = "",- tdescription = showtime itod ++ "-" ++ showtime otod,- tcomment = "",- tmetadata = [],- tpostings = ps,- tpreceding_comment_lines=""- }- showtime = take 5 . show- acctname = tlcomment i- itime = tldatetime i- otime = tldatetime o- itod = localTimeOfDay itime- otod = localTimeOfDay otime- idate = localDay itime- hrs = elapsedSeconds (toutc otime) (toutc itime) / 3600 where toutc = localTimeToUTC utc- amount = Mixed [hours hrs]- ps = [Posting{pstatus=False,paccount=acctname,pamount=amount,- pcomment="",ptype=VirtualPosting,pmetadata=[],ptransaction=Just t}]--tests_Hledger_Data_TimeLog = TestList [-- "timeLogEntriesToTransactions" ~: do- today <- getCurrentDay- now' <- getCurrentTime- tz <- getCurrentTimeZone- let now = utcToLocalTime tz now'- nowstr = showtime now- yesterday = prevday today- clockin = TimeLogEntry In- mktime d = LocalTime d . fromMaybe midnight . parseTime defaultTimeLocale "%H:%M:%S"- showtime = formatTime defaultTimeLocale "%H:%M"- assertEntriesGiveStrings name es ss = assertEqual name ss (map tdescription $ timeLogEntriesToTransactions now es)-- assertEntriesGiveStrings "started yesterday, split session at midnight"- [clockin (mktime yesterday "23:00:00") ""]- ["23:00-23:59","00:00-"++nowstr]- assertEntriesGiveStrings "split multi-day sessions at each midnight"- [clockin (mktime (addDays (-2) today) "23:00:00") ""]- ["23:00-23:59","00:00-23:59","00:00-"++nowstr]- assertEntriesGiveStrings "auto-clock-out if needed" - [clockin (mktime today "00:00:00") ""] - ["00:00-"++nowstr]- let future = utcToLocalTime tz $ addUTCTime 100 now'- futurestr = showtime future- assertEntriesGiveStrings "use the clockin time for auto-clockout if it's in the future"- [clockin future ""]- [printf "%s-%s" futurestr futurestr]-- ]
+ Hledger/Data/Timeclock.hs view
@@ -0,0 +1,310 @@+{-|++A 'TimeclockEntry' is a clock-in, clock-out, or other directive in a timeclock+file (see timeclock.el or the command-line version). These can be+converted to 'Transactions' and queried like a ledger.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StandaloneDeriving #-}++module Hledger.Data.Timeclock (+ timeclockToTransactions+ ,timeclockToTransactionsOld+ ,tests_Timeclock+)+where++import Data.List (intercalate, partition, sortBy, sortOn, uncons)+import Data.Maybe (fromMaybe)+import Data.Text qualified as T+import Data.Time.Calendar (addDays)+import Data.Time.Clock (addUTCTime, getCurrentTime)+import Data.Time.Format (defaultTimeLocale, formatTime, parseTimeM)+import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..), getCurrentTimeZone,+ localTimeToUTC, midnight, utc, utcToLocalTime)+import Text.Printf (printf)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.Dates+import Hledger.Data.Amount+import Hledger.Data.Posting++-- detailed output for debugging+-- deriving instance Show TimeclockEntry++-- compact output+instance Show TimeclockEntry where+ show t = printf "%s %s %s %s" (show $ tlcode t) (show $ tldatetime t) (tlaccount t) (tldescription t)++instance Show TimeclockCode where+ show SetBalance = "b"+ show SetRequiredHours = "h"+ show In = "i"+ show Out = "o"+ show FinalOut = "O"++instance Read TimeclockCode where+ readsPrec _ ('b':xs) = [(SetBalance, xs)]+ readsPrec _ ('h':xs) = [(SetRequiredHours, xs)]+ readsPrec _ ('i':xs) = [(In, xs)]+ readsPrec _ ('o':xs) = [(Out, xs)]+ readsPrec _ ('O':xs) = [(FinalOut, xs)]+ readsPrec _ _ = []++data Session = Session {+ in' :: TimeclockEntry,+ out :: TimeclockEntry+} deriving Show++data Sessions = Sessions {+ completed :: [Session],+ active :: [TimeclockEntry]+} deriving Show++-- | Convert timeclock entries to journal transactions.+-- This is the old version from hledger <1.43, now enabled by --old-timeclock.+-- It requires strictly alternating clock-in and clock-entries.+-- It was documented as allowing only one clocked-in session at a time,+-- but in fact it allows concurrent sessions, even with the same account name.+--+-- Entries must be a strict alternation of in and out, beginning with in.+-- When there is no clockout, one is added with the provided current time. +-- Sessions crossing midnight are split into days to give accurate per-day totals.+-- If entries are not in the expected in/out order, an error is raised.+--+timeclockToTransactionsOld :: LocalTime -> [TimeclockEntry] -> [Transaction]+timeclockToTransactionsOld _ [] = []+timeclockToTransactionsOld now [i]+ | tlcode i /= In = errorExpectedCodeButGot In i+ | odate > idate = entryFromTimeclockInOut True i o' : timeclockToTransactionsOld now [i',o]+ | otherwise = [entryFromTimeclockInOut True i o]+ where+ o = TimeclockEntry (tlsourcepos i) Out end "" "" "" []+ end = if itime > now then itime else now+ (itime,otime) = (tldatetime i,tldatetime o)+ (idate,odate) = (localDay itime,localDay otime)+ -- split the session at midnight+ o' = o{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}+ i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}+timeclockToTransactionsOld now (i:o:rest)+ | tlcode i /= In = errorExpectedCodeButGot In i+ | tlcode o /= Out = errorExpectedCodeButGot Out o+ | odate > idate = entryFromTimeclockInOut True i o' : timeclockToTransactionsOld now (i':o:rest)+ | otherwise = entryFromTimeclockInOut True i o : timeclockToTransactionsOld now rest+ where+ (itime,otime) = (tldatetime i,tldatetime o)+ (idate,odate) = (localDay itime,localDay otime)+ -- split the session at midnight+ o' = o{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}+ i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}+{- HLINT ignore timeclockToTransactionsOld -}++-- | Convert timeclock entries to journal transactions.+-- This is the new, default version added in hledger 1.43 and improved in 1.50.+-- It allows concurrent clocked-in sessions (though not with the same account name),+-- and clock-in/clock-out entries in any order.+--+-- Entries are processed in parse order.+-- Sessions crossing midnight are split into days to give accurate per-day totals.+-- At the end, any sessions with no clockout get an implicit clockout with the provided "now" time.+-- If any entries cannot be paired as expected, an error is raised.+--+timeclockToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]+timeclockToTransactions now entries0 = transactions+ where+ -- don't sort by time, it messes things up; just reverse to get the parsed order+ entries = dbg7 "timeclock entries" $ reverse entries0+ sessions = dbg6 "sessions" $ pairClockEntries entries [] []+ transactionsFromSession s = entryFromTimeclockInOut False (in' s) (out s)+ -- If any "in" sessions are in the future, then set their out time to the initial time+ outtime te = max now (tldatetime te)+ createout te = TimeclockEntry (tlsourcepos te) Out (outtime te) (tlaccount te) "" "" []+ outs = map createout (active sessions)+ stillopen = dbg6 "stillopen" $ pairClockEntries ((active sessions) <> outs) [] []+ transactions = map transactionsFromSession $ sortBy (\s1 s2 -> compare (in' s1) (in' s2)) (completed sessions ++ completed stillopen)++ -- | Assuming that entries have been sorted, we go through each time log entry.+ -- We collect all of the "i" in the list "actives," and each time we encounter+ -- an "o," we look for the corresponding "i" in actives.+ -- If we cannot find it, then it is an error (since the list is sorted).+ -- If the "o" is recorded on a different day than the "i" then we close the+ -- active entry at the end of its day, replace it in the active list+ -- with a start at midnight on the next day, and try again.+ -- This raises an error if any outs cannot be paired with an in.+ pairClockEntries :: [TimeclockEntry] -> [TimeclockEntry] -> [Session] -> Sessions+ pairClockEntries [] actives sessions1 = Sessions {completed = sessions1, active = actives}+ pairClockEntries (entry:es) actives sessions1+ | tlcode entry == In = pairClockEntries es inentries sessions1+ | tlcode entry == Out = pairClockEntries es' actives' sessions2+ | otherwise = pairClockEntries es actives sessions1+ where+ (inentry, newactive) = findInForOut entry (partition (\e -> tlaccount e == tlaccount entry) actives)+ (itime, otime) = (tldatetime inentry, tldatetime entry)+ (idate, odate) = (localDay itime, localDay otime)+ omidnight = entry {tldatetime = itime {localDay = addDays 1 idate, localTimeOfDay = midnight}}+ imidnight = inentry {tldatetime = itime {localDay = addDays 1 idate, localTimeOfDay = midnight}}+ (sessions2, actives', es')+ | odate > idate = (Session {in' = inentry, out = omidnight} : sessions1, imidnight:newactive, entry:es)+ | otherwise = (Session {in' = inentry, out = entry} : sessions1, newactive, es)+ inentries = case filter ((== tlaccount entry) . tlaccount) actives of+ [] -> entry:actives+ activesinthisacct -> error' $ timeclockEntryError activesinthisacct entry $+ "This clockin overlaps the session in the same account which began on line "+ ++ intercalate ", " (map (show . timeclockEntryLine) activesinthisacct) ++ ".\n"+ ++ "Overlapping sessions with the same account name are not supported."++ -- | Find the relevant clockin in the actives list that should be paired with this clockout.+ -- If there is a session that has the same account name, then use that.+ -- Otherwise, if there is an active anonymous session, use that.+ -- Otherwise, raise an error.+ findInForOut :: TimeclockEntry -> ([TimeclockEntry], [TimeclockEntry]) -> (TimeclockEntry, [TimeclockEntry])+ findInForOut _ (matchingout:othermatches, rest) = (matchingout, othermatches <> rest)+ findInForOut o ([], activeins) =+ if emptyname then (first, rest) else error' errmsg+ where+ l = show $ unPos $ sourceLine $ tlsourcepos o+ c = unPos $ sourceColumn $ tlsourcepos o+ emptyname = tlaccount o == ""+ (first, rest) = case uncons activeins of+ Just (hd, tl) -> (hd, tl)+ Nothing -> error' errmsg+ errmsg =+ printf+ "%s:\n%s\n%s\n\nCould not find previous clockin to match this clockout."+ (sourcePosPretty $ tlsourcepos o)+ (l ++ " | " ++ show o)+ (replicate (length l) ' ' ++ " |" ++ replicate c ' ' ++ "^")++errorExpectedCodeButGot :: TimeclockCode -> TimeclockEntry -> a+errorExpectedCodeButGot expected actual = error' $ printf+ ("%s:\n%s\n%s\n\nExpected a timeclock %s entry but got %s.\n"+ ++"Please alternate i and o, beginning with i.")+ (sourcePosPretty $ tlsourcepos actual)+ (l ++ " | " ++ show actual)+ (replicate (length l) ' ' ++ " |" ++ replicate c ' ' ++ "^")+ (show expected)+ (show $ tlcode actual)+ where+ l = show $ unPos $ sourceLine $ tlsourcepos actual+ c = unPos $ sourceColumn $ tlsourcepos actual++-- | Make an error message about a timeclock entry, in hledger's standard error format:+-- its position; an excerpt showing it, marked with ^, after any related earlier entries;+-- and the given explanation.+timeclockEntryError :: [TimeclockEntry] -> TimeclockEntry -> String -> String+timeclockEntryError related e msg = intercalate "\n" $+ [sourcePosPretty (tlsourcepos e) ++ ":"]+ ++ concat (zipWith excerptLines (Nothing : map Just es) es)+ ++ [replicate (length $ show $ timeclockEntryLine e) ' ' ++ " |" ++ replicate col ' ' ++ "^", "", msg]+ where+ es = sortOn timeclockEntryLine related ++ [e]+ col = unPos $ sourceColumn $ tlsourcepos e+ -- each entry's line, preceded by an empty line if it's not adjacent to the previous one+ excerptLines prev x =+ [ "" | Just p <- [prev], timeclockEntryLine x > timeclockEntryLine p + 1 ]+ ++ [show (timeclockEntryLine x) ++ " | " ++ T.unpack (T.stripEnd $ T.pack $ show x)]++-- | A timeclock entry's line number.+timeclockEntryLine :: TimeclockEntry -> Int+timeclockEntryLine = unPos . sourceLine . tlsourcepos++-- | Convert a timeclock clockin and clockout entry to an equivalent journal+-- transaction, representing the time expenditure. Note this entry is not balanced,+-- since we omit the \"assets:time\" transaction for simpler output.+entryFromTimeclockInOut :: Bool -> TimeclockEntry -> TimeclockEntry -> Transaction+entryFromTimeclockInOut requiretimeordered i o+ | not requiretimeordered || otime >= itime = t+ | otherwise =+ -- Clockout time earlier than clockin is an error.+ -- (Clockin earlier than preceding clockin/clockout is allowed.)+ -- We should never encounter this case now that we sort the entries,+ -- but let's leave it in case of error.+ error' $ printf+ ("%s:\n%s\nThis clockout time (%s) is earlier than the previous clockin.\n"+ ++"Please adjust it to be later than %s.")+ (sourcePosPretty $ tlsourcepos o)+ (unlines [+ replicate (length l) ' '++ " | " ++ show i,+ l ++ " | " ++ show o,+ (replicate (length l) ' ' ++ " |" ++ replicate c ' ' ++ replicate 19 '^')+ ])+ (show $ tldatetime o)+ (show $ tldatetime i)+ where+ l = show $ unPos $ sourceLine $ tlsourcepos o+ c = (unPos $ sourceColumn $ tlsourcepos o) + 2+ t = Transaction {+ tindex = 0,+ tsourcepos = (tlsourcepos i, tlsourcepos i),+ tdate = idate,+ tdate2 = Nothing,+ tstatus = Cleared,+ tcode = "",+ tdescription = desc,+ tcomment = tlcomment i <> tlcomment o,+ ttags = tltags i ++ tltags o,+ tpostings = ps,+ tprecedingcomment=""+ }+ itime = tldatetime i+ otime = tldatetime o+ itod = localTimeOfDay itime+ otod | localDay otime > idate = TimeOfDay 23 59 0 -- a session split at midnight ends at the next midnight; describe that as 23:59+ | otherwise = localTimeOfDay otime+ idate = localDay itime+ desc | T.null (tldescription i) = T.pack $ showtime itod ++ "-" ++ showtime otod+ | otherwise = tldescription i+ showtime = take 5 . show+ hours = elapsedSeconds (toutc otime) (toutc itime) / 3600 where toutc = localTimeToUTC utc+ acctname = tlaccount i+ -- Generate an hours amount, displayed with 2 decimal places by default.+ -- Its quantity is not rounded to that (#1527), so totals are accurate;+ -- it is exact, or as exact as possible (dividing seconds by 3600 is rounded at the 255th decimal place).+ amt = case mixedAmount $ hrs hours of+ a | not $ a < 0 -> a+ _ -> error' $ timeclockEntryError [i] o $+ printf "This clockout is earlier than its clockin, on line %d." (timeclockEntryLine i)+ ps = [posting{paccount=acctname, pamount=amt, preal=VirtualPosting, ptransaction=Just t}]+++-- tests++tests_Timeclock = testGroup "Timeclock" [+ testCaseSteps "timeclockToTransactions tests" $ \step -> do+ step "gathering data"+ today <- getCurrentDay+ now' <- getCurrentTime+ tz <- getCurrentTimeZone+ let now = utcToLocalTime tz now'+ nowstr = showtime now+ yesterday = prevday today+ clockin = TimeclockEntry (initialPos "") In+ clockout = TimeclockEntry (initialPos "") Out+ mktime d = LocalTime d . fromMaybe midnight .+ parseTimeM True defaultTimeLocale "%H:%M:%S"+ showtime = formatTime defaultTimeLocale "%H:%M"+ txndescs = map (T.unpack . tdescription) . timeclockToTransactions now+ future = utcToLocalTime tz $ addUTCTime 100 now'+ futurestr = showtime future+ step "started yesterday, split session at midnight"+ txndescs [clockin (mktime yesterday "23:00:00") "" "" "" []] @?= ["23:00-23:59","00:00-"++nowstr]+ step "split multi-day sessions at each midnight"+ txndescs [clockin (mktime (addDays (-2) today) "23:00:00") "" "" "" []] @?= ["23:00-23:59","00:00-23:59","00:00-"++nowstr]+ step "auto-clock-out if needed"+ txndescs [clockin (mktime today "00:00:00") "" "" "" []] @?= ["00:00-"++nowstr]+ step "use the clockin time for auto-clockout if it's in the future"+ txndescs [clockin future "" "" "" []] @?= [printf "%s-%s" futurestr futurestr]+ step "multiple open sessions"+ txndescs (reverse [+ clockin (mktime today "00:00:00") "a" "" "" [],+ clockin (mktime today "01:00:00") "b" "" "" [],+ clockin (mktime today "02:00:00") "c" "" "" [],+ clockout (mktime today "03:00:00") "b" "" "" [],+ clockout (mktime today "04:00:00") "a" "" "" [],+ clockout (mktime today "05:00:00") "c" "" "" []+ ])+ @?= ["00:00-04:00", "01:00-03:00", "02:00-05:00"]+ ]
Hledger/Data/Transaction.hs view
@@ -1,417 +1,781 @@ {-| -A 'Transaction' consists of two or more related 'Posting's which balance-to zero, representing a movement of some commodity(ies) between accounts,-plus a date and optional metadata like description and cleared status.---}--module Hledger.Data.Transaction-where-import Data.List-import Data.Maybe-import Data.Time.Calendar-import Test.HUnit-import Text.Printf-import qualified Data.Map as Map--import Hledger.Utils-import Hledger.Data.Types-import Hledger.Data.Dates-import Hledger.Data.Posting-import Hledger.Data.Amount-import Hledger.Data.Commodity--instance Show Transaction where show = showTransactionUnelided--instance Show ModifierTransaction where - show t = "= " ++ mtvalueexpr t ++ "\n" ++ unlines (map show (mtpostings t))--instance Show PeriodicTransaction where - show t = "~ " ++ ptperiodicexpr t ++ "\n" ++ unlines (map show (ptpostings t))--nulltransaction :: Transaction-nulltransaction = Transaction {- tdate=nulldate,- teffectivedate=Nothing, - tstatus=False, - tcode="", - tdescription="", - tcomment="",- tmetadata=[],- tpostings=[],- tpreceding_comment_lines=""- }--{-|-Show a journal transaction, formatted for the print command. ledger 2.x's-standard format looks like this:--@-yyyy/mm/dd[ *][ CODE] description......... [ ; comment...............]- account name 1..................... ...$amount1[ ; comment...............]- account name 2..................... ..$-amount1[ ; comment...............]--pcodewidth = no limit -- 10 -- mimicking ledger layout.-pdescwidth = no limit -- 20 -- I don't remember what these mean,-pacctwidth = 35 minimum, no maximum -- they were important at the time.-pamtwidth = 11-pcommentwidth = no limit -- 22-@--}-showTransaction :: Transaction -> String-showTransaction = showTransaction' True--showTransactionUnelided :: Transaction -> String-showTransactionUnelided = showTransaction' False--showTransaction' :: Bool -> Transaction -> String-showTransaction' elide t =- unlines $ [description] ++ showpostings (tpostings t) ++ [""]- where- description = concat [date, status, code, desc, comment]- date = showdate (tdate t) ++ maybe "" showedate (teffectivedate t)- showdate = printf "%-10s" . showDate- showedate = printf "=%s" . showdate- status = if tstatus t then " *" else ""- code = if length (tcode t) > 0 then printf " (%s)" $ tcode t else ""- desc = if null d then "" else " " ++ d where d = tdescription t- comment = if null c then "" else " ; " ++ c where c = tcomment t- showpostings ps- | elide && length ps > 1 && isTransactionBalanced Nothing t -- imprecise balanced check- = map showposting (init ps) ++ [showpostingnoamt (last ps)]- | otherwise = map showposting ps- where- showpostingnoamt p = rstrip $ showacct p ++ " " ++ showcomment (pcomment p)- showposting p = concatTopPadded [showacct p- ," "- ,showamt (pamount p)- ,showcomment (pcomment p)- ]- showacct p = " " ++ showstatus p ++ printf (printf "%%-%ds" w) (showAccountName Nothing (ptype p) (paccount p))- where w = maximum $ map (length . paccount) ps- showstatus p = if pstatus p then "* " else ""- showamt =- padleft 12 . showMixedAmount- showcomment s = if null s then "" else " ; "++s---- | Show an account name, clipped to the given width if any, and--- appropriately bracketed/parenthesised for the given posting type.-showAccountName :: Maybe Int -> PostingType -> AccountName -> String-showAccountName w = fmt- where- fmt RegularPosting = take w'- fmt VirtualPosting = parenthesise . reverse . take (w'-2) . reverse- fmt BalancedVirtualPosting = bracket . reverse . take (w'-2) . reverse- w' = fromMaybe 999999 w- parenthesise s = "("++s++")"- bracket s = "["++s++"]"--hasRealPostings :: Transaction -> Bool-hasRealPostings = not . null . realPostings--realPostings :: Transaction -> [Posting]-realPostings = filter isReal . tpostings--virtualPostings :: Transaction -> [Posting]-virtualPostings = filter isVirtual . tpostings--balancedVirtualPostings :: Transaction -> [Posting]-balancedVirtualPostings = filter isBalancedVirtual . tpostings--transactionsPostings :: [Transaction] -> [Posting]-transactionsPostings = concat . map tpostings---- | Get the sums of a transaction's real, virtual, and balanced virtual postings.-transactionPostingBalances :: Transaction -> (MixedAmount,MixedAmount,MixedAmount)-transactionPostingBalances t = (sumPostings $ realPostings t- ,sumPostings $ virtualPostings t- ,sumPostings $ balancedVirtualPostings t)---- | Is this transaction balanced ? A balanced transaction's real--- (non-virtual) postings sum to 0, and any balanced virtual postings--- also sum to 0.-isTransactionBalanced :: Maybe (Map.Map String Commodity) -> Transaction -> Bool-isTransactionBalanced canonicalcommoditymap t =- -- isReallyZeroMixedAmountCost rsum && isReallyZeroMixedAmountCost bvsum- isZeroMixedAmount rsum' && isZeroMixedAmount bvsum'- where- (rsum, _, bvsum) = transactionPostingBalances t- rsum' = canonicaliseMixedAmountCommodity canonicalcommoditymap $ costOfMixedAmount rsum- bvsum' = canonicaliseMixedAmountCommodity canonicalcommoditymap $ costOfMixedAmount bvsum---- | Ensure this transaction is balanced, possibly inferring a missing--- amount or a conversion price first, or return an error message.------ Balancing is affected by the provided commodities' display precisions.------ We can infer an amount when there are multiple real postings and--- exactly one of them is amountless; likewise for balanced virtual--- postings. Inferred amounts are converted to cost basis when possible.------ We can infer a price when all amounts were specified and the sum of--- real postings' amounts is exactly two non-explicitly-priced amounts in--- different commodities; likewise for balanced virtual postings.-balanceTransaction :: Maybe (Map.Map String Commodity) -> Transaction -> Either String Transaction-balanceTransaction canonicalcommoditymap t@Transaction{tpostings=ps}- | length rwithoutamounts > 1 || length bvwithoutamounts > 1- = Left $ printerr "could not balance this transaction (too many missing amounts)"- | not $ isTransactionBalanced canonicalcommoditymap t''' = Left $ printerr $ nonzerobalanceerror t'''- | otherwise = Right t'''- where- -- maybe infer missing amounts- (rwithamounts, rwithoutamounts) = partition hasAmount $ realPostings t- (bvwithamounts, bvwithoutamounts) = partition hasAmount $ balancedVirtualPostings t- ramounts = map pamount rwithamounts- bvamounts = map pamount bvwithamounts- t' = t{tpostings=map inferamount ps}- where - inferamount p | not (hasAmount p) && isReal p = p{pamount = (- sum ramounts)}- | not (hasAmount p) && isBalancedVirtual p = p{pamount = (- sum bvamounts)}- | otherwise = p-- -- maybe infer conversion prices, for real postings- rmixedamountsinorder = map pamount $ realPostings t'- ramountsinorder = concatMap amounts rmixedamountsinorder- rcommoditiesinorder = map commodity ramountsinorder- rsumamounts = amounts $ sum rmixedamountsinorder- -- assumption: the sum of mixed amounts is normalised (one simple amount per commodity)- t'' = if length rsumamounts == 2 && all (isNothing.price) rsumamounts && t'==t- then t'{tpostings=map inferprice ps}- else t'- where- -- assumption: a posting's mixed amount contains one simple amount- inferprice p@Posting{pamount=Mixed [a@Amount{commodity=c,price=Nothing}], ptype=RegularPosting}- = p{pamount=Mixed [a{price=conversionprice c}]}- where- conversionprice c | c == unpricedcommodity- -- assign a balancing price. Use @@ for more exact output when possible.- -- invariant: prices should always be positive. Enforced with "abs"- = if length ramountsinunpricedcommodity == 1- then Just $ TotalPrice $ Mixed [setAmountPrecision maxprecision $ abs $ targetcommodityamount]- else Just $ UnitPrice $ Mixed [setAmountPrecision maxprecision $ abs $ targetcommodityamount `divideAmount` (quantity unpricedamount)]- | otherwise = Nothing- where- unpricedcommodity = head $ filter (`elem` (map commodity rsumamounts)) rcommoditiesinorder- unpricedamount = head $ filter ((==unpricedcommodity).commodity) rsumamounts- targetcommodityamount = head $ filter ((/=unpricedcommodity).commodity) rsumamounts- ramountsinunpricedcommodity = filter ((==unpricedcommodity).commodity) ramountsinorder- inferprice p = p-- -- maybe infer prices for balanced virtual postings. Just duplicates the above for now.- bvmixedamountsinorder = map pamount $ balancedVirtualPostings t''- bvamountsinorder = concatMap amounts bvmixedamountsinorder- bvcommoditiesinorder = map commodity bvamountsinorder- bvsumamounts = amounts $ sum bvmixedamountsinorder- t''' = if length bvsumamounts == 2 && all (isNothing.price) bvsumamounts && t'==t -- XXX could check specifically for bv amount inferring- then t''{tpostings=map inferprice ps}- else t''- where- inferprice p@Posting{pamount=Mixed [a@Amount{commodity=c,price=Nothing}], ptype=BalancedVirtualPosting}- = p{pamount=Mixed [a{price=conversionprice c}]}- where- conversionprice c | c == unpricedcommodity- = if length bvamountsinunpricedcommodity == 1- then Just $ TotalPrice $ Mixed [setAmountPrecision maxprecision $ abs $ targetcommodityamount]- else Just $ UnitPrice $ Mixed [setAmountPrecision maxprecision $ abs $ targetcommodityamount `divideAmount` (quantity unpricedamount)]- | otherwise = Nothing- where- unpricedcommodity = head $ filter (`elem` (map commodity bvsumamounts)) bvcommoditiesinorder- unpricedamount = head $ filter ((==unpricedcommodity).commodity) bvsumamounts- targetcommodityamount = head $ filter ((/=unpricedcommodity).commodity) bvsumamounts- bvamountsinunpricedcommodity = filter ((==unpricedcommodity).commodity) bvamountsinorder- inferprice p = p-- printerr s = intercalate "\n" [s, showTransactionUnelided t]--nonzerobalanceerror :: Transaction -> String-nonzerobalanceerror t = printf "could not balance this transaction (%s%s%s)" rmsg sep bvmsg- where- (rsum, _, bvsum) = transactionPostingBalances t- rmsg | isReallyZeroMixedAmountCost rsum = ""- | otherwise = "real postings are off by " ++ show (costOfMixedAmount rsum)- bvmsg | isReallyZeroMixedAmountCost bvsum = ""- | otherwise = "balanced virtual postings are off by " ++ show (costOfMixedAmount bvsum)- sep = if not (null rmsg) && not (null bvmsg) then "; " else ""--transactionActualDate :: Transaction -> Day-transactionActualDate = tdate---- Get a transaction's effective date, defaulting to the actual date.-transactionEffectiveDate :: Transaction -> Day-transactionEffectiveDate t = fromMaybe (tdate t) $ teffectivedate t---- | Once we no longer need both, set the main transaction date to either--- the actual or effective date. A bit hacky.-journalTransactionWithDate :: WhichDate -> Transaction -> Transaction-journalTransactionWithDate ActualDate t = t-journalTransactionWithDate EffectiveDate t = txnTieKnot t{tdate=transactionEffectiveDate t}---- | Ensure a transaction's postings refer back to it.-txnTieKnot :: Transaction -> Transaction-txnTieKnot t@Transaction{tpostings=ps} = t{tpostings=map (settxn t) ps}---- | Set a posting's parent transaction.-settxn :: Transaction -> Posting -> Posting-settxn t p = p{ptransaction=Just t}--tests_Hledger_Data_Transaction = TestList [- "showTransaction" ~: do- assertEqual "show a balanced transaction, eliding last amount"- (unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries $47.18"- ," assets:checking"- ,""- ])- (let t = Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" (Mixed [dollars 47.18]) "" RegularPosting [] (Just t)- ,Posting False "assets:checking" (Mixed [dollars (-47.18)]) "" RegularPosting [] (Just t)- ] ""- in showTransaction t)-- ,"showTransaction" ~: do- assertEqual "show a balanced transaction, no eliding"- (unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries $47.18"- ," assets:checking $-47.18"- ,""- ])- (let t = Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" (Mixed [dollars 47.18]) "" RegularPosting [] (Just t)- ,Posting False "assets:checking" (Mixed [dollars (-47.18)]) "" RegularPosting [] (Just t)- ] ""- in showTransactionUnelided t)-- -- document some cases that arise in debug/testing:- ,"showTransaction" ~: do- assertEqual "show an unbalanced transaction, should not elide"- (unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries $47.18"- ," assets:checking $-47.19"- ,""- ])- (showTransaction- (txnTieKnot $ Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" (Mixed [dollars 47.18]) "" RegularPosting [] Nothing- ,Posting False "assets:checking" (Mixed [dollars (-47.19)]) "" RegularPosting [] Nothing- ] ""))-- ,"showTransaction" ~: do- assertEqual "show an unbalanced transaction with one posting, should not elide"- (unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries $47.18"- ,""- ])- (showTransaction- (txnTieKnot $ Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" (Mixed [dollars 47.18]) "" RegularPosting [] Nothing- ] ""))-- ,"showTransaction" ~: do- assertEqual "show a transaction with one posting and a missing amount"- (unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries "- ,""- ])- (showTransaction- (txnTieKnot $ Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" missingamt "" RegularPosting [] Nothing- ] ""))-- ,"showTransaction" ~: do- assertEqual "show a transaction with a priced commodityless amount"- (unlines- ["2010/01/01 x"- ," a 1 @ $2"- ," b "- ,""- ])- (showTransaction- (txnTieKnot $ Transaction (parsedate "2010/01/01") Nothing False "" "x" "" []- [Posting False "a" (Mixed [Amount unknown 1 (Just $ UnitPrice $ Mixed [Amount dollar{precision=0} 2 Nothing])]) "" RegularPosting [] Nothing- ,Posting False "b" missingamt "" RegularPosting [] Nothing- ] ""))-- ,"balanceTransaction" ~: do- assertBool "detect unbalanced entry, sign error"- (isLeft $ balanceTransaction Nothing- (Transaction (parsedate "2007/01/28") Nothing False "" "test" "" []- [Posting False "a" (Mixed [dollars 1]) "" RegularPosting [] Nothing,- Posting False "b" (Mixed [dollars 1]) "" RegularPosting [] Nothing- ] ""))- assertBool "detect unbalanced entry, multiple missing amounts"- (isLeft $ balanceTransaction Nothing- (Transaction (parsedate "2007/01/28") Nothing False "" "test" "" []- [Posting False "a" missingamt "" RegularPosting [] Nothing,- Posting False "b" missingamt "" RegularPosting [] Nothing- ] ""))- let e = balanceTransaction Nothing (Transaction (parsedate "2007/01/28") Nothing False "" "" "" []- [Posting False "a" (Mixed [dollars 1]) "" RegularPosting [] Nothing,- Posting False "b" missingamt "" RegularPosting [] Nothing- ] "")- assertBool "balanceTransaction allows one missing amount" (isRight e)- assertEqual "balancing amount is inferred"- (Mixed [dollars (-1)])- (case e of- Right e' -> (pamount $ last $ tpostings e')- Left _ -> error' "should not happen")- let e = balanceTransaction Nothing (Transaction (parsedate "2011/01/01") Nothing False "" "" "" []- [Posting False "a" (Mixed [dollars 1.35]) "" RegularPosting [] Nothing,- Posting False "b" (Mixed [euros (-1)]) "" RegularPosting [] Nothing- ] "")- assertBool "balanceTransaction can infer conversion price" (isRight e)- assertEqual "balancing conversion price is inferred"- (Mixed [Amount{commodity=dollar{precision=2},- quantity=1.35,- price=(Just $ TotalPrice $ Mixed [Amount{commodity=euro{precision=maxprecision},- quantity=1,- price=Nothing}])}])- (case e of- Right e' -> (pamount $ head $ tpostings e')- Left _ -> error' "should not happen")-- ,"isTransactionBalanced" ~: do- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ,Posting False "c" (Mixed [dollars (-1.00)]) "" RegularPosting [] (Just t)- ] ""- assertBool "detect balanced" (isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ,Posting False "c" (Mixed [dollars (-1.01)]) "" RegularPosting [] (Just t)- ] ""- assertBool "detect unbalanced" (not $ isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ] ""- assertBool "detect unbalanced, one posting" (not $ isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 0]) "" RegularPosting [] (Just t)- ] ""- assertBool "one zero posting is considered balanced for now" (isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ,Posting False "c" (Mixed [dollars (-1.00)]) "" RegularPosting [] (Just t)- ,Posting False "d" (Mixed [dollars 100]) "" VirtualPosting [] (Just t)- ] ""- assertBool "virtual postings don't need to balance" (isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ,Posting False "c" (Mixed [dollars (-1.00)]) "" RegularPosting [] (Just t)- ,Posting False "d" (Mixed [dollars 100]) "" BalancedVirtualPosting [] (Just t)- ] ""- assertBool "balanced virtual postings need to balance among themselves" (not $ isTransactionBalanced Nothing t)- let t = Transaction (parsedate "2009/01/01") Nothing False "" "a" "" []- [Posting False "b" (Mixed [dollars 1.00]) "" RegularPosting [] (Just t)- ,Posting False "c" (Mixed [dollars (-1.00)]) "" RegularPosting [] (Just t)- ,Posting False "d" (Mixed [dollars 100]) "" BalancedVirtualPosting [] (Just t)- ,Posting False "e" (Mixed [dollars (-100)]) "" BalancedVirtualPosting [] (Just t)- ] ""- assertBool "balanced virtual postings need to balance among themselves (2)" (isTransactionBalanced Nothing t)-- ]+A 'Transaction' represents a movement of some commodity(ies) between two+or more accounts. It consists of multiple account 'Posting's which balance+to zero, a date, and optional extras like description, cleared status, and+tags.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Data.Transaction+( -- * Transaction+ nulltransaction+, transaction+, txnTieKnot+, txnUntieKnot+ -- * operations+, hasRealPostings+, realPostings+, assignmentPostings+, virtualPostings+, balancedVirtualPostings+, transactionsPostings+, transactionTransformPostings+, transactionApplyValuation+, transactionToCost+, transactionInferEquityPostings+, transactionTagCostsAndEquityAndMaybeInferCosts+, transactionApplyAliases+, transactionMapPostings+, transactionMapPostingAmounts+, transactionAmounts+, transactionCommodityStyles+, transactionCommodityStylesWith+, transactionNegate+, partitionAndCheckConversionPostings+, transactionAddTags+, transactionAddHiddenAndMaybeVisibleTag+ -- * helpers+, TransactionBalancingPrecision(..)+, payeeAndNoteFromDescription+, payeeAndNoteFromDescription'+ -- nonzerobalanceerror+ -- * date operations+, transactionDate2+, transactionDateOrDate2+ -- * transaction description parts+, transactionPayee+, transactionNote+ -- payeeAndNoteFromDescription+ -- * rendering+, showTransaction+, showTransactionWithLayout+, showTransactionOneLineAmounts+, showTransactionOneLine+, showTransactionLineFirstPart+, transactionFile+ -- * transaction errors+, annotateErrorWithTransaction+ -- * tests+, tests_Transaction+) where++import Control.Monad.Trans.State (StateT(..), evalStateT)+import Data.Bifunctor (first, second)+import Data.Foldable (foldlM)+import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe)+import Data.Semigroup (Endo(..))+import Data.Text (Text)+import Data.Map qualified as M+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, fromGregorian)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.Dates+import Hledger.Data.Posting+import Hledger.Data.Amount+import Hledger.Data.Valuation+import Data.Decimal (normalizeDecimal, decimalPlaces, roundTo)+import Data.Functor ((<&>))+import Data.Function ((&))+import Data.List (union)+++-- | How to determine the precision used for checking that transactions are balanced,+-- and so how much imbalance is tolerated (selected by --txn-tolerance). See #2402.+data TransactionBalancingPrecision =+ TBPDisplay+ -- ^ Legacy behaviour, as in hledger <1.50, included to ease upgrades.+ -- use precision inferred from the whole journal, overridable by commodity directive or -c.+ -- Display precision is also transaction balancing precision; increasing it can break journal reading.+ -- Some valid journals are rejected until commodity directives are added.+ -- Larger imbalances can be hidden, and in accounts that are never reconciled, can accumulate over time.+ | TBPEntry+ -- ^ Simpler, more robust behaviour, like Ledger: use precision inferred from the transaction's journal entry.+ -- Display precision and transaction balancing precision are independent; display precision never affects journal reading.+ -- Valid journals from ledger or beancount are accepted without needing commodity directives.+ -- Imbalances smaller than the entry's precision are still tolerated, and can accumulate.++ deriving (Bounded, Enum, Eq, Ord, Read, Show)++instance HasAmounts Transaction where+ styleAmounts styles t = t{tpostings=styleAmounts styles $ tpostings t}++nulltransaction :: Transaction+nulltransaction = Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=nulldate,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="",+ tdescription="",+ tcomment="",+ ttags=[],+ tpostings=[],+ tprecedingcomment=""+ }++-- | Make a simple transaction with the given date and postings.+transaction :: Day -> [Posting] -> Transaction+transaction day ps = txnTieKnot $ nulltransaction{tdate=day, tpostings=ps}++transactionPayee :: Transaction -> Text+transactionPayee = fst . payeeAndNoteFromDescription . tdescription++transactionNote :: Transaction -> Text+transactionNote = snd . payeeAndNoteFromDescription . tdescription++-- | Parse a transaction's description into payee and note (aka narration) fields,+-- assuming a convention of separating these with | (like Beancount).+-- Ie, everything up to the first | is the payee, everything after it is the note.+-- When there's no |, payee == note == description.+payeeAndNoteFromDescription :: Text -> (Text,Text)+payeeAndNoteFromDescription t+ | T.null n = (t, t)+ | otherwise = (T.strip p, T.strip $ T.drop 1 n)+ where+ (p, n) = T.span (/= '|') t++-- | Like payeeAndNoteFromDescription, but if there's no | then payee is empty.+payeeAndNoteFromDescription' :: Text -> (Text,Text)+payeeAndNoteFromDescription' t =+ if isJust $ T.find (=='|') t then payeeAndNoteFromDescription t else ("",t)+++{-|+Render a journal transaction as text similar to the style of Ledger's print command.++Adapted from Ledger 2.x and 3.x standard format:++@+yyyy-mm-dd[ *][ CODE] description......... [ ; comment...............]+ account name 1..................... ...$amount1[ ; comment...............]+ account name 2..................... ..$-amount1[ ; comment...............]++pcodewidth = no limit -- 10 -- mimicking ledger layout.+pdescwidth = no limit -- 20 -- I don't remember what these mean,+pacctwidth = 35 minimum, no maximum -- they were important at the time.+pamtwidth = 11+pcommentwidth = no limit -- 22+@++The output will be parseable journal syntax.+To facilitate this, postings with explicit multi-commodity amounts+are displayed as multiple similar postings, one per commodity.+(Normally does not happen with this function).+-}+showTransaction :: Transaction -> Text+showTransaction = TL.toStrict . TB.toLazyText . showTransactionHelper False defaultPostingLayout++-- | Like 'showTransaction', but with an explicit posting layout+-- (e.g. to support @print --layout=hledger1@).+showTransactionWithLayout :: PostingLayout -> Transaction -> Text+showTransactionWithLayout layout = TL.toStrict . TB.toLazyText . showTransactionHelper False layout++-- | Like showTransaction, but explicit multi-commodity amounts+-- are shown on one line, comma-separated. In this case the output will+-- not be parseable journal syntax.+showTransactionOneLineAmounts :: Transaction -> Text+showTransactionOneLineAmounts = TL.toStrict . TB.toLazyText . showTransactionHelper True defaultPostingLayout++-- | Show only a transaction's first line: date, status, code, description,+-- and same-line comment, without any comment lines or postings. Used by the transactions command.+-- (Distinct from 'showTransactionOneLineAmounts', which shows the whole transaction+-- but with multi-commodity amounts on one line.)+showTransactionOneLine :: Transaction -> Text+showTransactionOneLine t = transactionFirstLine t <> "\n"++-- | Helper for showTransaction*.+-- Any preceding comment lines (tprecedingcomment, already newline-terminated) are shown first.+showTransactionHelper :: Bool -> PostingLayout -> Transaction -> TB.Builder+showTransactionHelper onelineamounts layout t =+ TB.fromText (tprecedingcomment t)+ <> TB.fromText (transactionFirstLine t) <> newline+ <> foldMap ((<> newline) . TB.fromText) newlinecomments+ <> foldMap ((<> newline) . TB.fromText) (postingsAsLinesWithLayout defaultFmt onelineamounts layout $ tpostings t)+ <> newline+ where+ newlinecomments = drop 1 $ renderCommentLines (tcomment t)+ newline = TB.singleton '\n'++-- | Render a transaction's first line: date, status, code, description, and+-- same-line comment (the part after @;@ on the date line), with trailing whitespace stripped.+transactionFirstLine :: Transaction -> Text+transactionFirstLine t = T.stripEnd $ showTransactionLineFirstPart t <> T.concat [desc, samelinecomment]+ where+ desc = if T.null d then "" else " " <> d where d = tdescription t+ samelinecomment = case renderCommentLines (tcomment t) of [] -> ""+ c:_ -> c++-- Useful when rendering error messages.+showTransactionLineFirstPart t = T.concat [date, status, code]+ where+ date = showDate (tdate t) <> maybe "" (("="<>) . showDate) (tdate2 t)+ status | tstatus t == Cleared = " *"+ | tstatus t == Pending = " !"+ | otherwise = ""+ code = if T.null (tcode t) then "" else wrap " (" ")" $ tcode t++hasRealPostings :: Transaction -> Bool+hasRealPostings = not . null . realPostings++realPostings :: Transaction -> [Posting]+realPostings = filter isReal . tpostings++assignmentPostings :: Transaction -> [Posting]+assignmentPostings = filter hasBalanceAssignment . tpostings++virtualPostings :: Transaction -> [Posting]+virtualPostings = filter isVirtual . tpostings++balancedVirtualPostings :: Transaction -> [Posting]+balancedVirtualPostings = filter isBalancedVirtual . tpostings++transactionsPostings :: [Transaction] -> [Posting]+transactionsPostings = concatMap tpostings++-- Get a transaction's secondary date, or the primary date if there is none.+transactionDate2 :: Transaction -> Day+transactionDate2 t = fromMaybe (tdate t) $ tdate2 t++-- Get a transaction's primary or secondary date, as specified.+transactionDateOrDate2 :: WhichDate -> Transaction -> Day+transactionDateOrDate2 PrimaryDate = tdate+transactionDateOrDate2 SecondaryDate = transactionDate2++-- | Ensure a transaction's postings refer back to it, so that eg+-- relatedPostings works right.+txnTieKnot :: Transaction -> Transaction+txnTieKnot t@Transaction{tpostings=ps} = t' where+ t' = t{tpostings=map (postingSetTransaction t') ps}++-- | Ensure a transaction's postings do not refer back to it, so that eg+-- recursiveSize and GHCI's :sprint work right.+txnUntieKnot :: Transaction -> Transaction+txnUntieKnot t@Transaction{tpostings=ps} = t{tpostings=map (\p -> p{ptransaction=Nothing}) ps}++-- | Set a posting's parent transaction.+postingSetTransaction :: Transaction -> Posting -> Posting+postingSetTransaction t p = p{ptransaction=Just t}++-- | Apply a transform function to this transaction's amounts.+transactionTransformPostings :: (Posting -> Posting) -> Transaction -> Transaction+transactionTransformPostings f t@Transaction{tpostings=ps} = t{tpostings=map f ps}++-- | Apply a specified valuation to this transaction's amounts, using+-- the provided price oracle, commodity styles, and reference dates.+-- See amountApplyValuation.+transactionApplyValuation :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Transaction -> Transaction+transactionApplyValuation priceoracle styles periodlast today v =+ transactionTransformPostings (postingApplyValuation priceoracle styles periodlast today v)++-- | Maybe convert this 'Transaction's amounts to cost.+transactionToCost :: ConversionOp -> Transaction -> Transaction+transactionToCost cost t = t{tpostings = mapMaybe (postingToCost cost) $ tpostings t}++-- | For any costs in this 'Transaction' which don't have associated equity conversion postings,+-- generate and add those. Generated amounts are rounded to the transaction's local display+-- precision to avoid arithmetic artifacts (e.g. 9.216 * 1801.215277778 = 16600.000000002 -> 16600.00),+-- except in a transaction whose imbalance is shown by an imbalance posting (see --infer-imbalance):+-- there, the conversion postings keep their exact cost amounts, so that every commodity balances exactly.+transactionInferEquityPostings :: Bool -> AccountName -> Transaction -> Transaction+transactionInferEquityPostings verbosetags equityAcct t =+ t{tpostings = (if hasimbalanceposting then id else map roundGenerated) $ go $ tpostings t}+ where+ hasimbalanceposting = any (postingHasTag imbalancePostingTagName) (tpostings t)+ -- The consecutive per-lot fragments of one posting (lotsplit-tagged and+ -- sharing poriginal, as in Lots.mergeLotSplits) get one set of conversion+ -- postings after the last fragment, so collapsing lot detail can still merge them.+ go [] = []+ go (p:ps) = postingsAddInferredEquityPostings verbosetags equityAcct (p:run) ++ go rest+ where+ (run, rest)+ | isLotSplit p = span (\q -> isLotSplit q && poriginal q == poriginal p) ps+ | otherwise = ([], ps)+ isLotSplit = postingHasTag lotsplitPostingTagName+ -- Round generated equity conversion posting amounts (quantities, not just display)+ -- to the transaction's local display precision, avoiding arithmetic artifacts+ -- (e.g. 9.216 * 1801.215277778 = 16600.000000002 -> 16600.00).+ styles = transactionCommodityStyles t+ roundGenerated p+ | generatedPostingTagName `elem` map fst (ptags p) = p{pamount = mapMixedAmount roundAmount (pamount p)}+ | otherwise = p+ roundAmount a = case M.lookup (acommodity a) styles of+ Just s@AmountStyle{asprecision=Precision p} -> a{aquantity = roundTo p (aquantity a), astyle = s}+ _ -> a++type IdxPosting = (Int, Posting)++-- XXX Warning: The following code - for analysing equity conversion postings,+-- inferring missing costs and ignoring redundant costs -+-- is twisty and hard to follow.++label s = ((s <> ": ")++)++-- | Add tags to a transaction, discarding any for which it already has a value.+-- Note this does not add tags to the transaction's comment.+transactionAddTags :: Transaction -> [Tag] -> Transaction+transactionAddTags t@Transaction{ttags} tags = t{ttags=ttags `union` tags}++-- | Add the given hidden tag to a transaction; and with a true argument,+-- also add the equivalent visible tag to the transaction's tags and comment fields.+-- If the transaction already has these tags (with any value), do nothing.+transactionAddHiddenAndMaybeVisibleTag :: Bool -> HiddenTag -> Transaction -> Transaction+transactionAddHiddenAndMaybeVisibleTag verbosetags ht t@Transaction{tcomment=c, ttags} =+ (t `transactionAddTags` ([ht] <> [ vt|verbosetags]))+ {tcomment=if verbosetags && not hadtag then c `commentAddTagNextLine` vt else c}+ where+ vt@(vname,_) = toVisibleTag ht+ hadtag = any ((== (T.toLower vname)) . T.toLower . fst) ttags -- XXX should regex-quote vname++-- | Find, associate, and tag the corresponding equity conversion postings and costful or potentially costful postings in this transaction.+-- With a true addcosts argument, also generate and add any equivalent costs that are missing.+-- The (previously detected) names of all equity conversion accounts should be provided.+--+-- For every pair of adjacent conversion postings, this first searches for a posting with equivalent cost (1).+-- If no such posting is found, it then searches the costless postings, for one matching one of the conversion amounts (2).+-- If either of these found a candidate posting, it is tagged with costPostingTagName.+-- Then if in addcosts mode, if a costless posting was found, a cost equivalent to the conversion amounts is added to it.+--+-- The name reflects the complexity of this and its helpers; clarification is ongoing.+--+transactionTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> [AccountName] -> Transaction -> Either String Transaction+transactionTagCostsAndEquityAndMaybeInferCosts verbosetags1 addcosts conversionaccts t+ -- Without conversion postings there is nothing to tag or infer, so skip the work (and the rebuild) below.+ | not $ any ((`elem` conversionaccts) . paccount) $ tpostings t = Right t+ | otherwise = first (annotateErrorWithTransaction t . T.unpack) $ do+ -- number the postings+ let npostings = zip [0..] $ tpostings t++ -- Identify all pairs of conversion postings and all other postings (with and without costs) in the transaction.+ (conversionPairs, otherps) <- partitionAndCheckConversionPostings False conversionaccts npostings++ -- Generate a pure function that can be applied to each of this transaction's postings,+ -- possibly modifying it, to produce the following end result:+ -- 1. each pair of conversion postings, and the corresponding postings which balance them, are tagged for easy identification+ -- 2. each pair of balancing postings which did't have an explicit cost, have had a cost calculated and added to one of them+ -- 3. if any ambiguous situation was detected, an informative error is raised+ processposting <- transformIndexedPostingsF (tagAndMaybeAddCostsForEquityPostings verbosetags1 addcosts) conversionPairs otherps++ -- And if there was no error, use it to modify the transaction's postings.+ return t{tpostings = map (snd . processposting) npostings}++ where++ -- Generate the tricksy processposting function,+ -- which when applied to each posting in turn, rather magically has the effect of+ -- applying tagAndMaybeAddCostsForEquityPostings to each pair of conversion postings in the transaction,+ -- matching them with the other postings, tagging them and perhaps adding cost information to the other postings.+ -- General type:+ -- transformIndexedPostingsF :: (Monad m, Foldable t, Traversable t) =>+ -- (a -> StateT s m (a1 -> a1)) ->+ -- t a ->+ -- s ->+ -- m (a1 -> a1)+ -- Concrete type:+ transformIndexedPostingsF ::+ ((IdxPosting, IdxPosting) -> StateT ([IdxPosting],[IdxPosting]) (Either Text) (IdxPosting -> IdxPosting)) -> -- state update function (tagAndMaybeAddCostsForEquityPostings with the bool applied)+ [(IdxPosting, IdxPosting)] -> -- initial state: the pairs of adjacent conversion postings in the transaction+ ([IdxPosting],[IdxPosting]) -> -- initial state: the other postings in the transaction, separated into costful and costless+ (Either Text (IdxPosting -> IdxPosting)) -- returns an error message or a posting transform function+ transformIndexedPostingsF updatefn = evalStateT . fmap (appEndo . foldMap Endo) . traverse (updatefn)++ -- A tricksy state update helper for processposting/transformIndexedPostingsF.+ -- Approximately: given a pair of equity conversion postings to match,+ -- and lists of the remaining unmatched costful and costless other postings,+ -- 1. find (and consume) two other postings whose amounts/cost match the two conversion postings+ -- 2. add hidden identifying tags to the conversion postings and the other posting which has (or could have) an equivalent cost+ -- 3. if in add costs mode, and the potential equivalent-cost posting does not have that explicit cost, add it+ -- 4. or if there is a problem, raise an informative error or do nothing, as appropriate.+ -- Or if there are no costful postings at all, do nothing.+ tagAndMaybeAddCostsForEquityPostings :: Bool -> Bool -> (IdxPosting, IdxPosting) -> StateT ([IdxPosting], [IdxPosting]) (Either Text) (IdxPosting -> IdxPosting)+ tagAndMaybeAddCostsForEquityPostings verbosetags addcosts' ((n1, cp1), (n2, cp2)) = StateT $ \(costps, otherps) -> do+ -- Get the two conversion posting amounts, if possible+ ca1 <- conversionPostingAmountNoCost cp1+ ca2 <- conversionPostingAmountNoCost cp2+ let + -- All costful postings whose cost is equivalent to the conversion postings' amounts.+ matchingCostfulPs =+ dbg7With (label "matched costful postings".show.length) $ + mapMaybe (mapM $ costfulPostingIfMatchesBothAmounts ca1 ca2) costps++ -- In dry run mode: all other costless, single-commodity postings.+ -- In add costs mode: all other costless, single-commodity postings whose amount matches at least one of the conversion postings,+ -- with the equivalent cost added to one of them. (?)+ matchingCostlessPs =+ dbg7With (label "matched costless postings".show.length) $+ if addcosts'+ then mapMaybe (mapM $ addCostIfMatchesOneAmount ca1 ca2) otherps+ else [(n,(p, a)) | (n,p) <- otherps, let Just a = postingSingleAmount p]++ -- A function that adds a cost and/or tag to a numbered posting if appropriate.+ postingAddCostAndOrTag np costp (n,p) =+ (n, if | n == np -> costp & postingAddHiddenAndMaybeVisibleTag False verbosetags (costPostingTagName,"") -- if it's the specified posting number, replace it with the costful posting, and tag it+ | n == n1 || n == n2 -> p & postingAddHiddenAndMaybeVisibleTag False verbosetags (conversionPostingTagName,"") -- if it's one of the equity conversion postings, tag it+ | otherwise -> p)++ -- Annotate any errors with the conversion posting pair+ first (annotateWithPostings [cp1, cp2]) $+ if+ -- If a single costful posting matches the conversion postings,+ -- delete it from the list of costful postings in the state, delete the+ -- first matching costless posting from the list of costless postings+ -- in the state, and return the transformation function with the new state.+ | [(np, costp)] <- matchingCostfulPs+ , Just newcostps <- deleteIdx np costps+ -> Right (postingAddCostAndOrTag np costp, (if addcosts' then newcostps else costps, otherps))++ -- If no costful postings match the conversion postings, but some+ -- of the costless postings match, check that the first such posting has a+ -- different amount from all the others, and if so add a cost to it,+ -- then delete it from the list of costless postings in the state,+ -- and return the transformation function with the new state.+ | [] <- matchingCostfulPs+ , (np, (costp, amt)):nps <- matchingCostlessPs+ , not $ any (amountsMatch amt . snd . snd) nps+ , Just newotherps <- deleteIdx np otherps+ -> Right (postingAddCostAndOrTag np costp, (costps, if addcosts' then newotherps else otherps))++ -- Otherwise, do nothing, leaving the transaction unchanged.+ -- We don't want to be over-zealous reporting problems here+ -- since this is always called at least in dry run mode by+ -- journalFinalise > journalMarkRedundantCosts. (#2045)+ | otherwise -> Right (id, (costps, otherps))++ -- If a posting with cost matches both the conversion amounts, return it along+ -- with the matching amount which must be present in another non-conversion posting.+ costfulPostingIfMatchesBothAmounts :: Amount -> Amount -> Posting -> Maybe Posting+ costfulPostingIfMatchesBothAmounts a1 a2 costfulp = do+ a@Amount{acost=Just _} <- postingSingleAmount costfulp+ if+ | dbgamtmatch 1 a1 a (amountsMatch (-a1) a) && dbgcostmatch 2 a2 a (costMatches a2 a) -> Just costfulp+ | dbgamtmatch 2 a2 a (amountsMatch (-a2) a) && dbgcostmatch 1 a1 a (costMatches a1 a) -> Just costfulp+ | otherwise -> Nothing+ where+ -- A conversion posting's amount matches the costful amount's cost+ -- when it equals the transacted cost; or the cost basis (a lot+ -- disposal, whose conversion postings record what the units cost,+ -- the difference from the proceeds being in the gain posting); or,+ -- when a cost basis is written but not yet known (an unspecified+ -- {} basis, filled in by lot matching later), when it is in the+ -- cost's commodity. The balancer and the post-lot gain check+ -- verify the amounts afterwards.+ costMatches c a =+ amountsMatch c (amountCost a)+ || amountsMatch c (amountCostBasis a)+ || (hasUnspecifiedBasis a && acommodity c == acommodity (amountCost a))+ hasUnspecifiedBasis a = maybe False (isNothing . cbCost) (acostbasis a)+ dbgamtmatch n a b = dbg7 ("conversion posting " <>show n<>" "<>showAmount a<>" balances amount "<>showAmountWithoutCost b <>" of costful posting "<>showAmount b<>" at precision "<>dbgShowAmountPrecision a<>" ?")+ dbgcostmatch n a b = dbg7 ("and\nconversion posting "<>show n<>" "<>showAmount a<>" matches cost " <>showAmount (amountCost b)<>" of costful posting "<>showAmount b<>" at precision "<>dbgShowAmountPrecision a<>" ?") ++ -- Add a cost to a posting if it matches (negative) one of the+ -- supplied conversion amounts, adding the other amount as the cost.+ addCostIfMatchesOneAmount :: Amount -> Amount -> Posting -> Maybe (Posting, Amount)+ addCostIfMatchesOneAmount a1 a2 p = do+ a <- postingSingleAmount p+ let newp cost = p{pamount = mixedAmount a{acost = Just $ TotalCost cost}}+ if+ | amountsMatch (-a1) a -> Just (newp a2, a2)+ | amountsMatch (-a2) a -> Just (newp a1, a1)+ | otherwise -> Nothing++ -- Get the single-commodity costless amount from a conversion posting, or raise an error.+ conversionPostingAmountNoCost p = case postingSingleAmount p of+ Just a@Amount{acost=Nothing} -> Right a+ Just Amount{acost=Just _} -> Left $ annotateWithPostings [p] "Conversion postings must not have a cost:"+ Nothing -> Left $ annotateWithPostings [p] "Conversion postings must have a single-commodity amount:"++ -- Do these amounts look the same when compared at the first's display precision ?+ amountsMatch a b = amountLooksZero $ amountSetPrecision (asprecision $ astyle a) $ a - b++ -- Delete a posting from the indexed list of postings based on either its+ -- index or its posting amount.+ -- Note: traversing the whole list to delete a single match is generally not efficient,+ -- but given that a transaction probably doesn't have more than four postings, it should+ -- still be more efficient than using a Map or another data structure. Even monster+ -- transactions with up to 10 postings, which are generally not a good+ -- idea, are still too small for there to be an advantage.+ -- XXX shouldn't assume transactions have few postings+ deleteIdx n = deleteUniqueMatch ((n==) . fst)+ deleteUniqueMatch p (x:xs) | p x = if any p xs then Nothing else Just xs+ | otherwise = (x:) <$> deleteUniqueMatch p xs+ deleteUniqueMatch _ [] = Nothing+ annotateWithPostings xs str = T.unlines $ str : postingsAsLines defaultFmt False xs++dbgShowAmountPrecision a =+ case asprecision $ astyle a of+ Precision n -> show n+ NaturalPrecision -> show $ decimalPlaces $ normalizeDecimal $ aquantity a++-- Given the names of conversion equity accounts, sort the given indexed postings+-- into three lists of posting numbers (stored in two pairs), like so:+-- (conversion postings, (costful other postings, costless other postings)).+-- A true first argument activates its secondary function: check that all+-- conversion postings occur in adjacent pairs, otherwise return an error.+partitionAndCheckConversionPostings :: Bool -> [AccountName] -> [IdxPosting] -> Either Text ( [(IdxPosting, IdxPosting)], ([IdxPosting], [IdxPosting]) )+partitionAndCheckConversionPostings check conversionaccts =+ -- Left fold processes postings in parse order, so that eg inferred costs+ -- will be added to the first (top-most) posting, not the last one.+ foldlM select (([], ([], [])), Nothing)+ -- The costless other postings are somehow reversed still; "second (second reverse)" fixes that.+ <&> fmap (second (second reverse) . fst)+ where+ select ((cs, others@(ps, os)), Nothing) np@(_, p)+ | isConversion p = Right ((cs, others), Just np)+ | hasCost p = Right ((cs, (np:ps, os)), Nothing)+ | otherwise = Right ((cs, (ps, np:os)), Nothing)+ select ((cs, others@(ps,os)), Just lst) np@(_, p)+ | isConversion p = Right (((lst, np):cs, others), Nothing)+ | check = Left "Conversion postings must occur in adjacent pairs"+ | otherwise = Right ((cs, (ps, np:os)), Nothing)+ isConversion p = paccount p `elem` conversionaccts+ hasCost p = isJust $ acost =<< postingSingleAmount p++-- | Get a posting's amount if it is single-commodity.+postingSingleAmount :: Posting -> Maybe Amount+postingSingleAmount p = case amountsRaw (pamount p) of+ [a] -> Just a+ _ -> Nothing++-- | Apply some account aliases to all posting account names in the transaction, as described by accountNameApplyAliases.+-- This can fail due to a bad replacement pattern in a regular expression alias.+transactionApplyAliases :: [AccountAlias] -> Transaction -> Either RegexError Transaction+transactionApplyAliases aliases t =+ case mapM (postingApplyAliases aliases) $ tpostings t of+ Right ps -> Right $ txnTieKnot $ t{tpostings=ps}+ Left err -> Left err++-- | Apply a transformation to a transaction's postings.+transactionMapPostings :: (Posting -> Posting) -> Transaction -> Transaction+transactionMapPostings f t@Transaction{tpostings=ps} = t{tpostings=map f ps}++-- | Apply a transformation to a transaction's posting amounts.+transactionMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Transaction -> Transaction+transactionMapPostingAmounts f = transactionMapPostings (postingTransformAmount f)++-- | All posting amounts from this transaction, in order.+transactionAmounts :: Transaction -> [MixedAmount]+transactionAmounts = map pamount . tpostings++-- | Get this transaction's local styles - the commodity styles inferred from+-- its explicitly-written (or generated from balance assignments) posting amounts.+-- Inferred balancing amounts are excluded so that they can't confusingly increase+-- the entry's local balancing precision.+transactionCommodityStyles :: Transaction -> M.Map CommoditySymbol AmountStyle+transactionCommodityStyles =+ either (const mempty) id . -- ignore style problems, commodityStylesFromAmounts doesn't report them currently+ commodityStylesFromAmounts . concatMap (amountsRaw . pamount) . filter isExplicitAmount . tpostings++-- | Like transactionCommodityStyles, but attach a particular rounding strategy to the styles,+-- affecting how they will affect display precisions when applied.+transactionCommodityStylesWith :: Rounding -> Transaction -> M.Map CommoditySymbol AmountStyle+transactionCommodityStylesWith r = amountStylesSetRounding r . transactionCommodityStyles++-- | Flip the sign of this transaction's posting amounts (and balance assertion amounts).+transactionNegate :: Transaction -> Transaction+transactionNegate = transactionMapPostings postingNegate++-- | The file path from which this transaction was parsed.+transactionFile :: Transaction -> FilePath+transactionFile Transaction{tsourcepos} = sourceName $ fst tsourcepos++-- Add transaction information to an error message.+annotateErrorWithTransaction :: Transaction -> String -> String+annotateErrorWithTransaction t s =+ unlines [ sourcePosPairPretty $ tsourcepos t, s+ , T.unpack . T.stripEnd $ showTransaction t+ ]++-- tests++tests_Transaction :: TestTree+tests_Transaction =+ testGroup "Transaction" [++ testGroup "showPostingLines" [+ testCase "null posting" $ showPostingLines nullposting @?= [" 0"]+ , testCase "non-null posting" $+ let p =+ posting+ { pstatus = Cleared+ , paccount = "a"+ , pamount = mixed [usd 1, hrs 2]+ , pcomment = "pcomment1\npcomment2\n tag3: val3 \n"+ , preal = RealPosting+ , ptags = [("ptag1", "val1"), ("ptag2", "val2")]+ }+ in showPostingLines p @?=+ [ " * a $1.00 ; pcomment1"+ , " ; pcomment2"+ , " ; tag3: val3 "+ , " * a 2.00h ; pcomment1"+ , " ; pcomment2"+ , " ; tag3: val3 "+ ]+ ]++ , let+ -- one implicit amount+ timp = nulltransaction {tpostings = ["a" `post` usd 1, "b" `post` missingamt]}+ -- explicit amounts, balanced+ texp = nulltransaction {tpostings = ["a" `post` usd 1, "b" `post` usd (-1)]}+ -- explicit amount, only one posting+ texp1 = nulltransaction {tpostings = ["(a)" `post` usd 1]}+ -- explicit amounts, two commodities, explicit balancing price+ texp2 = nulltransaction {tpostings = ["a" `post` usd 1, "b" `post` (hrs (-1) `at` usd 1)]}+ -- explicit amounts, two commodities, implicit balancing price+ texp2b = nulltransaction {tpostings = ["a" `post` usd 1, "b" `post` hrs (-1)]}+ -- one missing amount, not the last one+ t3 = nulltransaction {tpostings = ["a" `post` usd 1, "b" `post` missingamt, "c" `post` usd (-1)]}+ -- unbalanced amounts when precision is limited (#931)+ -- t4 = nulltransaction {tpostings = ["a" `post` usd (-0.01), "b" `post` usd (0.005), "c" `post` usd (0.005)]}+ in testGroup "postingsAsLines" [+ testCase "null-transaction" $ postingsAsLines defaultFmt False (tpostings nulltransaction) @?= []+ , testCase "implicit-amount" $ postingsAsLines defaultFmt False (tpostings timp) @?=+ [ " a $1.00"+ , " b" -- implicit amount remains implicit+ ]+ , testCase "explicit-amounts" $ postingsAsLines defaultFmt False (tpostings texp) @?=+ [ " a $1.00"+ , " b $-1.00"+ ]+ , testCase "one-explicit-amount" $ postingsAsLines defaultFmt False (tpostings texp1) @?=+ [ " (a) $1.00"+ ]+ , testCase "explicit-amounts-two-commodities" $ postingsAsLines defaultFmt False (tpostings texp2) @?=+ [ " a $1.00"+ , " b -1.00h @ $1.00"+ ]+ , testCase "explicit-amounts-not-explicitly-balanced" $ postingsAsLines defaultFmt False (tpostings texp2b) @?=+ [ " a $1.00"+ , " b -1.00h"+ ]+ , testCase "implicit-amount-not-last" $ postingsAsLines defaultFmt False (tpostings t3) @?=+ [" a $1.00", " b", " c $-1.00"]+ -- , testCase "ensure-visibly-balanced" $+ -- in postingsAsLines False (tpostings t4) @?=+ -- [" a $-0.01", " b $0.005", " c $0.005"]++ ]++ , testGroup "showTransaction" [+ testCase "null transaction" $ showTransaction nulltransaction @?= "0000-01-01\n\n"+ , testCase "non-null transaction" $ showTransaction+ nulltransaction+ { tdate = fromGregorian 2012 05 14+ , tdate2 = Just $ fromGregorian 2012 05 15+ , tstatus = Unmarked+ , tcode = "code"+ , tdescription = "desc"+ , tcomment = "tcomment1\ntcomment2\n"+ , ttags = [("ttag1", "val1")]+ , tpostings =+ [ nullposting+ { pstatus = Cleared+ , paccount = "a"+ , pamount = mixed [usd 1, hrs 2]+ , pcomment = "\npcomment2\n"+ , preal = RealPosting+ , ptags = [("ptag1", "val1"), ("ptag2", "val2")]+ }+ ]+ } @?=+ T.unlines+ [ "2012-05-14=2012-05-15 (code) desc ; tcomment1"+ , " ; tcomment2"+ , " * a $1.00"+ , " ; pcomment2"+ , " * a 2.00h"+ , " ; pcomment2"+ , ""+ ]+ , testCase "show a balanced transaction" $+ (let t =+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ "coopportunity"+ ""+ []+ [ posting {paccount = "expenses:food:groceries", pamount = mixedAmount (usd 47.18), ptransaction = Just t}+ , posting {paccount = "assets:checking", pamount = mixedAmount (usd (-47.18)), ptransaction = Just t}+ ]+ in showTransaction t) @?=+ (T.unlines+ [ "2007-01-28 coopportunity"+ , " expenses:food:groceries $47.18"+ , " assets:checking $-47.18"+ , ""+ ])+ , testCase "show an unbalanced transaction, should not elide" $+ (showTransaction+ (txnTieKnot $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ "coopportunity"+ ""+ []+ [ posting {paccount = "expenses:food:groceries", pamount = mixedAmount (usd 47.18)}+ , posting {paccount = "assets:checking", pamount = mixedAmount (usd (-47.19))}+ ])) @?=+ (T.unlines+ [ "2007-01-28 coopportunity"+ , " expenses:food:groceries $47.18"+ , " assets:checking $-47.19"+ , ""+ ])+ , testCase "show a transaction with one posting and a missing amount" $+ (showTransaction+ (txnTieKnot $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2007 01 28)+ Nothing+ Unmarked+ ""+ "coopportunity"+ ""+ []+ [posting {paccount = "expenses:food:groceries", pamount = missingmixedamt}])) @?=+ (T.unlines ["2007-01-28 coopportunity", " expenses:food:groceries", ""])+ , testCase "show a transaction with a priced commodityless amount" $+ (showTransaction+ (txnTieKnot $+ Transaction+ 0+ ""+ nullsourcepospair+ (fromGregorian 2010 01 01)+ Nothing+ Unmarked+ ""+ "x"+ ""+ []+ [ posting {paccount = "a", pamount = mixedAmount $ num 1 `at` (usd 2 `withPrecision` Precision 0)}+ , posting {paccount = "b", pamount = missingmixedamt}+ ])) @?=+ (T.unlines ["2010-01-01 x", " a 1 @ $2", " b", ""])+ ]+ ]
+ Hledger/Data/TransactionModifier.hs view
@@ -0,0 +1,158 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ViewPatterns #-}+{-|++A 'TransactionModifier' is a rule that modifies certain 'Transaction's,+typically adding automated postings to them.++-}+module Hledger.Data.TransactionModifier (+ modifyTransactions+)+where++import Prelude hiding (Applicative(..))+import Control.Applicative (Applicative(..), (<|>))+import Data.Function ((&))+import Data.Map qualified as M+import Data.Maybe (catMaybes)+import Data.Text qualified as T+import Data.Time.Calendar (Day)+import Safe (headDef)+import Hledger.Data.Types+import Hledger.Data.Amount+import Hledger.Data.Dates+import Hledger.Data.Transaction (txnTieKnot, transactionAddHiddenAndMaybeVisibleTag)+import Hledger.Query (Query, filterQuery, matchesAmount, matchesPostingExtra,+ parseQuery, queryIsAmt, queryIsCur, simplifyQuery)+import Hledger.Data.Posting (commentJoin, commentAddTag, postingAddTags, modifiedTransactionTagName)+import Hledger.Utils (dbg6, wrap)++-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Hledger.Data.Posting+-- >>> import Hledger.Data.Transaction+-- >>> import Hledger.Data.Journal++-- | Apply all the given transaction modifiers, in turn, to each transaction.+-- Or if any of them fails to be parsed, return the first error. A reference+-- date is provided to help interpret relative dates in transaction modifier+-- queries.+modifyTransactions :: (AccountName -> Maybe AccountType)+ -> (AccountName -> [Tag])+ -> M.Map CommoditySymbol AmountStyle+ -> Day -> Bool -> [TransactionModifier] -> [Transaction]+ -> Either String [Transaction]+modifyTransactions atypes atags styles d verbosetags tmods ts = do+ fs <- mapM (transactionModifierToFunction atypes atags styles d verbosetags) tmods -- convert modifiers to functions, or return a parse error+ let+ modifytxn t =+ t' & if t'/=t then transactionAddHiddenAndMaybeVisibleTag verbosetags (modifiedTransactionTagName,"") else id+ where+ t' = foldr (flip (.)) id fs t -- apply each function in turn++ Right $ map modifytxn ts++-- | Converts a 'TransactionModifier' to a 'Transaction'-transforming function+-- which applies the modification(s) specified by the TransactionModifier.+-- Or, returns the error message there is a problem parsing the TransactionModifier's query.+-- A reference date is provided to help interpret relative dates in the query.+--+-- The postings of the transformed transaction will reference it in the usual+-- way (ie, 'txnTieKnot' is called).+--+-- Currently the only kind of modification possible is adding automated+-- postings when certain other postings are present.+--+-- >>> import Data.Text.IO qualified as T+-- >>> t = nulltransaction{tpostings=["ping" `post` usd 1]}+-- >>> tmpost acc amt = TMPostingRule (acc `post` amt) False+-- >>> test = either putStr (T.putStr.showTransaction) . fmap ($ t) . transactionModifierToFunction (const Nothing) (const []) mempty nulldate True+-- >>> test $ TransactionModifier "" ["pong" `tmpost` usd 2]+-- 0000-01-01+-- ping $1.00+-- pong $2.00 ; generated-posting: =+-- <BLANKLINE>+-- >>> test $ TransactionModifier "miss" ["pong" `tmpost` usd 2]+-- 0000-01-01+-- ping $1.00+-- <BLANKLINE>+-- >>> test $ TransactionModifier "ping" [("pong" `tmpost` nullamt{aquantity=3}){tmprIsMultiplier=True}]+-- 0000-01-01+-- ping $1.00+-- pong $3.00 ; generated-posting: = ping+-- <BLANKLINE>+--+transactionModifierToFunction :: (AccountName -> Maybe AccountType)+ -> (AccountName -> [Tag])+ -> M.Map CommoditySymbol AmountStyle+ -> Day -> Bool -> TransactionModifier+ -> Either String (Transaction -> Transaction)+transactionModifierToFunction atypes atags styles refdate verbosetags TransactionModifier{tmquerytxt, tmpostingrules} = do+ q <- simplifyQuery . fst <$> parseQuery refdate tmquerytxt+ let+ fs = map (\tmpr -> addAccountTags . tmPostingRuleToFunction verbosetags styles q tmquerytxt tmpr) tmpostingrules+ addAccountTags p = p `postingAddTags` atags (paccount p)+ generatePostings p = p : map ($ p) (if matchesPostingExtra atypes q p then fs else [])+ Right $ \t@(tpostings -> ps) -> txnTieKnot t{tpostings=concatMap generatePostings ps}++-- | Converts a 'TransactionModifier''s posting rule to a 'Posting'-generating function,+-- which will be used to make a new posting based on the old one (an "automated posting").+-- The new posting's amount can optionally be the old posting's amount multiplied by a constant.+-- If the old posting had a total-priced amount, the new posting's multiplied amount will be unit-priced.+-- The new posting will have a hidden _generated-posting: tag added,+-- and with a true first argument, also a visible generated-posting: tag.+-- The provided TransactionModifier's query text is saved as the tags' value.+tmPostingRuleToFunction :: Bool -> M.Map CommoditySymbol AmountStyle -> Query -> T.Text -> TMPostingRule -> (Posting -> Posting)+tmPostingRuleToFunction verbosetags styles query querytxt tmpr =+ \p -> styleAmounts styles . renderPostingCommentDates $ pr+ { pdate = pdate pr <|> pdate p+ , pdate2 = pdate2 pr <|> pdate2 p+ , paccount = account' p+ , pamount = amount' p+ , pcomment = pcomment pr & (if verbosetags then (`commentAddTag` ("generated-posting",qry)) else id)+ , ptags = ptags pr+ & (("_generated-posting",qry) :)+ & (if verbosetags then (("generated-posting", qry) :) else id)+ }+ where+ pr = tmprPosting tmpr+ qry = "= " <> querytxt+ symq = filterQuery (liftA2 (||) queryIsCur queryIsAmt) query+ account' = if accountTemplate `T.isInfixOf` paccount pr+ then \p -> T.replace accountTemplate (paccount p) $ paccount pr+ else const $ paccount pr+ where accountTemplate = "%account"+ amount' = case postingRuleMultiplier tmpr of+ Nothing -> const $ pamount pr+ Just n -> \p ->+ -- Multiply the old posting's amount by the posting rule's multiplier.+ let+ pramount = dbg6 "pramount" . headDef nullamt . amountsRaw $ pamount pr+ matchedamount = dbg6 "matchedamount" . filterMixedAmount (symq `matchesAmount`) $ pamount p+ -- Handle a matched amount with a total price carefully so as to keep the transaction balanced (#928).+ -- Approach 1: convert to a unit price and increase the display precision slightly+ -- Mixed as = dbg6 "multipliedamount" $ n `multiplyMixedAmount` mixedAmountTotalCostToUnitCost matchedamount+ -- Approach 2: multiply the total price (keeping it positive) as well as the quantity+ as = dbg6 "multipliedamount" $ multiplyMixedAmount n matchedamount+ in+ case acommodity pramount of+ "" -> as+ -- TODO multipliers with commodity symbols are not yet a documented feature.+ -- For now: in addition to multiplying the quantity, it also replaces the+ -- matched amount's commodity, display style, and price with those of the posting rule.+ c -> mapMixedAmount (\a -> a{acommodity = c, astyle = astyle pramount, acost = acost pramount}) as++postingRuleMultiplier :: TMPostingRule -> Maybe Quantity+postingRuleMultiplier tmpr = case amountsRaw . pamount $ tmprPosting tmpr of+ [a] | tmprIsMultiplier tmpr -> Just $ aquantity a+ _ -> Nothing++renderPostingCommentDates :: Posting -> Posting+renderPostingCommentDates p = p { pcomment = comment' }+ where+ dates = T.concat $ catMaybes [showDate <$> pdate p, ("=" <>) . showDate <$> pdate2 p]+ comment'+ | T.null dates = pcomment p+ | otherwise = (wrap "[" "]" dates) `commentJoin` pcomment p
Hledger/Data/Types.hs view
@@ -1,205 +1,971 @@-{-# LANGUAGE DeriveDataTypeable #-}-{-|--Most data types are defined here to avoid import cycles.-Here is an overview of the hledger data model:--> Journal -- a journal is read from one or more data files. It contains..-> [Transaction] -- journal transactions (aka entries), which have date, status, code, description and..-> [Posting] -- multiple account postings, which have account name and amount-> [HistoricalPrice] -- historical commodity prices->-> Ledger -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..-> Journal -- a filtered copy of the original journal, containing only the transactions and postings we are interested in-> Tree AccountName -- all accounts named by the journal's transactions, as a hierarchy-> Map AccountName Account -- the postings, and resulting balances, in each account--For more detailed documentation on each type, see the corresponding modules.--Evolution of transaction\/entry\/posting terminology:-- - ledger 2: entries contain transactions-- - hledger 0.4: Entrys contain RawTransactions (which are flattened to Transactions)-- - ledger 3: transactions contain postings-- - hledger 0.5: LedgerTransactions contain Postings (which are flattened to Transactions)-- - hledger 0.8: Transactions contain Postings (referencing Transactions..)---}--module Hledger.Data.Types-where-import Control.Monad.Error (ErrorT)-import Data.Time.Calendar-import Data.Time.LocalTime-import Data.Tree-import Data.Typeable-import qualified Data.Map as Map-import System.Time (ClockTime)---type SmartDate = (String,String,String)--data WhichDate = ActualDate | EffectiveDate deriving (Eq,Show)--data DateSpan = DateSpan (Maybe Day) (Maybe Day) deriving (Eq,Show,Ord)--data Interval = NoInterval- | Days Int | Weeks Int | Months Int | Quarters Int | Years Int- | DayOfMonth Int | DayOfWeek Int- -- WeekOfYear Int | MonthOfYear Int | QuarterOfYear Int- deriving (Eq,Show,Ord)--type AccountName = String--data Side = L | R deriving (Eq,Show,Read,Ord)--data Commodity = Commodity {- symbol :: String, -- ^ the commodity's symbol- -- display preferences for amounts of this commodity- side :: Side, -- ^ should the symbol appear on the left or the right- spaced :: Bool, -- ^ should there be a space between symbol and quantity- precision :: Int, -- ^ number of decimal places to display- -- XXX these three might be better belonging to Journal- decimalpoint :: Char, -- ^ character to use as decimal point- separator :: Char, -- ^ character to use for separating digit groups (eg thousands)- separatorpositions :: [Int] -- ^ positions of separators, counting leftward from decimal point- } deriving (Eq,Ord,Show,Read)---- | An amount's price in another commodity may be written as \@ unit--- price or \@\@ total price. Note although a MixedAmount is used, it--- should be in a single commodity, also the amount should be positive;--- these are not enforced currently.-data Price = UnitPrice MixedAmount | TotalPrice MixedAmount- deriving (Eq,Ord)--data Amount = Amount {- commodity :: Commodity,- quantity :: Double,- price :: Maybe Price -- ^ the price for this amount at posting time- } deriving (Eq,Ord)--newtype MixedAmount = Mixed [Amount] deriving (Eq,Ord)--data PostingType = RegularPosting | VirtualPosting | BalancedVirtualPosting- deriving (Eq,Show)--data Posting = Posting {- pstatus :: Bool,- paccount :: AccountName,- pamount :: MixedAmount,- pcomment :: String,- ptype :: PostingType,- pmetadata :: [(String,String)],- ptransaction :: Maybe Transaction -- ^ this posting's parent transaction (co-recursive types).- -- Tying this knot gets tedious, Maybe makes it easier/optional.- }---- The equality test for postings ignores the parent transaction's--- identity, to avoid infinite loops.-instance Eq Posting where- (==) (Posting a1 b1 c1 d1 e1 f1 _) (Posting a2 b2 c2 d2 e2 f2 _) = a1==a2 && b1==b2 && c1==c2 && d1==d2 && e1==e2 && f1==f2--data Transaction = Transaction {- tdate :: Day,- teffectivedate :: Maybe Day,- tstatus :: Bool, -- XXX tcleared ?- tcode :: String,- tdescription :: String,- tcomment :: String,- tmetadata :: [(String,String)],- tpostings :: [Posting], -- ^ this transaction's postings (co-recursive types).- tpreceding_comment_lines :: String- } deriving (Eq)--data ModifierTransaction = ModifierTransaction {- mtvalueexpr :: String,- mtpostings :: [Posting]- } deriving (Eq)--data PeriodicTransaction = PeriodicTransaction {- ptperiodicexpr :: String,- ptpostings :: [Posting]- } deriving (Eq)--data TimeLogCode = SetBalance | SetRequiredHours | In | Out | FinalOut deriving (Eq,Ord) --data TimeLogEntry = TimeLogEntry {- tlcode :: TimeLogCode,- tldatetime :: LocalTime,- tlcomment :: String- } deriving (Eq,Ord)--data HistoricalPrice = HistoricalPrice {- hdate :: Day,- hsymbol :: String,- hamount :: MixedAmount- } deriving (Eq) -- & Show (in Amount.hs)--type Year = Integer---- | A journal "context" is some data which can change in the course of--- parsing a journal. An example is the default year, which changes when a--- Y directive is encountered. At the end of parsing, the final context--- is saved for later use by eg the add command.-data JournalContext = Ctx {- ctxYear :: !(Maybe Year) -- ^ the default year most recently specified with Y- , ctxCommodity :: !(Maybe Commodity) -- ^ the default commodity most recently specified with D- , ctxAccount :: ![AccountName] -- ^ the current stack of parent accounts/account name components- -- specified with "account" directive(s). Concatenated, these- -- are the account prefix prepended to parsed account names.- , ctxAliases :: ![(AccountName,AccountName)] -- ^ the current list of account name aliases in effect- } deriving (Read, Show, Eq)--data Journal = Journal {- jmodifiertxns :: [ModifierTransaction],- jperiodictxns :: [PeriodicTransaction],- jtxns :: [Transaction],- open_timelog_entries :: [TimeLogEntry],- historical_prices :: [HistoricalPrice],- final_comment_lines :: String, -- ^ any trailing comments from the journal file- jContext :: JournalContext, -- ^ the context (parse state) at the end of parsing- files :: [(FilePath, String)], -- ^ the file path and raw text of the main and- -- any included journal files. The main file is- -- first followed by any included files in the- -- order encountered.- filereadtime :: ClockTime -- ^ when this journal was last read from its file(s)- } deriving (Eq, Typeable)---- | A JournalUpdate is some transformation of a Journal. It can do I/O or--- raise an error.-type JournalUpdate = ErrorT String IO (Journal -> Journal)---- | A hledger journal reader is a triple of format name, format-detecting--- predicate, and a parser to Journal.-data Reader = Reader {rFormat :: String- ,rDetector :: FilePath -> String -> Bool- ,rParser :: FilePath -> String -> ErrorT String IO Journal- }--data Ledger = Ledger {- journal :: Journal,- accountnametree :: Tree AccountName,- accountmap :: Map.Map AccountName Account- }--data Account = Account {- aname :: AccountName,- apostings :: [Posting], -- ^ postings in this account- abalance :: MixedAmount -- ^ sum of postings in this account and subaccounts- }---- | A generic, pure specification of how to filter (or search) transactions and postings.-data FilterSpec = FilterSpec {- datespan :: DateSpan -- ^ only include if in this date span- ,cleared :: Maybe Bool -- ^ only include if cleared\/uncleared\/don't care- ,real :: Bool -- ^ only include if real\/don't care- ,empty :: Bool -- ^ include if empty (ie amount is zero)- ,acctpats :: [String] -- ^ only include if matching these account patterns- ,descpats :: [String] -- ^ only include if matching these description patterns- ,depth :: Maybe Int- } deriving (Show)-+ {-|++Most data types are defined here to avoid import cycles.+Here is an overview of the hledger data model:++> Journal -- a journal is read from one or more data files. It contains..+> [Transaction] -- journal transactions (aka entries), which have date, cleared status, code, description and..+> [Posting] -- multiple account postings, which have account name and amount+> [MarketPrice] -- historical market prices for commodities+>+> Ledger -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..+> Journal -- a filtered copy of the original journal, containing only the transactions and postings we are interested in+> [Account] -- all accounts, in tree order beginning with a "root" account", with their balances and sub/parent accounts++For more detailed documentation on each type, see the corresponding modules.++-}++-- {-# LANGUAGE DeriveAnyClass #-} -- https://hackage.haskell.org/package/deepseq-1.4.4.0/docs/Control-DeepSeq.html#v:rnf+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE StrictData #-}++module Hledger.Data.Types (+ module Hledger.Data.Types,+#if MIN_VERSION_time(1,11,0)+ Year+#endif+)+where++import GHC.Generics (Generic)+import Control.DeepSeq (NFData(..))+import Data.Bifunctor (first)+import Data.Decimal (Decimal, DecimalRaw(..))+import Data.Default (Default(..))+import Data.Functor (($>))+import Data.List (intercalate, sortBy)+--XXX https://hackage.haskell.org/package/containers/docs/Data-Map.html+--Note: You should use Data.Map.Strict instead of this module if:+--You will eventually need all the values stored.+--The stored values don't represent large virtual data structures to be lazily computed.+import Data.Map qualified as M+import Data.Set qualified as S+import Data.Ord (comparing)+import Data.Semigroup (Min(..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day)+import Data.Time.Clock.POSIX (POSIXTime)+import Data.Time.LocalTime (LocalTime)+import Data.Word (Word8)+import Text.Blaze (ToMarkup(..))+import Text.Megaparsec (SourcePos(SourcePos), mkPos)++import Hledger.Utils.Regex+++-- synonyms for various date-related scalars+#if MIN_VERSION_time(1,11,0)+import Data.Time.Calendar (Year)+#else+type Year = Integer+#endif+type Month = Int -- 1-12+type Quarter = Int -- 1-4+type YearWeek = Int -- 1-52+type MonthWeek = Int -- 1-5+type YearDay = Int -- 1-366+type MonthDay = Int -- 1-31+type WeekDay = Int -- 1-7++-- | A possibly incomplete year-month-day date provided by the user, to be+-- interpreted as either a date or a date span depending on context. Missing+-- parts "on the left" will be filled from the provided reference date, e.g. if+-- the year and month are missing, the reference date's year and month are used.+-- Missing parts "on the right" are assumed, when interpreting as a date, to be+-- 1, (e.g. if the year and month are present but the day is missing, it means+-- first day of that month); or when interpreting as a date span, to be a+-- wildcard (so it would mean all days of that month). See the `smartdate`+-- parser for more examples.+--+-- Or, one of the standard periods and a numeric offset relative to the reference date:+-- (last|this|next) (day|week|month|quarter|year), where "this" means the period+-- containing the reference date.+--+-- Or, (last|this|next) weekdayname, where "this" "next".+--+-- Or, (last|this|next) monthname, where "this" means the previous 1st if in that month,+-- otherwise the start of the next occurrence of that month.+--+data SmartDate+ = SmartCompleteDate Day+ | SmartAssumeStart Year (Maybe Month) -- XXX improve these constructor names+ | SmartFromReference (Maybe Month) MonthDay --+ | SmartMonth Month+ | SmartRelative Integer SmartInterval+ | SmartRelativeMonth Ordering Month -- ^ EQ will be treated like GT+ | SmartRelativeWeekDay Ordering WeekDay+ deriving (Show)++data SmartInterval = Day | Week | Month | Quarter | Year deriving (Show)++data WhichDate = PrimaryDate | SecondaryDate deriving (Eq,Show)++-- | A date which is either exact or flexible.+-- Flexible dates are allowed to be adjusted in certain situations.+data EFDay = Exact Day | Flex Day deriving (Eq,Generic,Show)++-- EFDay's Ord instance treats them like ordinary dates, ignoring exact/flexible.+instance Ord EFDay where compare d1 d2 = compare (fromEFDay d1) (fromEFDay d2)++fromEFDay :: EFDay -> Day+fromEFDay (Exact d) = d+fromEFDay (Flex d) = d++modifyEFDay :: (Day -> Day) -> EFDay -> EFDay+modifyEFDay f (Exact d) = Exact $ f d+modifyEFDay f (Flex d) = Flex $ f d++-- | A possibly open-ended span of time, from an optional inclusive start date+-- to an optional exclusive end date. Each date can be either exact or flexible.+-- An "exact date span" is a Datepan with exact start and end dates.+data DateSpan = DateSpan (Maybe EFDay) (Maybe EFDay) deriving (Eq,Ord,Generic)++instance Default DateSpan where def = DateSpan Nothing Nothing++-- Some common report subperiods, both finite and open-ended.+-- A higher-level abstraction than DateSpan.+data Period =+ DayPeriod Day+ | WeekPeriod Day+ | MonthPeriod Year Month+ | QuarterPeriod Year Quarter+ | YearPeriod Year+ | PeriodBetween Day Day+ | PeriodFrom Day+ | PeriodTo Day+ | PeriodAll+ deriving (Eq,Ord,Show,Generic)++instance Default Period where def = PeriodAll++-- All the kinds of report interval allowed in a period expression+-- (to generate periodic reports or periodic transactions).+data Interval =+ NoInterval+ | Days Int+ | Weeks Int+ | Months Int+ | Quarters Int+ | Years Int+ | NthWeekdayOfMonth Int Int -- n, weekday 1-7+ | MonthDay Int -- 1-31+ | MonthAndDay Int Int -- month 1-12, monthday 1-31+ | DaysOfWeek [Int] -- [weekday 1-7]+ deriving (Eq,Show,Ord,Generic)++instance Default Interval where def = NoInterval++type Payee = Text++type AccountName = Text++-- A specification indicating how to depth-limit+data DepthSpec = DepthSpec {+ dsFlatDepth :: Maybe Int,+ dsRegexpDepths :: [(Regexp, Int)]+ } deriving (Eq,Show)++-- Semigroup instance consider all regular expressions, but take the minimum of the simple flat depths+instance Semigroup DepthSpec where+ DepthSpec d1 l1 <> DepthSpec d2 l2 = DepthSpec (getMin <$> (Min <$> d1) <> (Min <$> d2)) (l1 ++ l2)++instance Monoid DepthSpec where+ mempty = DepthSpec Nothing []++data AccountType =+ Asset+ | Liability+ | Equity+ | Revenue+ | Expense+ | Cash -- ^ a subtype of Asset - liquid assets to show in cashflow report+ | Conversion -- ^ a subtype of Equity - account with which to balance commodity conversions+ | Gain -- ^ a subtype of Revenue - realised capital gains/losses+ | UnrealisedGain -- ^ a subtype of Equity - accumulated unrealised capital gains/losses+ | Imbalance -- ^ a subtype of Equity - transactions' tolerated imbalances, shown by --infer-imbalance+ deriving (Eq,Ord,Generic,Enum,Bounded)++instance Show AccountType where+ show Asset = "A"+ show Liability = "L"+ show Equity = "E"+ show Revenue = "R"+ show Expense = "X"+ show Cash = "C"+ show Conversion = "V"+ show Gain = "G"+ show UnrealisedGain = "U"+ show Imbalance = "M"++isBalanceSheetAccountType :: AccountType -> Bool+isBalanceSheetAccountType t = t `elem` [+ Asset,+ Liability,+ Equity,+ Cash,+ Conversion,+ UnrealisedGain,+ Imbalance+ ]++isIncomeStatementAccountType :: AccountType -> Bool+isIncomeStatementAccountType t = t `elem` [+ Revenue,+ Expense,+ Gain+ ]++-- not worth the trouble, letters defined in accountdirectivep for now+--instance Read AccountType+-- where+-- readsPrec _ ('A' : xs) = [(Asset, xs)]+-- readsPrec _ ('L' : xs) = [(Liability, xs)]+-- readsPrec _ ('E' : xs) = [(Equity, xs)]+-- readsPrec _ ('R' : xs) = [(Revenue, xs)]+-- readsPrec _ ('X' : xs) = [(Expense, xs)]+-- readsPrec _ _ = []++data AccountAlias = BasicAlias AccountName AccountName+ | RegexAlias Regexp Replacement+ deriving (Eq, Read, Show, Ord, Generic)++data Side = L | R deriving (Eq,Show,Read,Ord,Generic)++-- | One of the decimal marks we support: either period or comma.+type DecimalMark = Char++isDecimalMark :: Char -> Bool+isDecimalMark c = c == '.' || c == ','++-- | The basic numeric type used in amounts.+type Quantity = Decimal+-- The following is for hledger-web, and requires blaze-markup.+-- Doing it here avoids needing a matching flag on the hledger-web package.+instance ToMarkup Quantity+ where+ toMarkup = toMarkup . show+deriving instance Generic (DecimalRaw a)++-- | An amount's per-unit or total cost/selling price in another+-- commodity, as recorded in the journal entry eg with @ or @@.+-- "Cost", formerly AKA "transaction price". The amount is always positive.+data AmountCost = UnitCost !Amount | TotalCost !Amount+ deriving (Eq,Ord,Generic,Show)++-- | Display styles for amounts - things which can be detected during parsing, such as+-- commodity side and spacing, digit group marks, decimal mark, number of decimal digits etc.+-- Every "Amount" has an AmountStyle.+-- After amounts are parsed from the input, for each "Commodity" a standard style is inferred+-- and then used when displaying amounts in that commodity.+-- Related to "AmountFormat" but higher level.+--+-- See also:+-- - hledger manual > Commodity styles+-- - hledger manual > Amounts+-- - hledger manual > Commodity display style+data AmountStyle = AmountStyle {+ ascommodityside :: !Side, -- ^ show the symbol on the left or the right ?+ ascommodityspaced :: !Bool, -- ^ show a space between symbol and quantity ?+ asdigitgroups :: !(Maybe DigitGroupStyle), -- ^ show the integer part with these digit group marks, or not+ asdecimalmark :: !(Maybe Char), -- ^ show this character (should be . or ,) as decimal mark, or use the default (.)+ asprecision :: !AmountPrecision, -- ^ "display precision" - show this number of digits after the decimal point+ asrounding :: !Rounding -- ^ "rounding strategy" - kept here for convenience, for now:+ -- when displaying an amount, it is ignored,+ -- but when applying this style to another amount, it determines + -- how hard we should try to adjust that amount's display precision.+} deriving (Eq,Ord,Read,Generic)++instance Show AmountStyle where+ show AmountStyle{..} = unwords+ [ "AmountStylePP"+ , show ascommodityside+ , show ascommodityspaced+ , show asdigitgroups+ , show asdecimalmark+ , show asprecision+ , show asrounding+ ]++-- | The "display precision" for a hledger amount, by which we mean+-- the number of decimal digits to display to the right of the decimal mark.+data AmountPrecision =+ Precision !Word8 -- ^ show this many decimal digits (0..255)+ | NaturalPrecision -- ^ show all significant decimal digits stored internally+ deriving (Eq,Ord,Read,Show,Generic)++-- | "Rounding strategy" - how to apply an AmountStyle's display precision+-- to a posting amount (and its cost, if any). +-- Mainly used to customise print's output, with --round=none|soft|hard|all.+data Rounding =+ NoRounding -- ^ keep display precisions unchanged in amt and cost+ | SoftRounding -- ^ do soft rounding of amt and cost amounts (show more or fewer decimal zeros to approximate the target precision, but don't hide significant digits)+ | HardRounding -- ^ do hard rounding of amt (use the exact target precision, possibly hiding significant digits), and soft rounding of cost+ | AllRounding -- ^ do hard rounding of amt and cost+ deriving (Eq,Ord,Read,Show,Generic)++-- | A style for displaying digit groups in the integer part of a+-- floating point number. It consists of the character used to+-- separate groups (any of the digit group marks accepted when parsing:+-- period, comma, underscore, apostrophe, or one of several unicode+-- spaces; see isDigitSeparatorChar), and the size of each group,+-- starting with the one nearest the decimal point. The last group size+-- is assumed to repeat. Eg, comma between thousands is DigitGroups ',' [3].+data DigitGroupStyle = DigitGroups !Char ![Word8]+ deriving (Eq,Ord,Read,Show,Generic)++type CommoditySymbol = Text++data Commodity = Commodity {+ csymbol :: CommoditySymbol,+ cformat :: Maybe AmountStyle,+ ccomment :: Text, -- ^ any comment lines following the commodity directive+ ctags :: [Tag], -- ^ tags extracted from the comment, if any+ caliases :: [(Amount, SourcePos)], -- ^ aliases declared by alias: tags: each alias's symbol, and the number of its units equal to one unit of this commodity, as written;+ -- and the position of the commodity directive which declared it+ csourcepos :: SourcePos -- ^ source position of the commodity directive+ } deriving (Show,Eq,Generic) --,Ord)++-- | The cost basis of an individual lot - some quantity of an asset acquired at a given date and time.+-- This can represent a definite cost basis, which must have a cost and date; the label is optional.+-- Or it can represent a cost basis matcher for selecting lots.+-- Note: cost is always stored as a per-unit cost, even if the user specified total cost with {{}}.+data CostBasis = CostBasis {+ cbDate :: !(Maybe Day), -- ^ nominal acquisition date+ cbLabel :: !(Maybe Text), -- ^ a short label to ensure uniqueness, correct intra-day order, or memorability, if needed+ cbCost :: !(Maybe Amount) -- ^ nominal acquisition cost (per-unit)+} deriving (Show,Eq,Generic,Ord)++-- | Identifies a specific lot of a commodity, by its acquisition date and optional label.+-- Ordered by date first, then label (Nothing sorts before Just).+data LotId = LotId {+ lotDate :: !Day,+ lotLabel :: !(Maybe Text)+} deriving (Show,Eq,Ord,Generic)++-- | The method used to select lots for disposal or transfer.+-- Per-account methods (scoped to the posting's account):+-- FIFO/LIFO select oldest/newest first. HIFO selects highest cost first.+-- AVERAGE uses weighted average cost basis for disposals (FIFO consumption order).+-- SPECID requires every disposal/transfer to have an explicit lot selector matching exactly one lot.+-- Global validation methods (*ALL variants):+-- FIFOALL/LIFOALL/HIFOALL select per-account but validate that the selected lots would also+-- be chosen first if all accounts' lots were considered together. Errors if not.+-- AVERAGEALL additionally computes weighted average cost across the global pool.+data ReductionMethod = FIFO | LIFO | HIFO | AVERAGE | SPECID+ | FIFOALL | LIFOALL | HIFOALL | AVERAGEALL+ deriving (Show,Read,Eq,Ord,Generic)++data Amount = Amount {+ acommodity :: !CommoditySymbol, -- commodity symbol, or special value "AUTO"+ aquantity :: !Quantity, -- numeric quantity, or zero in case of "AUTO"+ astyle :: !AmountStyle,+ acost :: !(Maybe AmountCost), -- ^ transacted exchange rate - the unit or total cost, in another commodity, used for this amount within its transaction+ acostbasis :: !(Maybe CostBasis) -- ^ the cost basis of an investment lot represented by this amount. Or, a matcher to select such a lot from the available lots.+} deriving (Eq,Ord,Generic,Show)++-- | Types with this class have one or more amounts,+-- which can have display styles applied to them.+class HasAmounts a where+ styleAmounts :: M.Map CommoditySymbol AmountStyle -> a -> a++instance HasAmounts a =>+ HasAmounts [a]+ where styleAmounts styles = map (styleAmounts styles)++instance (HasAmounts a, HasAmounts b) =>+ HasAmounts (a,b)+ where styleAmounts styles (aa,bb) = (styleAmounts styles aa, styleAmounts styles bb)++instance HasAmounts a =>+ HasAmounts (Maybe a)+ where styleAmounts styles = fmap (styleAmounts styles)++-- | hledger's most general amount type.+-- It can contain multiple single-commodity Amounts, each possibly with a transacted cost and/or a lot cost basis attached.+-- Internally it is a map from MixedAmountKey to Amount, for efficiency and so that every mixed amount has a single canonical form.+newtype MixedAmount = Mixed (M.Map MixedAmountKey Amount)+ deriving (Generic,Show)++-- | The key used to group amounts within a MixedAmount: commodity and an optional unit or total transacted cost.+-- Amounts with the same commodity and transacted cost are combined; different transacted costs are kept separate.+-- (Lot cost basis is not part of the key, so not kept separate; subaccounts are used for that.)+data MixedAmountKey+ = MixedAmountKeyNoCost+ !CommoditySymbol -- ^ amount commodity+ | MixedAmountKeyUnitCost+ !CommoditySymbol -- ^ amount commodity+ !CommoditySymbol -- ^ transacted cost commodity+ !Quantity -- ^ transacted cost per unit+ | MixedAmountKeyTotalCost+ !CommoditySymbol -- ^ amount commodity+ !CommoditySymbol -- ^ transacted cost commodity+ deriving (Eq, Generic, Show)++-- | Sort by commodity, then cost commodity (no cost first), then cost type and quantity.+instance Ord MixedAmountKey where+ compare = comparing commodity <> comparing costCommodity <> comparing costDetail+ where+ commodity (MixedAmountKeyNoCost c) = c+ commodity (MixedAmountKeyUnitCost c _ _) = c+ commodity (MixedAmountKeyTotalCost c _) = c++ costCommodity (MixedAmountKeyNoCost _) = Nothing+ costCommodity (MixedAmountKeyUnitCost _ pc _) = Just pc+ costCommodity (MixedAmountKeyTotalCost _ pc) = Just pc++ costDetail (MixedAmountKeyNoCost _) = Nothing+ costDetail (MixedAmountKeyUnitCost _ _ q) = Just (1 :: Int, Just q)+ costDetail (MixedAmountKeyTotalCost _ _) = Just (0, Nothing)++-- | Calculate the key for storing this Amount within a MixedAmount,+-- from its commodity and transacted cost (ignoring cost basis).+mixedAmountKey :: Amount -> MixedAmountKey+mixedAmountKey Amount{acommodity=c, acost} =+ case acost of+ Nothing -> MixedAmountKeyNoCost c+ Just (UnitCost p) -> MixedAmountKeyUnitCost c (acommodity p) (aquantity p)+ Just (TotalCost p) -> MixedAmountKeyTotalCost c (acommodity p)++instance Eq MixedAmount where a == b = maCompare a b == EQ+instance Ord MixedAmount where compare = maCompare++-- | Compare two MixedAmounts, substituting 0 for the quantity of any missing+-- commodities in either.+maCompare :: MixedAmount -> MixedAmount -> Ordering+maCompare (Mixed a) (Mixed b) = go (M.toList a) (M.toList b)+ where+ go xss@((kx,x):xs) yss@((ky,y):ys) = case compare kx ky of+ EQ -> compareQuantities (Just x) (Just y) <> go xs ys+ LT -> compareQuantities (Just x) Nothing <> go xs yss+ GT -> compareQuantities Nothing (Just y) <> go xss ys+ go ((_,x):xs) [] = compareQuantities (Just x) Nothing <> go xs []+ go [] ((_,y):ys) = compareQuantities Nothing (Just y) <> go [] ys+ go [] [] = EQ+ compareQuantities = comparing (maybe 0 aquantity) <> comparing (maybe 0 totalcost)+ totalcost x = case acost x of+ Just (TotalCost p) -> aquantity p+ _ -> 0++data PostingRealness = RealPosting | VirtualPosting | BalancedVirtualPosting+ deriving (Eq,Show,Generic)++type TagName = Text+type TagValue = Text+type Tag = (TagName, TagValue) -- ^ A tag name and (possibly empty) value.+type HiddenTag = Tag -- ^ A tag whose name begins with _.+type DateTag = (TagName, Day)++-- | Add the _ prefix to a normal visible tag's name, making it a hidden tag.+toHiddenTag :: Tag -> HiddenTag+toHiddenTag = first toHiddenTagName++-- | Drop the _ prefix from a hidden tag's name, making it a normal visible tag.+toVisibleTag :: HiddenTag -> Tag+toVisibleTag = first toVisibleTagName++-- | Does this tag name begin with the hidden tag prefix (_) ?+isHiddenTagName :: TagName -> Bool+isHiddenTagName t =+ case T.uncons t of+ Just ('_',_) -> True+ _ -> False++-- | Add the _ prefix to a normal visible tag's name, making it a hidden tag.+toHiddenTagName :: TagName -> TagName+toHiddenTagName = T.cons '_'++-- | Drop the _ prefix from a hidden tag's name, making it a normal visible tag.+toVisibleTagName :: TagName -> TagName+toVisibleTagName = T.drop 1++-- | The status of a transaction or posting, recorded with a status mark+-- (nothing, !, or *). What these mean is ultimately user defined.+data Status = Unmarked | Pending | Cleared+ deriving (Eq,Ord,Bounded,Enum,Generic)++instance Show Status where -- custom show.. bad idea.. don't do it..+ show Unmarked = ""+ show Pending = "!"+ show Cleared = "*"++nullsourcepos :: SourcePos+nullsourcepos = SourcePos "" (mkPos 1) (mkPos 1)++nullsourcepospair :: (SourcePos, SourcePos)+nullsourcepospair = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))++-- | A balance assertion is a declaration about an account's expected balance+-- at a certain point (posting date and parse order). They provide additional+-- error checking and readability to a journal file.+--+-- A balance assignments is an instruction to hledger to adjust an+-- account's balance to a certain amount at a certain point.+--+-- The 'BalanceAssertion' type is used for representing both of these.+--+-- hledger supports multiple kinds of balance assertions/assignments,+-- which differ in whether they refer to a single commodity or all commodities,+-- and the (subaccount-)inclusive or exclusive account balance.+--+data BalanceAssertion = BalanceAssertion {+ baamount :: Amount, -- ^ the expected balance in a particular commodity+ batotal :: Bool, -- ^ disallow additional non-asserted commodities ?+ bainclusive :: Bool, -- ^ include subaccounts when calculating the actual balance ?+ baposition :: SourcePos -- ^ the assertion's file position, for error reporting+ } deriving (Eq,Generic,Show)++data Posting = Posting {+ pdate :: Maybe Day, -- ^ this posting's date, if different from the transaction's+ pdate2 :: Maybe Day, -- ^ this posting's secondary date, if different from the transaction's+ pstatus :: Status,+ paccount :: AccountName,+ pamount :: MixedAmount,+ pcomment :: Text, -- ^ this posting's comment lines, as a single non-indented multi-line string+ preal :: PostingRealness, -- ^ is this a normal balanced posting, or a virtual/unbalanced one ?+ ptags :: [Tag], -- ^ tag names and values, extracted from the posting comment + -- and (after finalisation) the posting account's directive if any+ pbalanceassertion :: Maybe BalanceAssertion, -- ^ an expected balance in the account after this posting,+ -- in a single commodity, excluding subaccounts.+ ptransaction :: Maybe Transaction, -- ^ this posting's parent transaction (co-recursive types).+ -- Tying this knot gets tedious, Maybe makes it easier/optional.+ poriginal :: Maybe Posting -- ^ When this posting has been transformed in some way+ -- (eg its amount or cost was inferred, or the account name was+ -- changed by a pivot or budget report), this references the original+ -- untransformed posting (which will have Nothing in this field).+ } deriving (Generic)++-- The equality test for postings ignores the parent transaction's+-- identity, to avoid recurring ad infinitum.+-- XXX could check that it's Just or Nothing.+instance Eq Posting where+ (==) (Posting a1 b1 c1 d1 e1 f1 g1 h1 i1 _ _) (Posting a2 b2 c2 d2 e2 f2 g2 h2 i2 _ _) = a1==a2 && b1==b2 && c1==c2 && d1==d2 && e1==e2 && f1==f2 && g1==g2 && h1==h2 && i1==i2++-- | Posting's show instance elides the parent transaction so as not to recurse forever.+instance Show Posting where+ show Posting{..} = "PostingPP {" ++ intercalate ", " [+ "pdate=" ++ show (show pdate)+ ,"pdate2=" ++ show (show pdate2)+ ,"pstatus=" ++ show (show pstatus)+ ,"paccount=" ++ show paccount+ ,"pamount=" ++ show pamount+ ,"pcomment=" ++ show pcomment+ ,"preal=" ++ show preal+ ,"ptags=" ++ show ptags+ ,"pbalanceassertion=" ++ show pbalanceassertion+ ,"ptransaction=" ++ show (ptransaction $> "txn")+ ,"poriginal=" ++ show poriginal+ ] ++ "}"++data Transaction = Transaction {+ tindex :: Integer, -- ^ this transaction's 1-based position in the transaction stream, or 0 when not available+ tprecedingcomment :: Text, -- ^ any comment lines immediately preceding this transaction+ tsourcepos :: (SourcePos, SourcePos), -- ^ the file position where the date starts, and where the last posting ends+ tdate :: Day,+ tdate2 :: Maybe Day,+ tstatus :: Status,+ tcode :: Text,+ tdescription :: Text,+ tcomment :: Text, -- ^ this transaction's comment lines, as a single non-indented multi-line string+ ttags :: [Tag], -- ^ tag names and values, extracted from the comment+ tpostings :: [Posting] -- ^ this transaction's postings+ } deriving (Eq,Generic,Show)++-- | A transaction modifier rule. This has a query which matches postings+-- in the journal, and a list of transformations to apply to those+-- postings or their transactions. Currently there is one kind of transformation:+-- the TMPostingRule, which adds a posting ("auto posting") to the transaction,+-- optionally setting its amount to the matched posting's amount multiplied by a constant.+data TransactionModifier = TransactionModifier {+ tmquerytxt :: Text,+ tmpostingrules :: [TMPostingRule]+ } deriving (Eq,Generic,Show)++nulltransactionmodifier = TransactionModifier{+ tmquerytxt = ""+ ,tmpostingrules = []+}++-- | A transaction modifier transformation, which adds an extra posting+-- to the matched posting's transaction.+-- Can be like a regular posting, or can have the tmprIsMultiplier flag set,+-- indicating that it's a multiplier for the matched posting's amount.+data TMPostingRule = TMPostingRule+ { tmprPosting :: Posting+ , tmprIsMultiplier :: Bool+ } deriving (Eq,Generic,Show)++-- | A periodic transaction rule, describing a transaction that recurs.+data PeriodicTransaction = PeriodicTransaction {+ ptperiodexpr :: Text, -- ^ the period expression as written+ ptinterval :: Interval, -- ^ the interval at which this transaction recurs+ ptspan :: DateSpan, -- ^ the (possibly unbounded) period during which this transaction recurs. Contains a whole number of intervals.+ --+ ptsourcepos :: (SourcePos, SourcePos), -- ^ the file position where the period expression starts, and where the last posting ends+ ptstatus :: Status, -- ^ some of Transaction's fields+ ptcode :: Text,+ ptdescription :: Text,+ ptcomment :: Text,+ pttags :: [Tag],+ ptpostings :: [Posting]+ } deriving (Eq,Generic) -- , Show in PeriodicTransaction.hs++nullperiodictransaction = PeriodicTransaction{+ ptperiodexpr = ""+ ,ptinterval = def+ ,ptspan = def+ ,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 1) (mkPos 1))+ ,ptstatus = Unmarked+ ,ptcode = ""+ ,ptdescription = ""+ ,ptcomment = ""+ ,pttags = []+ ,ptpostings = []+}++-- | Which rows an assert directive's query must match: none, or at least one.+data AssertQuantifier = AssertNone | AssertSome deriving (Eq,Show,Generic)++-- | An assert directive: a standing rule, a query which must match no rows or some rows+-- of the equivalent balance report, over the whole journal or in every period.+-- The query is kept as text, since Hledger.Query depends on this module;+-- it is validated when parsed, and parsed again when checked.+data AssertDirective = AssertDirective {+ adQuantifier :: AssertQuantifier+ ,adPeriod :: Maybe (Interval, DateSpan) -- ^ the period expression, if any: the rule is checked in each of its periods+ ,adPeriodText :: Text -- ^ the period expression as written, or empty+ ,adQueryText :: Text -- ^ the query as written+ ,adSkips :: [DateSpan] -- ^ the periods of its skip subdirectives, whose checks are skipped+ ,adSourceText :: Text -- ^ the directive's lines as written (the assert line and any skip lines), for error excerpts+ ,adSourcePos :: SourcePos+ } deriving (Eq,Generic) -- , Show in Journal.hs++data TimeclockCode = SetBalance | SetRequiredHours | In | Out | FinalOut deriving (Eq,Ord,Generic)++data TimeclockEntry = TimeclockEntry {+ tlsourcepos :: SourcePos,+ tlcode :: TimeclockCode,+ tldatetime :: LocalTime,+ tlaccount :: AccountName,+ tldescription :: Text,+ tlcomment :: Text,+ tltags :: [Tag]+ } deriving (Eq,Ord,Generic)++-- | A market price declaration made by the journal format's P directive.+-- It declares two things: a historical exchange rate between two commodities,+-- and an amount display style for the second commodity.+data PriceDirective = PriceDirective {+ pdsourcepos :: SourcePos+ ,pddate :: Day+ ,pdcommodity :: CommoditySymbol+ ,pdamount :: Amount+ } deriving (Eq,Ord,Generic,Show)++-- | A historical market price (exchange rate) from one commodity to another.+-- A more concise form of a PriceDirective, without the amount display info.+data MarketPrice = MarketPrice {+ mpdate :: Day -- ^ Date on which this price becomes effective.+ ,mpfrom :: CommoditySymbol -- ^ The commodity being converted from.+ ,mpto :: CommoditySymbol -- ^ The commodity being converted to.+ ,mprate :: Quantity -- ^ One unit of the "from" commodity is worth this quantity of the "to" commodity.+ } deriving (Eq,Ord,Generic, Show)++showMarketPrice MarketPrice{..} = unwords [show mpdate, T.unpack mpfrom <> ">" <> T.unpack mpto, show mprate]+showMarketPrices = intercalate "\n" . map ((' ':).showMarketPrice) . sortBy (comparing mpdate)++-- additional valuation-related types in Valuation.hs++-- | A source position calculated during parsing, with the parser's offset and+-- remaining input at that point. Kept in the parse state, so that later+-- positions can be calculated cheaply from it (see Hledger.Read.Common.getSourcePos').+data ParsePos = ParsePos {+ ppSourcePos :: SourcePos+ ,ppOffset :: Int+ ,ppInput :: Text+ } deriving (Eq,Generic,Show)++-- | Counts of the journal entries which the journal parser's fast path (see+-- Hledger.Read.JournalReader) accepted or declined, and the reasons for declining.+-- Collected only with --debug, and reported after parsing.+data FastPathStats = FastPathStats {+ fpsTxnsFast :: Int -- ^ transactions parsed by the fast path+ ,fpsTxnsGeneral :: Int -- ^ transactions it declined, parsed by the general parser+ ,fpsPricesFast :: Int -- ^ price directives parsed by the fast path+ ,fpsPricesGeneral :: Int -- ^ price directives it declined+ ,fpsDeclines :: M.Map Text Int -- ^ the number of declines for each reason+ } deriving (Eq,Generic,Show)++instance Semigroup FastPathStats where+ FastPathStats a b c d e <> FastPathStats a' b' c' d' e' =+ FastPathStats (a + a') (b + b') (c + c') (d + d') (M.unionWith (+) e e')++instance Monoid FastPathStats where+ mempty = FastPathStats 0 0 0 0 M.empty++-- | A journal, containing general ledger transactions; also directives and various other things.+-- This is hledger's main data model.+--+-- During parsing, it is used as the type alias "ParsedJournal".+-- The jparse* fields are mainly used during parsing and included here for convenience.+-- The list fields described as "in parse order" are usually reversed for efficiency during parsing.+-- After parsing, "journalFinalise" converts ParsedJournal to a finalised "Journal",+-- which has all lists correctly ordered, and much data inference and validation applied.+--+data Journal = Journal {+ -- parsing-related state+ jparsedefaultyear :: Maybe Year -- ^ the current default year, specified by the most recent Y or apply year directive (or current date)+ ,jparseapplyyears :: [Maybe Year] -- ^ the default years that were in effect before each open apply year directive, innermost first.+ -- end apply year restores (and removes) the first one.+ ,jparsedefaultcommodity :: Maybe (CommoditySymbol,AmountStyle) -- ^ the current default commodity and its format, specified by the most recent D directive+ ,jparsedecimalmark :: Maybe DecimalMark -- ^ the character to always parse as decimal point, if set by CsvReader's decimal-mark (or a future journal directive)+ ,jparseparentaccounts :: [AccountName] -- ^ the current stack of parent account names, specified by apply account directives+ ,jparsealiases :: [AccountAlias] -- ^ the current account name aliases in effect from alias directives or alias: tags, most recent first.+ -- These are applied to account names as written, before any parent account is added (apply account); and end aliases clears them.+ ,jparseoptaliases :: [AccountAlias] -- ^ the account name aliases from --alias options, in command line order.+ -- These are applied to full account names, after a parent account is added; and end aliases does not clear them.+ -- Hence they are kept separate from jparsealiases. See Hledger.Read.Common.accountNameApplyModifiers.+ -- ,jparsetransactioncount :: Integer -- ^ the current count of transactions parsed so far (only journal format txns, currently)+ ,jparsetimeclockentries :: [TimeclockEntry] -- ^ timeclock sessions which have not been clocked out+ ,jparseincludefilestack :: [(FilePath, FilePath)] -- ^ (absolute path, canonical path) of included files, most recent first+ ,jparsepos :: Maybe ParsePos -- ^ the most recently calculated source position, if any, from which later ones are calculated cheaply+ ,jparseamountstyles :: S.Set AmountStyle -- ^ the distinct amount styles parsed so far, which parsed amounts share to save memory+ ,jparsetexts :: S.Set Text -- ^ the distinct account names and commodity symbols parsed so far, which parsed items share to save memory+ ,jparsefastpathstats :: FastPathStats -- ^ how many entries the parser's fast path has accepted or declined so far, and why (with --debug)+-- principal data+ ,jdeclaredpayees :: [(Payee,PayeeDeclarationInfo)] -- ^ Payees declared by payee directives, in parse order.+ ,jdeclaredtags :: [(TagName,TagDeclarationInfo)] -- ^ Tags declared by tag directives, in parse order.+ ,jdeclaredaccounts :: [(AccountName,AccountDeclarationInfo)] -- ^ Accounts declared by account directives, in parse order.+ ,jdeclaredaccounttags :: M.Map AccountName [Tag] -- ^ Accounts which were declared with tags, and those tags.+ ,jdeclaredaccounttypes :: M.Map AccountType [AccountName] -- ^ Accounts which were declared with a type: tag, grouped by the type.+ ,jaccounttypes :: M.Map AccountName AccountType -- ^ All the account types known, from account declarations or account names or parent accounts.+ ,jdeclaredcommodities :: M.Map CommoditySymbol Commodity -- ^ Commodities (and their display styles) declared by commodity directives, in parse order.+ ,jdeclaredcommoditytags :: M.Map CommoditySymbol [Tag] -- ^ Commodities which were declared with tags, and those tags.+ ,jinferredcommoditystyles :: M.Map CommoditySymbol AmountStyle -- ^ Commodity display styles inferred from amounts in the journal.+ ,jglobalcommoditystyles :: M.Map CommoditySymbol AmountStyle -- ^ Commodity display styles declared by command line options (sometimes augmented, see the import command).+ ,jpricedirectives :: [PriceDirective] -- ^ P (market price) directives in the journal, in parse order.+ ,jinferredmarketprices :: [MarketPrice] -- ^ Market prices inferred from transactions in the journal, in parse order.+ ,jtxnmodifiers :: [TransactionModifier] -- ^ Auto posting rules declared in the journal.+ ,jperiodictxns :: [PeriodicTransaction] -- ^ Periodic transaction rules declared in the journal.+ ,jasserts :: [AssertDirective] -- ^ Assert directives declared in the journal, in parse order.+ ,jtxns :: [Transaction] -- ^ Transactions recorded in the journal. The important bit.+ ,jitems :: [JournalItem] -- ^ All top-level items of the journal file(s), in parse order,+ -- including directives, comment lines and blank lines as written.+ -- Used to reproduce the journal (print --export).+ ,jfiles :: [JournalFile] -- ^ the main and any included journal files. The main file is first,+ -- followed by any included files in the order encountered.+ ,jauxfiles :: [(FilePath, [FilePath])] -- ^ for each data file (in jfiles) whose reading involved other files,+ -- its path and the paths of those other files: for a CSV file,+ -- its rules file and any rules files that includes; for a rules file,+ -- any rules files it includes, and the data file it read, if any.+ -- Shown by the files command, and watched for changes, like jfiles,+ -- when reloading.+ ,jlastreadtime :: POSIXTime -- ^ when this journal was last read from its file(s)+ -- NOTE: after adding new fields, eg involving account names, consider updating+ -- the Anon instance in Hleger.Cli.Anon+ } deriving (Eq, Generic)++-- | One top-level item of a journal file, recorded in file order so that+-- the file can be reproduced (by print --export). Transactions are+-- represented by a placeholder; the transaction itself is in jtxns.+-- Text fields hold verbatim source text, including the trailing newline.+-- Blank lines are recorded only as separators (one JIBlank for each run of them),+-- since print --export normalises blank lines.+-- Fields are strict so that recording items doesn't retain parse-time thunks.+data JournalItem+ = JITransaction !SourcePos -- ^ a transaction: the one in jtxns whose tsourcepos starts here+ | JIComment !Text -- ^ a single top-level comment line (starting with ; # or *)+ | JICommentBlock !Text -- ^ a comment ... end comment block+ | JIDirective !Text -- ^ a directive which should be reproduced when exporting+ -- (including P, ~ and = rules), without any ! or @ prefix+ | JINonExportedDirective !Text -- ^ a directive which should not be reproduced when exporting:+ -- apply account, alias and their end forms, whose effect is+ -- already applied to the data; and the Ledger directives hledger ignores+ | JIInclude !Text -- ^ an include directive line; the included file's items follow it+ | JIBlank -- ^ one or more blank lines+ deriving (Eq, Generic, Show)++-- | One of the files a journal was read from.+data JournalFile = JournalFile {+ jfpath :: FilePath -- ^ the file's path. TODO: FilePath is a sloppy type here, don't assume it's a+ -- real file; values like "" or "-" can be seen+ ,jftext :: Text -- ^ the file's raw text+ ,jfdepth :: Int -- ^ the file's include depth: 0 for a main file, 1 for a file it includes, and so on+ } deriving (Eq, Generic, Show)++-- | A journal in the process of being parsed, not yet finalised.+-- The data is partial, and list fields are in reverse order.+type ParsedJournal = Journal++-- | One of the standard *-separated value file types known by hledger,+data SepFormat + = Csv -- comma-separated+ | Tsv -- tab-separated+ | Ssv -- semicolon-separated+ deriving (Eq, Ord)++-- XXX A little confusion, this is also used to name readers in splitReaderPrefix.+-- readers, input formats, and output formats overlap but are distinct concepts.+-- | The id of a data format understood by hledger, eg @journal@ or @csv@.+-- The --output-format option selects one of these for output.+data StorageFormat + = Rules + | Journal' + | Ledger' + | Timeclock + | Timedot + | Sep SepFormat + deriving (Eq, Ord)++instance Show SepFormat where+ show Csv = "csv"+ show Ssv = "ssv"+ show Tsv = "tsv"++instance Show StorageFormat where+ show Rules = "rules"+ show Journal' = "journal"+ show Ledger' = "ledger"+ show Timeclock = "timeclock"+ show Timedot = "timedot"+ show (Sep Csv) = "csv"+ show (Sep Ssv) = "ssv"+ show (Sep Tsv) = "tsv"++-- | Extra information found in a payee directive.+data PayeeDeclarationInfo = PayeeDeclarationInfo {+ pdicomment :: Text -- ^ any comment lines following the payee directive+ ,pditags :: [Tag] -- ^ tags extracted from the comment, if any+} deriving (Eq,Show,Generic)++nullpayeedeclarationinfo = PayeeDeclarationInfo {+ pdicomment = ""+ ,pditags = []+}++-- | Extra information found in a tag directive.+newtype TagDeclarationInfo = TagDeclarationInfo {+ tdicomment :: Text -- ^ any comment lines following the tag directive. No tags allowed here.+} deriving (Eq,Show,Generic)++nulltagdeclarationinfo = TagDeclarationInfo {+ tdicomment = ""+}++-- | Extra information about an account that can be derived from+-- its account directive (and the other account directives).+data AccountDeclarationInfo = AccountDeclarationInfo {+ adicomment :: Text -- ^ any comment lines following an account directive for this account+ ,aditags :: [Tag] -- ^ tags extracted from the account comment, if any+ ,adideclarationorder :: Int -- ^ the order in which this account was declared,+ -- relative to other account declarations, during parsing (1..)+ ,adisourcepos :: SourcePos -- ^ source file and position+} deriving (Eq,Show,Generic)++nullaccountdeclarationinfo = AccountDeclarationInfo {+ adicomment = ""+ ,aditags = []+ ,adideclarationorder = 0+ ,adisourcepos = SourcePos "" (mkPos 1) (mkPos 1)+}++-- | An account within a hierarchy, with references to its parent+-- and subaccounts if any, and with per-report-period data of type 'a'.+-- Only the name is required; the other fields may or may not be present.+data Account a = Account {+ aname :: AccountName -- ^ full name+ ,adeclarationinfo :: Maybe AccountDeclarationInfo -- ^ optional extra info from account directives+ -- relationships in the tree+ ,asubs :: [Account a] -- ^ subaccounts+ ,aparent :: Maybe (Account a) -- ^ parent account+ ,aboring :: Bool -- ^ used in some reports to indicate elidable accounts+ ,adata :: PeriodData a -- ^ associated data per report period+ } deriving (Generic, Functor)++-- | A general container for storing data values associated with zero or more+-- contiguous report (sub)periods, and with the (open ended) pre-report period.+-- The report periods are typically all the same length, but need not be.+--+-- Report periods are represented only by their start dates, used as the keys of a Map.+data PeriodData a = PeriodData {+ pdpre :: a -- ^ data for the period before the report+ ,pdperiods :: M.Map Day a -- ^ data for each period within the report+ } deriving (Eq, Ord, Functor, Generic)++-- | Data that's useful in "balance" reports:+-- subaccount-exclusive and -inclusive amounts,+-- typically representing either a balance change or an end balance;+-- and a count of postings.+data BalanceData = BalanceData {+ bdexcludingsubs :: MixedAmount -- ^ balance data excluding subaccounts+ ,bdincludingsubs :: MixedAmount -- ^ balance data including subaccounts+ ,bdnumpostings :: Int -- ^ the number of postings+ } deriving (Eq, Generic)++-- | Whether an account's balance is normally a positive number (in+-- accounting terms, a debit balance) or a negative number (credit balance).+-- Assets and expenses are normally positive (debit), while liabilities, equity+-- and income are normally negative (credit).+-- https://en.wikipedia.org/wiki/Normal_balance+data NormalSign = NormallyPositive | NormallyNegative deriving (Show, Eq)++-- | A Ledger has the journal it derives from, and the accounts+-- derived from that. Accounts are accessible both list-wise and+-- tree-wise, since each one knows its parent and subs; the first+-- account is the root of the tree and always exists.+data Ledger = Ledger {+ ljournal :: Journal+ ,laccounts :: [Account BalanceData]+ } deriving (Generic)++instance NFData AccountAlias+instance NFData AccountDeclarationInfo+instance NFData AccountType+instance NFData Amount+instance NFData AmountCost+instance NFData AmountPrecision+instance NFData AmountStyle+instance NFData AssertDirective+instance NFData AssertQuantifier+instance NFData BalanceAssertion+instance NFData Commodity+instance NFData CostBasis+instance NFData DateSpan+instance NFData DigitGroupStyle+instance NFData EFDay+instance NFData FastPathStats+instance NFData Interval+instance NFData Journal+instance NFData JournalFile+instance NFData JournalItem+instance NFData ParsePos+instance NFData LotId+instance NFData MarketPrice+instance NFData ReductionMethod+instance NFData MixedAmount+instance NFData MixedAmountKey+instance NFData Rounding+instance NFData PayeeDeclarationInfo+instance NFData PeriodicTransaction+instance NFData PostingRealness+instance NFData PriceDirective+instance NFData Side+instance NFData Status+instance NFData TagDeclarationInfo+instance NFData TimeclockCode+instance NFData TimeclockEntry+instance NFData TMPostingRule+instance NFData Transaction+instance NFData TransactionModifier++instance NFData Posting where+ -- Do not call rnf on the parent transaction to avoid recursive loops+ rnf (Posting d d2 s n a c t ta b mt op) =+ rnf d `seq` rnf d2 `seq` rnf s `seq` rnf n `seq` rnf a `seq` rnf c `seq` rnf t `seq` rnf ta `seq` rnf b `seq` mt `seq` rnf op `seq` ()
+ Hledger/Data/Valuation.hs view
@@ -0,0 +1,691 @@+{-|++Convert amounts to some related value in various ways. This involves+looking up historical market prices (exchange rates) between commodities.++-}++{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE DeriveGeneric #-}++module Hledger.Data.Valuation (+ ConversionOp(..)+ ,ValuationType(..)+ ,PriceOracle+ ,journalPriceOracle+ ,journalAliasPriceDirectives+ ,mixedAmountToCost+ ,mixedAmountApplyValuation+ ,mixedAmountValueAtDate+ ,amountValueAtDate+ ,mixedAmountApplyGain+ ,mixedAmountGainAtDate+ ,marketPriceReverse+ ,priceDirectiveToMarketPrice+ ,amountPriceDirectiveFromCost+ ,valuationTypeValuationCommodity+ -- ,priceLookup+ ,tests_Valuation+)+where++import Control.Applicative ((<|>))+import Data.Function ((&))+import Data.List (partition, intercalate, sortBy)+import Data.Map qualified as M+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Time.Calendar (Day, fromGregorian)+import Data.Maybe (fromMaybe, mapMaybe)+import Data.MemoUgly (memo)+import GHC.Generics (Generic)+import Safe (headMay, lastMay)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.Amount+import Hledger.Data.Dates (nulldate)+import Text.Printf (printf)+import Data.Decimal (decimalPlaces, roundTo, Decimal)+import Data.Word (Word8)+++------------------------------------------------------------------------------+-- Types++-- | Which cost conversion to perform on amounts, if any:+-- to cost basis where known, otherwise transacted cost (-B/--value=cost);+-- or to transacted cost always (--value=transacted).+-- (There was also an "infer equity postings" operation, but that is now done+-- earlier, in journal finalisation.)+data ConversionOp = NoConversionOp | ToCost | ToTransactedCost+ deriving (Show,Eq)++-- | What kind of value conversion should be done on amounts ?+-- CLI: --value=then|end|now|DATE[,COMM]+data ValuationType =+ AtThen (Maybe CommoditySymbol) -- ^ convert to default or given valuation commodity, using market prices at each posting's date+ | AtEnd (Maybe CommoditySymbol) -- ^ convert to default or given valuation commodity, using market prices at period end(s)+ | AtNow (Maybe CommoditySymbol) -- ^ convert to default or given valuation commodity, using current market prices+ | AtDate Day (Maybe CommoditySymbol) -- ^ convert to default or given valuation commodity, using market prices on some date+ deriving (Show,Eq)++valuationTypeValuationCommodity :: ValuationType -> Maybe CommoditySymbol+valuationTypeValuationCommodity = \case+ AtThen (Just c) -> Just c+ AtEnd (Just c) -> Just c+ AtNow (Just c) -> Just c+ AtDate _ (Just c) -> Just c+ _ -> Nothing++-- | A price oracle is a magic memoising function that efficiently+-- looks up market prices (exchange rates) from one commodity to+-- another (or if unspecified, to a default valuation commodity) on a+-- given date.+type PriceOracle = (Day, CommoditySymbol, Maybe CommoditySymbol) -> Maybe (CommoditySymbol, Quantity)++-- | An index of market prices for efficient lookup by commodity pair and date.+-- Maps each (from, to) commodity pair to a Map from date to the effective price,+-- where declared prices take precedence over inferred prices on the same day.+-- This allows O(log n) lookup per pair via M.lookupLE.+type PriceIndex = M.Map (CommoditySymbol, CommoditySymbol) (M.Map Day MarketPrice)++-- | Build a price index from declared and inferred market prices.+-- This is O(n log n) but done only once, enabling fast lookups later.+buildPriceIndex :: [MarketPrice] -> [MarketPrice] -> PriceIndex+buildPriceIndex declaredprices inferredprices =+ let+ -- Label each price with precedence (declared=True > inferred=False) and parse order+ declaredprices' = [(mpdate p, True, i, p) | (i, p) <- zip [1..] declaredprices]+ inferredprices' = [(mpdate p, False, i, p) | (i, p) <- zip [1..] inferredprices]+ allprices = declaredprices' ++ inferredprices'+ -- Group by commodity pair+ grouped = M.fromListWith (++)+ [((mpfrom p, mpto p), [(d, prec, order, p)]) | (d, prec, order, p) <- allprices]+ -- Build inner Map: sort ascending by (date, prec, order), then M.fromList+ -- keeps the last entry per date (highest precedence/parseorder wins)+ buildInnerMap prices =+ prices+ & sortBy compare+ & map (\(d, _, _, p) -> (d, p))+ & M.fromList+ in+ M.map buildInnerMap grouped++-- | Look up effective prices for all commodity pairs at a given date using the index.+-- Returns at most one price per commodity pair: the latest price on or before the date.+-- O(pairs × log n) where n is the number of prices per pair.+lookupEffectivePricesFromIndex :: Day -> PriceIndex -> [MarketPrice]+lookupEffectivePricesFromIndex d idx =+ mapMaybe (fmap snd . M.lookupLE d) (M.elems idx)++-- | Index for default valuation commodity lookup.+-- Maps source commodity to a map of (date -> destination), supporting O(log n) lookup+-- of the latest destination commodity on or before any given date.+type DefaultValuationIndex = M.Map CommoditySymbol (M.Map Day CommoditySymbol)++-- | Build an index for default valuation commodity lookup from a list of market prices.+buildDefaultValuationIndex :: [MarketPrice] -> DefaultValuationIndex+buildDefaultValuationIndex prices =+ let+ -- Label with parse order+ labeled = [(mpfrom p, mpdate p, i, mpto p) | (i, p) <- zip [1..] prices]+ -- Group by source commodity+ grouped = M.fromListWith (++) [(from, [(d, ord, to)]) | (from, d, ord, to) <- labeled]+ -- Build inner Map: sort by (date, parseorder), then M.fromList keeps last (highest parseorder per date)+ buildInnerMap entries = M.fromList [(d, to) | (d, _, to) <- sortBy compare entries]+ in+ M.map buildInnerMap grouped++-- | Combined indexes for efficient price lookup.+data PriceIndexes = PriceIndexes+ { piForward :: !PriceIndex -- ^ Index for forward prices (declared + inferred)+ , piDeclaredDefault :: !DefaultValuationIndex -- ^ Index for declared prices (for default valuation)+ , piInferredDefault :: !DefaultValuationIndex -- ^ Index for inferred prices (fallback for default valuation)+ }++-- | Build all price indexes from declared and inferred market prices, and commodity alias rates (see 'journalAliasPrices').+-- An alias rate is used only between two commodities which have no market prices between them, in either direction,+-- and never to choose a default valuation commodity.+-- This is O(n log n) but done only once.+buildPriceIndexes :: [MarketPrice] -> [MarketPrice] -> [MarketPrice] -> PriceIndexes+buildPriceIndexes declaredprices inferredprices aliasprices = PriceIndexes+ { piForward = addAliasPrices $ buildPriceIndex declaredprices inferredprices+ , piDeclaredDefault = buildDefaultValuationIndex declaredprices+ , piInferredDefault = buildDefaultValuationIndex inferredprices+ }+ where+ addAliasPrices idx = M.union idx $ M.fromList+ [ ((f, t), M.singleton (mpdate p) p)+ | p@MarketPrice{mpfrom=f, mpto=t} <- aliasprices+ , not $ M.member (f, t) idx, not $ M.member (t, f) idx ]++-- | Look up default valuation commodities for all source commodities at a given date.+-- Fallback logic: declared at date d, then declared at any date, then inferred at date d.+lookupDefaultValuations :: Day -> PriceIndexes -> M.Map CommoditySymbol CommoditySymbol+lookupDefaultValuations d PriceIndexes{..} =+ fromMaybe fallback (tryDeclaredAtDate <|> tryDeclaredLatest)+ where+ nonEmpty m = if M.null m then Nothing else Just m++ tryDeclaredAtDate = nonEmpty $ lookupDefaults (Just d) piDeclaredDefault+ tryDeclaredLatest = nonEmpty $ lookupDefaults Nothing piDeclaredDefault+ fallback = lookupDefaults (Just d) piInferredDefault++ lookupDefaults mdate = M.mapMaybe $ \innerMap ->+ case mdate of+ Nothing -> snd <$> M.lookupMax innerMap+ Just dt -> snd <$> M.lookupLE dt innerMap++-- | Generate a price oracle (memoising price lookup function) from a+-- journal's directive-declared and transaction-inferred market+-- prices. For best performance, generate this only once per journal,+-- reusing it across reports if there are more than one, as+-- compoundBalanceCommand does.+-- The boolean argument is whether to infer market prices from+-- transactions or not.+--+-- Commodity aliases are also used, as fixed exchange rates (see 'buildPriceIndexes'),+-- but only when no conversion can be found with market prices alone;+-- so they can't change a valuation which market prices provide (eg one declared in another file tree).+-- So an alias can be the valuation commodity,+-- and amounts left in an alias (by a file which didn't declare it) can be valued.+journalPriceOracle :: Bool -> Journal -> PriceOracle+journalPriceOracle infer j@Journal{jpricedirectives, jinferredmarketprices} =+ let+ declaredprices = map priceDirectiveToMarketPrice jpricedirectives+ inferredprices =+ (if infer then jinferredmarketprices else [])+ & dbg2Msg ("use prices inferred from costs? " <> if infer then "yes" else "no")+ -- Build indexes once for all lookups+ oracleWith extraprices = memo $ uncurry3 $ priceLookup $ memo $ makePriceGraph $+ buildPriceIndexes declaredprices inferredprices extraprices+ (ambiguousaliases, aliasrates) = journalAliasPriceDirectivesChecked j+ aliasprices = map priceDirectiveToMarketPrice aliasrates+ marketoracle = oracleWith []+ aliasoracle = oracleWith aliasprices+ -- Alias rates are never default valuation destinations, so they are tried only when converting to a given commodity.+ -- If that is to or from an alias which file trees declared differently, it's an error.+ withaliases k@(_, from, Just to) = marketoracle k <|>+ case mapMaybe (`M.lookup` ambiguousaliases) [from, to] of+ pds:_ -> error' $ ambiguousAliasError pds -- PARTIAL: an alias declared differently by different files can't be used+ [] -> dbg2Msg (aliasmsg k) (aliasoracle k)+ withaliases k = marketoracle k+ -- at --debug=2 +, show when alias rates are tried, and where they were declared+ aliasmsg (d, from, mto) =+ printf "no market price found from %s to %s on %s, trying commodity alias rates:\n%s"+ (showCommoditySymbol from) (maybe "" showCommoditySymbol mto) (show d)+ (intercalate "\n" [printf " %s>%s %s (alias declared at %s)" f (acommodity a) (show $ aquantity a) (sourcePosFileLine pos)+ | PriceDirective{pdcommodity=f, pdamount=a, pdsourcepos=pos} <- aliasrates] :: String)+ in+ if null aliasprices && M.null ambiguousaliases then marketoracle else memo withaliases++-- | Like 'journalAliasPriceDirectives', but separates out the aliases which are declared differently+-- (as an alias of a different commodity, or with a different quantity), which can happen when file trees are combined.+-- These are returned in a map, from each such alias to its different declarations.+journalAliasPriceDirectivesChecked :: Journal -> (M.Map CommoditySymbol [PriceDirective], [PriceDirective])+journalAliasPriceDirectivesChecked j = (ambiguous, filter (not . (`M.member` ambiguous) . aliasOf) pds)+ where+ pds = journalAliasPriceDirectives j+ aliasOf = acommodity . pdamount+ ambiguous = M.filter ((>1) . length) $ M.fromListWith (flip (++)) [(aliasOf pd, [pd]) | pd <- pds]++-- | An error message for using an alias with these different declarations.+ambiguousAliasError :: [PriceDirective] -> String+ambiguousAliasError pds = unlines $+ [printf "commodity alias %s is declared differently by different files, so it can't be used for valuation:" alias]+ <> [printf "%s: commodity %s ; alias: %s %s" (sourcePosFileLine pdsourcepos) (showCommoditySymbol pdcommodity) (show $ aquantity pdamount) alias+ | PriceDirective{..} <- pds]+ <> ["To use it, make these declarations agree; or use a different alias in one of them."]+ where alias = maybe "" (T.unpack . showCommoditySymbol . acommodity . pdamount) $ headMay pds++-- | A journal's commodity aliases, as fixed exchange rates: price directives dated 'nulldate',+-- saying that one unit of a commodity is worth the alias's quantity of the alias (as written), at all dates.+-- Each has the source position of the commodity directive which declared the alias.+journalAliasPriceDirectives :: Journal -> [PriceDirective]+journalAliasPriceDirectives Journal{jdeclaredcommodities} =+ [ PriceDirective{pdsourcepos=pos, pddate=nulldate, pdcommodity=csymbol c, pdamount=a}+ | c <- M.elems jdeclaredcommodities, (a, pos) <- caliases c ]++priceDirectiveToMarketPrice :: PriceDirective -> MarketPrice+priceDirectiveToMarketPrice PriceDirective{..} =+ MarketPrice{ mpdate = pddate+ , mpfrom = pdcommodity+ , mpto = acommodity pdamount+ , mprate = aquantity pdamount+ }++-- | Infer a market price from the given amount and its cost (if any),+-- and make a corresponding price directive on the given date.+-- The price's display precision will be set to show all significant+-- decimal digits; or if they seem to be infinite, defaultPrecisionLimit.+amountPriceDirectiveFromCost :: Day -> Amount -> Maybe PriceDirective+amountPriceDirectiveFromCost d amt@Amount{acommodity=fromcomm, aquantity=n} = case acost amt of+ Just (UnitCost u) -> Just $ pd{pdamount=u}+ Just (TotalCost t) | n /= 0 -> Just $ pd{pdamount=u}+ where u = amountSetFullPrecisionUpTo Nothing $ divideAmount n t+ _ -> Nothing+ where+ pd = PriceDirective{pdsourcepos=nullsourcepos, pddate=d, pdcommodity=fromcomm, pdamount=nullamt}++------------------------------------------------------------------------------+-- Converting things to value++-- | Convert all component amounts to cost/selling price if requested, and style them.+mixedAmountToCost :: M.Map CommoditySymbol AmountStyle -> ConversionOp -> MixedAmount -> MixedAmount+mixedAmountToCost styles cost = mapMixedAmount (amountToCost styles cost)++-- | Apply a specified valuation to this mixed amount, using the+-- provided price oracle, commodity styles, and reference dates.+-- See amountApplyValuation.+mixedAmountApplyValuation :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount+mixedAmountApplyValuation priceoracle styles periodlast today postingdate v =+ mapMixedAmount (amountApplyValuation priceoracle styles periodlast today postingdate v)++-- | Convert an Amount to its cost if requested, and style it appropriately.+amountToCost :: M.Map CommoditySymbol AmountStyle -> ConversionOp -> Amount -> Amount+amountToCost styles ToCost = styleAmounts styles . amountCostBasis+amountToCost styles ToTransactedCost = styleAmounts styles . amountCost+amountToCost _ NoConversionOp = id++-- | Apply a specified valuation to this amount, using the provided+-- price oracle, and reference dates. Also fix up its display style+-- using the provided commodity styles.+--+-- When the valuation requires converting to another commodity, a+-- valuation (conversion) date is chosen based on the valuation type+-- and the provided reference dates. It will be one of:+--+-- - the date of the posting itself (--value=then)+--+-- - the provided "period end" date - this is typically the last day+-- of a subperiod (--value=end with a multi-period report), or of+-- the specified report period or the journal (--value=end with a+-- single-period report).+--+-- - the provided "today" date (--value=now).+--+-- - a fixed date specified by the ValuationType itself+-- (--value=DATE).+--+-- This is all a bit complicated. See the reference doc at+-- https://hledger.org/hledger.html#effect-of-valuation-on-reports+-- (hledger_options.m4.md "Effect of valuation on reports"), and #1083.+--+amountApplyValuation :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> Amount -> Amount+amountApplyValuation priceoracle styles periodlast today postingdate v a =+ case v of+ AtThen mc -> amountValueAtDate priceoracle styles mc postingdate a+ AtEnd mc -> amountValueAtDate priceoracle styles mc periodlast a+ AtNow mc -> amountValueAtDate priceoracle styles mc today a+ AtDate d mc -> amountValueAtDate priceoracle styles mc d a++-- | Find the market value of each component amount in the given+-- commodity, or its default valuation commodity, at the given+-- valuation date, using the given market price oracle.+-- When market prices available on that date are not sufficient to+-- calculate the value, amounts are left unchanged.+mixedAmountValueAtDate :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount+mixedAmountValueAtDate priceoracle styles mc d = mapMixedAmount (amountValueAtDate priceoracle styles mc d)++-- | Find the market value of this amount in the given valuation+-- commodity if any, otherwise the default valuation commodity, at the+-- given valuation date. (The default valuation commodity is the+-- commodity of the latest applicable market price before the+-- valuation date.)+--+-- The returned amount will have its commodity's canonical style applied,+-- (with soft display rounding).+--+-- If the market prices available on that date are not sufficient to+-- calculate this value, the amount is left unchanged.+--+amountValueAtDate :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> Amount -> Amount+amountValueAtDate priceoracle styles mto d a =+ let lbl = lbl_ "amountValueAtDate" in+ case priceoracle (d, acommodity a, mto) of+ Nothing -> a+ Just (comm, rate) ->+ nullamt{acommodity=comm, aquantity=multiplyQuantities rate (aquantity a)}++ -- Manage style and precision of the new amount. Initially:+ -- rate is a Decimal with the internal precision of the original market price declaration.+ -- aquantity is a Decimal with a's internal precision.+ -- The calculated value's internal precision may be different from these.+ -- Its display precision will be that of nullamt (0).+ -- Now apply the standard display style for comm (if there is one)+ & styleAmounts styles+ -- set the display precision to match the internal precision (showing all digits),+ -- unnormalised (don't strip trailing zeros);+ -- but if it looks like an infinite decimal, limit the precision to 8.+ & amountSetFullPrecisionUpTo Nothing+ & dbg9With (lbl "calculated value".showAmount)++-- | Calculate the gain of each component amount, that is the difference+-- between the valued amount and the value of the cost basis (see+-- mixedAmountApplyValuation).+--+-- Note: the cost subtracted here is the sum of every contributing posting's+-- cost basis where known (lot postings), else transacted cost, regardless of+-- direction. (Summing postings merges amounts and can drop their bases, so+-- for --gain reports, lot postings' transacted costs are first replaced by+-- their basis costs; see Hledger.Cli.Utils.journalPrepareLotDetail.)+-- For a non-lot disposal posting recording its sale price with @,+-- the negative quantity flips its cost contribution from acquisition cost to+-- negated sale proceeds, so the result accumulates realised gain alongside+-- any unrealised gain on remaining units. In other words, with bare @ this+-- reports total gain since inception; with lot tracking, the unrealised gain+-- on the remaining units.+--+-- If the commodity we are valuing in is not the same as the commodity of the+-- cost, this will value the cost at the same date as the primary amount. This+-- may not be what you want; for example you may want the cost valued at the+-- posting date. If so, let us know and we can change this behaviour.+mixedAmountApplyGain :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount+mixedAmountApplyGain priceoracle styles periodlast today postingdate v ma =+ mixedAmountApplyValuation priceoracle styles periodlast today postingdate v $ ma `maMinus` mixedAmountCostBasis ma++-- | Calculate the gain of each component amount, that is the+-- difference between the valued amount and the value of the cost basis.+--+-- If the commodity we are valuing in is not the same as the commodity of the+-- cost, this will value the cost at the same date as the primary amount. This+-- may not be what you want; for example you may want the cost valued at the+-- posting date. If so, let us know and we can change this behaviour.+mixedAmountGainAtDate :: PriceOracle -> M.Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount+mixedAmountGainAtDate priceoracle styles mto d ma =+ mixedAmountValueAtDate priceoracle styles mto d $ ma `maMinus` mixedAmountCostBasis ma++------------------------------------------------------------------------------+-- Market price lookup++-- | Given a memoising price graph generator, a valuation date, a+-- source commodity and an optional valuation commodity, find the+-- value on that date of one unit of the source commodity in the+-- valuation commodity, or in a default valuation commodity. Returns+-- the valuation commodity that was specified or chosen, and the+-- quantity of it that one unit of the source commodity is worth. Or+-- if no applicable market price can be found or calculated, or if the+-- source commodity and the valuation commodity are the same, returns+-- Nothing.+--+-- See makePriceGraph for how prices are determined.+-- Note that both market prices and default valuation commodities can+-- vary with valuation date, since that determines which market prices+-- are visible.+--+priceLookup :: (Day -> PriceGraph) -> Day -> CommoditySymbol -> Maybe CommoditySymbol -> Maybe (CommoditySymbol, Quantity)+priceLookup makepricegraph d from mto =+ -- trace ("priceLookup ("++show d++", "++show from++", "++show mto++")") $+ let+ PriceGraph{pgEdges=forwardprices+ ,pgEdgesRev=allprices+ ,pgDefaultValuationCommodities=defaultdests+ } =+ dbg1Msg ("valuation date: "++show d) $ makepricegraph d+ mto' = mto <|> mdefaultto+ where+ mdefaultto = dbg1 ("default valuation commodity for "++T.unpack from) $+ M.lookup from defaultdests+ in+ case mto' of+ Nothing -> Nothing+ Just to | to==from -> Nothing+ Just to ->+ -- We have a commodity to convert to. Find the most direct price available,+ -- according to the rules described in makePriceGraph.+ let+ msg = printf "seeking %s to %s price" (showCommoditySymbol from) (showCommoditySymbol to)+ prices =+ (dbg2Msg (msg++" using forward prices") $+ dbg2Msg ("forward prices:\n" <> showMarketPrices forwardprices) $+ pricesShortestPath from to forwardprices)+ <|>+ (dbg2Msg (msg++" using forward and reverse prices") $+ dbg2Msg ("forward and reverse prices:\n" <> showMarketPrices allprices) $+ pricesShortestPath from to $ dbg5 "all forward and reverse prices" allprices)+ in case prices of+ Nothing -> Nothing+ Just [] -> Nothing+ Just ps -> Just (mpto $ last ps, rate)+ where+ rates = map mprate ps+ rate =+ -- aggregate all the prices into one+ product rates+ -- product (Decimal's Num instance) normalises, stripping trailing zeros.+ -- But we want to preserve even those, since the number of decimal digits+ -- here will guide amountValueAtDate in setting the Amount display precision later.+ -- So we restore them. Or rather, we ensure as many decimal digits as the maximum seen among rates.+ -- (Some prices might end up more precise than they were, but that seems harmless here.)+ & setMinDecimalPlaces (maximum $ map decimalPlaces rates)++-- Ensure this Decimal has at least this many decimal places, adding trailing zeros if necessary.+setMinDecimalPlaces :: Word8 -> Decimal -> Decimal+setMinDecimalPlaces n d+ | decimalPlaces d < n = roundTo n d -- too few, add some zeros+ | otherwise = d -- more than enough, keep as-is++tests_priceLookup =+ let+ p y m d from q to = MarketPrice{mpdate=fromGregorian y m d, mpfrom=from, mpto=to, mprate=q}+ ps1 = [+ p 2000 01 01 "A" 10 "B"+ ,p 2000 01 01 "B" 10 "C"+ ,p 2000 01 01 "C" 10 "D"+ ,p 2000 01 01 "E" 2 "D"+ ,p 2001 01 01 "A" 11 "B"+ ]+ makepricegraph = makePriceGraph (buildPriceIndexes ps1 [] [])+ in testCase "priceLookup" $ do+ priceLookup makepricegraph (fromGregorian 1999 01 01) "A" Nothing @?= Nothing+ priceLookup makepricegraph (fromGregorian 2000 01 01) "A" Nothing @?= Just ("B",10)+ priceLookup makepricegraph (fromGregorian 2000 01 01) "B" (Just "A") @?= Just ("A",0.1)+ priceLookup makepricegraph (fromGregorian 2000 01 01) "A" (Just "E") @?= Just ("E",500)+ -- alias rates (100 d per D; and 1000 B per A, which is ignored since there are A-B market prices)+ -- are used only between commodities with no market prices between them, and are never default destinations+ let aliasprices = [p 0 01 01 "D" 100 "d", p 0 01 01 "A" 1000 "B"]+ makepricegraph' = makePriceGraph (buildPriceIndexes ps1 [] aliasprices)+ priceLookup makepricegraph' (fromGregorian 2000 01 01) "D" (Just "d") @?= Just ("d",100)+ priceLookup makepricegraph' (fromGregorian 2000 01 01) "d" (Just "D") @?= Just ("D",0.01)+ priceLookup makepricegraph' (fromGregorian 2000 01 01) "A" (Just "d") @?= Just ("d",100000)+ priceLookup makepricegraph' (fromGregorian 2000 01 01) "A" (Just "B") @?= Just ("B",10)+ priceLookup makepricegraph' (fromGregorian 2000 01 01) "D" Nothing @?= Nothing++------------------------------------------------------------------------------+-- Market price graph+-- built directly with MarketPrices for now, probably space-inefficient++type Edge = MarketPrice+type Path = [Edge]++data PriceGraph = PriceGraph {+ pgDate :: Day+ -- ^ The date on which these prices are in effect.+ ,pgEdges :: [Edge]+ -- ^ "Forward" exchange rates between commodity pairs, either+ -- declared by P directives or (with --infer-market-prices) inferred from costs,+ -- forming the edges of a directed graph. + ,pgEdgesRev :: [Edge]+ -- ^ The same edges, plus any additional edges that can be+ -- inferred by reversing them and inverting the rates.+ --+ -- In both of these there will be at most one edge between each+ -- directed pair of commodities, eg there can be one USD->EUR and one EUR->USD.+ --+ ,pgDefaultValuationCommodities :: M.Map CommoditySymbol CommoditySymbol+ -- ^ The default valuation commodity for each source commodity.+ -- These are used when a valuation commodity is not specified+ -- (-V). They are the destination commodity of each source commodity's+ -- latest (declared or inferred, but not reverse) market price+ -- (on the date of this graph).+ }+ deriving (Show,Generic)++-- | Find the shortest path and corresponding conversion rate, if any, +-- from one commodity to another using the provided market prices which+-- form the edges of a directed graph. There should be at most one edge+-- between each directed pair of commodities, eg there can be one+-- USD->EUR price and one EUR->USD price.+pricesShortestPath :: CommoditySymbol -> CommoditySymbol -> [Edge] -> Maybe Path+pricesShortestPath start end edges =+ -- at --debug=2 +, print the pretty path and also the detailed prices+ let label = printf "shortest path from %s to %s: " (showCommoditySymbol start) (showCommoditySymbol end) in+ fmap (dbg2With (("price chain:\n"++).showMarketPrices)) $+ dbg2With ((label++).(maybe "none" (pshowpath ""))) $+ find [([],edges)]++ where+ -- Find the first and shortest complete path using a breadth-first search.+ find :: [(Path,[Edge])] -> Maybe Path+ find paths =+ case concatMap extend paths of+ [] -> Nothing + _ | pathlength > maxpathlength -> + -- Print a non-fatal warning to stderr, something we usually avoid.+ warn ("gave up searching for a price chain at length "++show maxpathlength++", please report a bug")+ Nothing+ where + pathlength = 2 + maybe 0 (length . fst) (headMay paths)+ maxpathlength = 1000+ paths' -> + case completepaths of+ p:_ -> Just p -- the left-most complete path at this length+ [] -> find paths'+ where completepaths = [p | (p,_) <- paths', (mpto <$> lastMay p) == Just end]++ -- Use all applicable edges from those provided to extend this path by one step,+ -- returning zero or more new (path, remaining edges) pairs.+ extend :: (Path,[Edge]) -> [(Path,[Edge])]+ extend (path,unusededges) =+ let+ pathnodes = start : map mpto path+ pathend = maybe start mpto $ lastMay path+ (nextedges,remainingedges) = partition ((==pathend).mpfrom) unusededges+ in+ [ (path', remainingedges')+ | e <- nextedges+ , let path' = dbgpath "trying" $ path ++ [e] -- PERF prepend ?+ , let pathnodes' = mpto e : pathnodes+ , let remainingedges' = [r | r <- remainingedges, mpto r `notElem` pathnodes' ]+ ]++-- debug helpers+dbgpath label = dbg2With (pshowpath label)+-- dbgedges label = dbg2With (pshowedges label)+pshowpath label = \case+ [] -> prefix label ""+ p@(e:_) -> prefix label $ pshownode (mpfrom e) ++ ">" ++ intercalate ">" (map (pshownode . mpto) p)+-- pshowedges label = prefix label . intercalate ", " . map (pshowedge "")+-- pshowedge label MarketPrice{..} = pshowedge' label mpfrom mpto+-- pshowedge' label from to = prefix label $ pshownode from ++ ">" ++ pshownode to+pshownode = T.unpack . showCommoditySymbol+prefix l = if null l then (""++) else ((l++": ")++)++-- | A snapshot of the known exchange rates between commodity pairs at a given date.+-- This is a home-made version, more tailored to our needs.+-- | Build the graph of commodity conversion prices for a given day.+-- Converts a list of declared market prices in parse order, and a+-- list of transaction-inferred market prices in parse order, to:+--+-- 1. a graph of all known exchange rates declared or inferred from +-- one commodity to another in effect on that day+--+-- 2. a second graph which includes any additional exchange rates+-- that can be inferred by reversing known rates+--+-- 3. a map of each commodity's default valuation commodity, if any.+--+-- These allow price lookup and valuation to be performed as+-- described in hledger.m4.md -> Valuation:+--+-- "hledger looks for a market price (exchange rate) from commodity A+-- to commodity B in one or more of these ways, 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 transaction prices.+-- +-- 2. A *reverse market price*:+-- the inverse of a declared or inferred market price from B to A.+-- +-- 3. A *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. A *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."+--+-- and: "For each commodity A, hledger picks a default valuation+-- commodity as follows, in this order of preference:+--+-- 1. The price commodity from the latest declared market price for A+-- on or before valuation date.+--+-- 2. The price commodity from the latest declared market price for A+-- on any date. (Allows conversion to proceed if 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, then the price commodity from+-- the latest transaction price for A on or before valuation date."+--+-- | Build the price graph using pre-built indexes for O(pairs × log n) lookup.+makePriceGraph :: PriceIndexes -> Day -> PriceGraph+makePriceGraph indexes d =+ dbg9 ("makePriceGraph "++show d) $+ PriceGraph{+ pgDate = d+ ,pgEdges=forwardprices+ ,pgEdgesRev=allprices+ ,pgDefaultValuationCommodities=defaultdests+ }+ where+ -- XXX logic duplicated in Hledger.Cli.Commands.Prices.prices, keep synced++ -- get the latest effective price for each commodity pair on or before date d+ forwardprices = dbg9 "effective forward prices" $+ lookupEffectivePricesFromIndex d (piForward indexes)++ -- infer any additional reverse prices not already declared or inferred+ reverseprices = dbg9 "additional reverse prices" $+ [p | p@MarketPrice{..} <- map marketPriceReverse forwardprices+ , not $ (mpfrom,mpto) `S.member` forwardpairs+ ]+ where+ forwardpairs = S.fromList [(mpfrom,mpto) | MarketPrice{..} <- forwardprices]+ allprices = forwardprices ++ reverseprices++ -- use indexed lookup for default valuation commodities+ defaultdests = dbg9 "default valuation commodities" $+ lookupDefaultValuations d indexes++marketPriceReverse :: MarketPrice -> MarketPrice+marketPriceReverse mp@MarketPrice{..} = + mp{mpfrom=mpto, mpto=mpfrom, mprate=if mprate==0 then 0 else 1/mprate} -- PARTIAL: /++nullmarketprice :: MarketPrice+nullmarketprice = MarketPrice {+ mpdate=nulldate+ ,mpfrom=""+ ,mpto=""+ ,mprate=0+ }++------------------------------------------------------------------------------++tests_Valuation = testGroup "Valuation" [+ tests_priceLookup+ ,testCase "marketPriceReverse" $ do+ marketPriceReverse nullmarketprice{mprate=2} @?= nullmarketprice{mprate=0.5}+ marketPriceReverse nullmarketprice @?= nullmarketprice -- the reverse of a 0 price is a 0 price+++ ]
+ Hledger/Query.hs view
@@ -0,0 +1,1598 @@+{-|++A general query system for matching things (accounts, postings,+transactions..) by various criteria, and a SimpleTextParser for query expressions.++-}++{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE TupleSections #-}++module Hledger.Query (+ -- * Query and QueryOpt+ Query(..),+ QueryOpt(..),+ OrdPlus(..),+ payeeTag,+ noteTag,+ generatedTransactionTag,+ -- * parsing+ parseQuery,+ parseQueryList,+ parseQueryTerm,+ parseAccountType,+ parseDepthSpec,+ parseAmountQueryArg,+ -- * modifying+ transformQuery,+ simplifyQuery,+ filterQuery,+ filterQueryOrNotQuery,+ querySplitRowTerms,+ matchesQuery,+ -- * predicates+ queryIsNull,+ queryIsDate,+ queryIsDate2,+ queryIsDateOrDate2,+ queryIsStatus,+ queryIsCode,+ queryIsDesc,+ queryIsTag,+ queryIsAcct,+ queryIsFind,+ queryIsType,+ queryIsDepth,+ queryIsFlatDepth,+ queryIsReal,+ queryIsAmt,+ queryIsCur,+ queryIsAmtOrCur,+ queryIsChange,+ queryIsBalance,+ queryIsRowTerm,+ queryHasBalance,+ queryHasChange,+ queryIsStartDateOnly,+ queryIsTransactionRelated,+ -- * accessors+ queryStartDate,+ queryEndDate,+ queryDateSpan,+ queryDateSpan',+ queryDepth,+ inAccount,+ inAccountQuery,+ -- * matching things with queries+ matchesTransaction,+ matchesTransactionExtra,+ matchesPayee,+ matchesPosting,+ matchesPostingExtra,+ postingQueryForAccount,+ matchesAccount,+ matchesAccountExtra,+ matchesMixedAmount,+ matchesAmount,+ matchesRowAmounts,+ matchesCommodity,+ matchesCommodityExtra,+ matchesTag,+ -- patternsMatchTags,+ matchesPriceDirective,+ words'',+ queryprefixes,+ -- * tests+ tests_Query+)+where++import Control.Applicative+import Control.Monad (guard)+import Data.Default (Default(..))+import Data.Char (isDigit)+import Data.Either (partitionEithers)+import Data.List (partition)+import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar (Day, fromGregorian )+import Safe (headErr, readMay, maximumByMay, maximumMay, minimumMay)+import Text.Megaparsec (between, noneOf, sepBy, try, (<?>), notFollowedBy)+import Text.Megaparsec.Char (char, string, string')+++import Hledger.Utils hiding (words')+import Hledger.Data.Types+import Hledger.Data.AccountName+import Hledger.Data.AccountType+import Hledger.Data.Amount (amountsRaw, isNonsimpleCommodityChar, mixedAmount, mixedAmountStripCosts, nullamt, nullmixedamt, showAmountWithZeroCommodity, showMixedAmountOneLine, usd)+import Hledger.Data.Dates+import Hledger.Data.Posting+import Hledger.Data.Transaction+import Data.Bifunctor+++-- | A query is a composition of search criteria, which can be used to+-- match postings, transactions, accounts and more.+data Query = + -- no-op queries+ Any -- ^ always match+ | None -- ^ never match+ -- data queries (in "standard" order, roughly as they appear in a transaction)+ | Date DateSpan -- ^ match primary dates in this date span+ | Date2 DateSpan -- ^ match secondary dates in this date span+ | StatusQ Status -- ^ match this txn/posting status+ | Code Regexp -- ^ match txn codes infix-matched by this regexp+ | Desc Regexp -- ^ match txn descriptions infix-matched by this regexp+ | Tag Regexp (Maybe Regexp) -- ^ match if a tag's name, and optionally its value, is infix-matched by the respective regexps+ | Acct Regexp -- ^ match account names infix-matched by this regexp+ | Type [AccountType] -- ^ match accounts whose type is one of these (or with no types, any account)+ | Depth Int -- ^ match if account depth is less than or equal to this value (or, sometimes used as a display option)+ | DepthAcct Regexp Int -- ^ match if the account matches and account depth is less than or equal to this value (usually used as a display option)+ | Real Bool -- ^ match postings with this "realness" value+ | Amt OrdPlus Quantity (Maybe CommoditySymbol)+ -- ^ match if the amount's numeric quantity is less than/greater than/equal to/unsignedly equal to some value,+ -- considering just amounts in this commodity if one is given+ | Cur Regexp -- ^ match if the commodity symbol is fully matched by this regexp.+ | Change OrdPlus Quantity (Maybe CommoditySymbol)+ -- ^ like Amt, but matching a report row (or an entry) by its change: the sum of its postings.+ -- Not tested against postings; reports apply it after aggregating (see 'querySplitRowTerms').+ | Balance OrdPlus Quantity (Maybe CommoditySymbol)+ -- ^ like Amt, but matching a report row by its balance: the sum of its postings up to the end of its period.+ -- Not tested against postings; reports apply it after aggregating (see 'querySplitRowTerms').+ | Find Regexp (Maybe DateSpan) -- ^ match if any text field (account, amount, comment, tag name or value, description, code) is infix-matched by this regexp, or if the date is within this span (present when the pattern also parses as a period expression)+ -- compound queries (expr:)+ | Not Query -- ^ negate this match+ | And [Query] -- ^ match if all of these match+ | Or [Query] -- ^ match if any of these match+ -- compound queries selecting whole transactions (any:, all:).+ -- When matching a posting, these look at the postings of its parent+ -- transaction, so a posting can be matched because of its siblings.+ -- In contexts with neither a transaction nor sibling postings available+ -- (matching an account name, a commodity symbol...), they are equivalent to And.+ | AnyPosting [Query] -- ^ match if any one posting is matched by all of these+ | AllPostings [Query] -- ^ match if all of one or more postings are matched by all of these+ deriving (Eq,Show)++instance Default Query where def = Any++-- | Construct a query for the payee: tag+payeeTag :: Maybe Text -> Either RegexError Query+payeeTag = fmap (Tag (toRegexCI' "payee")) . maybe (pure Nothing) (fmap Just . toQueryRegex)++-- | Construct a query for the note: tag+noteTag :: Maybe Text -> Either RegexError Query+noteTag = fmap (Tag (toRegexCI' "note")) . maybe (pure Nothing) (fmap Just . toQueryRegex)++-- | Construct a query for the generated-transaction: tag+generatedTransactionTag :: Query+generatedTransactionTag = Tag (toRegexCI' "generated-transaction") Nothing++-- | A more expressive Ord, used for amt:, change: and balance: queries. The Abs* variants+-- compare with the absolute value of a number, ignoring sign.+data OrdPlus = Lt | LtEq | Gt | GtEq | Eq | AbsLt | AbsLtEq | AbsGt | AbsGtEq | AbsEq+ deriving (Show,Eq)++-- | A query option changes a query's/report's behaviour and output in some way.+data QueryOpt = QueryOptInAcctOnly AccountName -- ^ show an account register focussed on this account+ | QueryOptInAcct AccountName -- ^ as above but include sub-accounts in the account register+ | QueryOptInterval Interval -- ^ report interval extracted from a date: query+ -- | QueryOptCostBasis -- ^ show amounts converted to cost where possible+ -- | QueryOptDate2 -- ^ show secondary dates instead of primary dates+ deriving (Show, Eq)++-- parsing++-- -- | A query restricting the account(s) to be shown in the sidebar, if any.+-- -- Just looks at the first query option.+-- showAccountMatcher :: [QueryOpt] -> Maybe Query+-- showAccountMatcher (QueryOptInAcctSubsOnly a:_) = Just $ Acct True $ accountNameToAccountRegex a+-- showAccountMatcher _ = Nothing+++-- | A version of parseQueryList which acts on a single Text of+-- space-separated terms.+--+-- The usual shell quoting rules are assumed. When a pattern contains+-- whitespace, it (or the whole term including prefix) should be enclosed+-- in single or double quotes.+--+-- A query term is either:+--+-- 1. a search pattern, which matches on one or more fields, eg:+--+-- acct:REGEXP - match the account name with a regular expression+-- desc:REGEXP - match the transaction description+-- date:PERIODEXP - match the date with a period expression+--+-- The prefix indicates the field to match, or if there is no prefix+-- account name is assumed.+--+-- 2. a query option, which modifies the reporting behaviour in some+-- way. There is currently one of these, which may appear only once:+--+-- inacct:FULLACCTNAME+--+-- Period expressions may contain relative dates, so a reference date is+-- required to fully parse these.+--+-- >>> parseQuery nulldate "expenses:dining out"+-- Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])+--+-- >>> parseQuery nulldate "\"expenses:dining out\""+-- Right (Acct (RegexpCI "expenses:dining out"),[])+parseQuery :: Day -> T.Text -> Either String (Query,[QueryOpt])+parseQuery d t = parseQueryList d $ words'' queryprefixes t++-- | Convert a list of space-separated queries to a single query+--+-- Multiple terms are combined as follows:+-- 1. multiple account patterns are OR'd together+-- 2. multiple description patterns are OR'd together+-- 3. multiple status patterns are OR'd together+-- 4. then all terms are AND'd together+parseQueryList :: Day -> [T.Text] -> Either String (Query, [QueryOpt])+parseQueryList d termstrs = do+ eterms <- mapM (parseQueryTerm d) termstrs+ let (pats, optss) = unzip eterms+ q = combineQueriesByType pats+ _ <- querySplitRowTerms q -- check change:/balance: terms are used only where they can be applied+ Right (q, concat optss)++combineQueriesByType :: [Query] -> Query+combineQueriesByType pats = q+ where+ (descpats, pats') = partition queryIsDesc pats+ (acctpats, pats'') = partition queryIsAcct pats'+ (statuspats, otherpats) = partition queryIsStatus pats''+ q = simplifyQuery $ And $ [Or acctpats, Or descpats, Or statuspats] ++ otherpats+ +-- XXX+-- | Quote-and-prefix-aware version of words - don't split on spaces which+-- are inside quotes, including quotes which may have one of the specified+-- prefixes in front, and maybe an additional not: prefix in front of that.+words'' :: [T.Text] -> T.Text -> [T.Text]+words'' prefixes = fromparse . parsewith maybePrefixedQuotedPhrases -- XXX+ where+ maybePrefixedQuotedPhrases :: SimpleTextParser [T.Text]+ maybePrefixedQuotedPhrases = choice' [prefixedQuotedPattern, singleQuotedPattern, doubleQuotedPattern, patterns] `sepBy`+ (notFollowedBy (skipNonNewlineSpaces >> char ')') >> skipNonNewlineSpaces1)+ prefixedQuotedPattern :: SimpleTextParser T.Text+ prefixedQuotedPattern = do+ not' <- fromMaybe "" `fmap` (optional $ string "not:")+ let allowednexts | T.null not' = prefixes+ | otherwise = prefixes ++ [""]+ next <- choice' $ map string allowednexts+ let prefix :: T.Text+ prefix = not' <> next+ p <- singleQuotedPattern <|> doubleQuotedPattern+ return $ prefix <> textStripQuotes p+ singleQuotedPattern :: SimpleTextParser T.Text+ singleQuotedPattern = textStripQuotes . T.pack <$> between (char '\'') (char '\'') (many $ noneOf ("'" :: [Char]))+ doubleQuotedPattern :: SimpleTextParser T.Text+ doubleQuotedPattern = textStripQuotes . T.pack <$> between (char '"') (char '"') (many $ noneOf ("\"" :: [Char]))+ patterns :: SimpleTextParser T.Text+ patterns = T.pack <$> many (noneOf (" \n\r" :: [Char]))++-- XXX+-- keep synced with patterns below, excluding "not"+queryprefixes :: [T.Text]+queryprefixes = map (<>":") [+ "inacctonly"+ ,"inacct"+ ,"amt"+ ,"change"+ ,"balance"+ ,"code"+ ,"desc"+ ,"payee"+ ,"note"+ ,"acct"+ ,"date"+ ,"date2"+ ,"status"+ ,"cur"+ ,"real"+ ,"depth"+ ,"tag"+ ,"type"+ ,"expr"+ ,"any"+ ,"all"+ ,"find"+ ]+ ++ ["::"] -- short form of find:++defaultprefix :: T.Text+defaultprefix = "acct"++-- -- | Parse the query string as a boolean tree of match patterns.+-- parseQueryTerm :: String -> Query+-- parseQueryTerm s = either (const (Any)) id $ runParser query () "" $ lexmatcher s++-- lexmatcher :: String -> [String]+-- lexmatcher s = words' s++-- query :: GenParser String () Query+-- query = undefined++-- | Parse a single query term as either a query or a query option,+-- or return an error message if parsing fails.+parseQueryTerm :: Day -> T.Text -> Either String (Query, [QueryOpt])+parseQueryTerm _ (T.stripPrefix "inacctonly:" -> Just s) = Right (Any, [QueryOptInAcctOnly s])+parseQueryTerm _ (T.stripPrefix "inacct:" -> Just s) = Right (Any, [QueryOptInAcct s])+parseQueryTerm d (T.stripPrefix "not:" -> Just s) =+ case parseQueryTerm d s of+ Right (q, qopts) -> Right (Not q, qopts)+ Left err -> Left err+parseQueryTerm _ (T.stripPrefix "code:" -> Just s) = (,[]) . Code <$> toQueryRegex s+parseQueryTerm _ (T.stripPrefix "desc:" -> Just s) = (,[]) . Desc <$> toQueryRegex s+parseQueryTerm _ (T.stripPrefix "payee:" -> Just s) = (,[]) <$> payeeTag (Just s)+parseQueryTerm _ (T.stripPrefix "note:" -> Just s) = (,[]) <$> noteTag (Just s)+parseQueryTerm _ (T.stripPrefix "acct:" -> Just s) = (,[]) . Acct <$> toQueryRegex s+parseQueryTerm d (T.stripPrefix "find:" -> Just s) = (,[]) <$> parseFindQuery d s+parseQueryTerm d (T.stripPrefix "::" -> Just s) = (,[]) <$> parseFindQuery d s+parseQueryTerm d (T.stripPrefix "date2:" -> Just s) =+ case parsePeriodExpr d s of Left e -> Left $ "could not parse \"date2:"++T.unpack s++"\": "++customErrorBundlePretty e+ Right (_ , spn) -> Right (Date2 spn, [])+parseQueryTerm d (T.stripPrefix "date:" -> Just s) =+ case parsePeriodExpr d s of Left e -> Left $ "could not parse \"date:"++T.unpack s++"\": "++customErrorBundlePretty e+ Right (NoInterval, spn) -> Right (Date spn, [])+ Right (interval , spn) -> Right (Date spn, [QueryOptInterval interval])+parseQueryTerm _ (T.stripPrefix "status:" -> Just s) =+ case parseStatus s of Left e -> Left $ "\"status:"++T.unpack s++"\" gave a parse error: " ++ e+ Right st -> Right (StatusQ st, [])+parseQueryTerm _ (T.stripPrefix "real:" -> Just s) = Right (Real $ parseBool s || T.null s, [])+parseQueryTerm _ (T.stripPrefix "amt:" -> Just s) = case parseAmountQueryArg "amt" s of+ Right (ord, q, mc) -> Right (Amt ord q mc, [])+ Left err -> Left err+parseQueryTerm _ (T.stripPrefix "change:" -> Just s) = case parseAmountQueryArg "change" s of+ Right (ord, q, mc) -> Right (Change ord q mc, [])+ Left err -> Left err+parseQueryTerm _ (T.stripPrefix "balance:" -> Just s) = case parseAmountQueryArg "balance" s of+ Right (ord, q, mc) -> Right (Balance ord q mc, [])+ Left err -> Left err+parseQueryTerm _ (T.stripPrefix "depth:" -> Just s) = (,[]) <$> parseDepthSpecQuery s+parseQueryTerm _ (T.stripPrefix "cur:" -> Just s) = (,[]) . Cur <$> toRegexCI ("^" <> s <> "$") -- support cur: as an alias+parseQueryTerm _ (T.stripPrefix "tag:" -> Just s) = (,[]) <$> parseTag s+parseQueryTerm _ (T.stripPrefix "type:" -> Just s) = (,[]) <$> parseTypeCodes s+parseQueryTerm d (T.stripPrefix "expr:" -> Just s) = parseBooleanQuery d s+parseQueryTerm d (T.stripPrefix "any:" -> Just s) = first (AnyPosting . (:[])) <$> parseBooleanQuery d s+parseQueryTerm d (T.stripPrefix "all:" -> Just s) = first (AllPostings . (:[])) <$> parseBooleanQuery d s+parseQueryTerm _ "" = Right (Any, [])+parseQueryTerm d s = parseQueryTerm d $ defaultprefix<>":"<>s++-- | Parses a boolean query expression.+--+-- Boolean queries combine smaller queries into larger ones. The boolean operators+-- made available through this function are "NOT e", "e AND e", "e OR e", and "e e".+-- Query options defined in multiple sub-queries are simply combined by concatenating+-- all options into one list.+--+-- Boolean operators in queries take precedence over one another. For instance, the+-- prefix-operator "NOT e" is always parsed before "e AND e", "e AND e" before "e OR e",+-- and "e OR e" before "e e".+--+-- The "space" operator still works as it did before the introduction of boolean operators:+-- it combines terms according to their types, using parseQueryList.+-- Whereas the new NOT, OR, and AND operators work uniformly for all term types.+-- There is an exception: queries being OR'd may not specify a date period,+-- because that can produce multiple, possibly disjoint, report periods and result sets,+-- and we don't have report semantics worked out for it yet. (#2178)+--+-- The result of this function is either an error encountered during parsing of the+-- expression or the combined query and query options.+--+-- >>> parseBooleanQuery nulldate "expenses:dining AND out"+-- Right (And [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])+--+-- >>> parseBooleanQuery nulldate "expenses:dining AND desc:a OR desc:b"+-- Right (Or [And [Acct (RegexpCI "expenses:dining"),Desc (RegexpCI "a")],Desc (RegexpCI "b")],[])+--+parseBooleanQuery :: Day -> T.Text -> Either String (Query,[QueryOpt])+parseBooleanQuery d t =+ either (Left . ("failed to parse query:" <>) . customErrorBundlePretty) Right $+ parsewith spacedExprsP t++ where+ -- Our "boolean queries" are compound query expressions built with a hierarchy of combinators.+ -- At the top level we have one or more query expressions separated by space.+ -- These are combined in the default way according to their types (see combineQueriesByType).+ spacedExprsP :: SimpleTextParser (Query, [QueryOpt])+ spacedExprsP = combineWith combineQueriesByType <$> orExprsP `sepBy` skipNonNewlineSpaces1++ where+ combineWith :: ([Query] -> Query) -> [(Query, [QueryOpt])] -> (Query, [QueryOpt])+ combineWith f res =+ let (qs, qoptss) = unzip res+ qoptss' = concat qoptss+ in case qs of+ [] -> (Any, qoptss')+ (q:[]) -> (simplifyQuery q, qoptss')+ _ -> (simplifyQuery $ f qs, qoptss')++ -- Containing query expressions separated by "or".+ -- If there's more than one, make sure none contains a "date:".+ orExprsP :: SimpleTextParser (Query, [QueryOpt])+ orExprsP = do+ exprs <- andExprsP `sepBy` (try $ skipNonNewlineSpaces >> string' "or" >> skipNonNewlineSpaces1)+ if ( length exprs > 1+ && (any (/=Any) $ map (filterQuery queryIsDateOrDate2 . fst) exprs))+ then fail "sorry, using date: in OR expressions is not supported."+ else return $ combineWith Or exprs++ where+ -- Containing query expressions separated by "and".+ andExprsP :: SimpleTextParser (Query, [QueryOpt])+ andExprsP = combineWith And <$> maybeNotExprP `sepBy` (try $ skipNonNewlineSpaces >> string' "and" >> skipNonNewlineSpaces1)++ where+ -- Containing query expressions optionally preceded by "not".+ maybeNotExprP :: SimpleTextParser (Query, [QueryOpt])+ maybeNotExprP = (maybe id (\_ (q, qopts) -> (Not q, qopts)) <$>+ optional (try $ string' "not" >> notFollowedBy (char ':') >> skipNonNewlineSpaces1)) <*> termOrParenthesisedExprP++ where+ -- Each of which is a parenthesised query expression or a single query term.+ termOrParenthesisedExprP :: SimpleTextParser (Query, [QueryOpt])+ termOrParenthesisedExprP = + between (char '(' >> skipNonNewlineSpaces) (try $ skipNonNewlineSpaces >> char ')') spacedExprsP+ <|> queryTermP++ where+ -- A simple query term: foo, acct:foo, desc:foo, payee:foo etc.+ queryTermP :: SimpleTextParser (Query, [QueryOpt])+ queryTermP = do+ prefix <- optional queryPrefixP+ arg <- queryArgP+ case parseQueryTerm d (fromMaybe "" prefix <> arg) of+ Right q -> return q+ Left err -> error' err++ where+ -- One of the query prefixes: acct:, desc:, payee: etc (plus zero or more not: prefixes).+ queryPrefixP :: SimpleTextParser T.Text+ queryPrefixP =+ (string "not:" <> (fromMaybe "" <$> optional queryPrefixP))+ <|> choice' (string <$> queryprefixes)+ <?> "query prefix"++ -- A query term's argument, the part after the prefix:+ -- any text enclosed in single quotes or double quotes,+ -- or any text up to the next space, closing parenthesis, or end of line,+ -- if it is not one of the keywords "not", "and", "or".+ queryArgP :: SimpleTextParser T.Text+ queryArgP = choice'+ [ textStripQuotes . T.pack <$> between (char '\'') (char '\'') (many $ noneOf ("'" :: [Char])),+ textStripQuotes . T.pack <$> between (char '"') (char '"') (many $ noneOf ("\"" :: [Char])),+ T.pack <$> (notFollowedBy keywordP >> (many $ noneOf (") \n\r" :: [Char]))) ]++ where+ -- Any of the combinator keywords used above (not/and/or), terminated by a space.+ keywordP :: SimpleTextParser T.Text+ keywordP = choice' (string' <$> ["not ", "and ", "or "])++-- | Parse the argument of a find: (or ::) query: a case-insensitive regexp+-- to be matched against any text field, and, if the argument also parses+-- as a period expression with a start or end date, a date span to be+-- matched against dates.+parseFindQuery :: Day -> T.Text -> Either RegexError Query+parseFindQuery d s = Find <$> toQueryRegex s <*> pure mspan+ where+ mspan = case parsePeriodExpr d s of+ Right (_, spn) | spn /= nulldatespan -> Just spn+ _ -> Nothing++-- | Parse the argument of an amt query term ([OP][SIGN]NUM), to an+-- OrdPlus and a Quantity, or if parsing fails, an error message. OP+-- can be <=, <, >=, >, or = . NUM can be a simple integer or decimal.+-- If a decimal, the decimal mark must be period, and it must have+-- digits preceding it. Digit group marks are not allowed.+parseAmountQueryTerm :: T.Text -> Either String (OrdPlus, Quantity)+parseAmountQueryTerm amtarg =+ case amtarg of+ -- number has a + sign, do a signed comparison+ (parse "<=+" -> Just q) -> Right (LtEq ,q)+ (parse "<+" -> Just q) -> Right (Lt ,q)+ (parse ">=+" -> Just q) -> Right (GtEq ,q)+ (parse ">+" -> Just q) -> Right (Gt ,q)+ (parse "=+" -> Just q) -> Right (Eq ,q)+ (parse "+" -> Just q) -> Right (Eq ,q)+ -- number has a - sign, do a signed comparison+ (parse "<-" -> Just q) -> Right (Lt ,-q)+ (parse "<=-" -> Just q) -> Right (LtEq ,-q)+ (parse ">-" -> Just q) -> Right (Gt ,-q)+ (parse ">=-" -> Just q) -> Right (GtEq ,-q)+ (parse "=-" -> Just q) -> Right (Eq ,-q)+ (parse "-" -> Just q) -> Right (Eq ,-q)+ -- number is unsigned and zero, do a signed comparison (more useful)+ (parse "<=" -> Just 0) -> Right (LtEq ,0)+ (parse "<" -> Just 0) -> Right (Lt ,0)+ (parse ">=" -> Just 0) -> Right (GtEq ,0)+ (parse ">" -> Just 0) -> Right (Gt ,0)+ -- number is unsigned and non-zero, do an absolute magnitude comparison+ (parse "<=" -> Just q) -> Right (AbsLtEq ,q)+ (parse "<" -> Just q) -> Right (AbsLt ,q)+ (parse ">=" -> Just q) -> Right (AbsGtEq ,q)+ (parse ">" -> Just q) -> Right (AbsGt ,q)+ (parse "=" -> Just q) -> Right (AbsEq ,q)+ (parse "" -> Just q) -> Right (AbsEq ,q)+ _ -> Left . T.unpack $+ "could not parse as a comparison operator followed by an optionally-signed number: " <> amtarg+ where+ -- Strip outer whitespace from the text, require and remove the+ -- specified prefix, remove all whitespace from the remainder, and+ -- read it as a simple integer or decimal if possible.+ parse :: T.Text -> T.Text -> Maybe Quantity+ parse p s = (T.stripPrefix p . T.strip) s >>= readMay . T.unpack . T.filter (/=' ')++-- | Parse the argument of an amt:, change: or balance: query term: a comparison ([OP][SIGN]NUM,+-- see 'parseAmountQueryTerm'), optionally with a commodity symbol before or after the number+-- (and its sign), as in @>$100@, @>-$100@, @>100 EUR@ or @>"AAPL 2026" 5@.+-- Returns an OrdPlus, a Quantity and the commodity symbol if any,+-- or if parsing fails, an error message mentioning the given query type.+--+-- >>> parseAmountQueryArg "amt" ">100"+-- Right (AbsGt,100,Nothing)+-- >>> parseAmountQueryArg "amt" "<-$100"+-- Right (Lt,-100,Just "$")+-- >>> parseAmountQueryArg "change" ">= 100 EUR"+-- Right (AbsGtEq,100,Just "EUR")+-- >>> parseAmountQueryArg "change" "\"AAPL 2026\"+5"+-- Right (Eq,5,Just "AAPL 2026")+parseAmountQueryArg :: String -> T.Text -> Either String (OrdPlus, Quantity, Maybe CommoditySymbol)+parseAmountQueryArg qtype arg = maybe (Left err) Right $ do+ let (op, rest) = T.span (`elem` ("<>=" :: String)) $ T.strip arg+ (sign1, rest1) = takeSign $ T.stripStart rest+ (msym1, rest2) = takeSymbol rest1+ (sign2, rest3) = takeSign rest2+ (num, rest4) = T.span (\c -> isDigit c || c == '.') rest3+ (msym2, rest5) = takeSymbol $ T.stripStart rest4+ guard $ T.null rest5+ sign <- case (sign1, sign2) of+ (s1, "") -> Just s1+ ("", s2) -> Just s2+ _ -> Nothing+ msym <- case (msym1, msym2) of+ (m, Nothing) -> Just m+ (Nothing, m) -> Just m+ _ -> Nothing+ (ord, q) <- either (const Nothing) Just . parseAmountQueryTerm $ op <> sign <> num+ Just (ord, q, msym)+ where+ err = "could not parse \"" ++ qtype ++ ":" ++ T.unpack arg ++ "\": expected a comparison operator"+ ++ " followed by an optionally-signed number, with an optional commodity symbol"+ -- a leading + or - sign if any, and the rest with leading spaces removed+ takeSign t = case T.uncons t of+ Just (c, t') | c `elem` ("+-" :: String) -> (T.singleton c, T.stripStart t')+ _ -> ("", t)+ -- a leading double-quoted or simple commodity symbol if any, and the rest with leading spaces removed+ takeSymbol t = case T.uncons t of+ Just ('"', t') | (sym, t'') <- T.break (=='"') t', not (T.null sym || T.null t'')+ -> (Just sym, T.stripStart $ T.drop 1 t'')+ _ -> case T.span (not . isNonsimpleCommodityChar) t of+ ("", _ ) -> (Nothing, t)+ (sym, t') -> (Just sym, T.stripStart t')++-- | Compile the regular expression argument of a query term, case-insensitively.+-- An empty argument (which the regex engine rejects) is replaced by an empty+-- group, so that it matches anything.+toQueryRegex :: T.Text -> Either RegexError Regexp+toQueryRegex s = toRegexCI $ if T.null s then "()" else s++parseTag :: T.Text -> Either RegexError Query+parseTag s = do+ tag <- toQueryRegex $ if T.null v then s else n+ body <- if T.null v then pure Nothing else Just <$> toQueryRegex (T.tail v)+ return $ Tag tag body+ where (n,v) = T.break (=='=') s++parseDepthSpec :: T.Text -> Either RegexError DepthSpec+parseDepthSpec s = do+ let depthString = T.unpack $ if T.null b then a else T.tail b+ depth <- case readMay depthString of+ Just d | d >= 0 -> Right d+ _ -> Left $ "could not parse depth \"" ++ T.unpack s ++ "\": "+ ++ "it should be a whole number, 0 or more, optionally preceded by ACCTREGEX="+ regexp <- mapM toQueryRegex $ if T.null b then Nothing else Just a+ return $ case regexp of+ Nothing -> DepthSpec (Just depth) []+ Just r -> DepthSpec Nothing [(r, depth)]+ where+ (a,b) = T.break (=='=') s++parseDepthSpecQuery :: T.Text -> Either RegexError Query+parseDepthSpecQuery s = do+ DepthSpec flat rs <- parseDepthSpec s+ let regexps = map (uncurry DepthAcct) rs+ return . And $ maybe id (\d -> (Depth d :)) flat regexps++-- | Parse one or more account type code letters to a query matching any of those types.+parseTypeCodes :: T.Text -> Either String Query+parseTypeCodes s =+ case partitionEithers $ map (parseAccountType False . T.singleton) $ T.unpack s of+ ((e:_),_) -> Left $ "could not parse " <> show e <> " as an account type code.\n" <> help+ ([],[]) -> Left help+ ([],ts) -> Right $ Type ts+ where+ help = "type:'s argument should be one or more of " ++ accountTypeChoices False++-- | Parse the value part of a "status:" query, or return an error.+parseStatus :: T.Text -> Either String Status+parseStatus s | s `elem` ["*","1"] = Right Cleared+ | s `elem` ["","0"] = Right Unmarked+ | s == "!" = Right Pending+ | otherwise = Left $ "could not parse "++show s++" as a status (should be *, ! or empty)"++-- | Parse the boolean value part of a "status:" query. "1" means true,+-- anything else will be parsed as false without error.+parseBool :: T.Text -> Bool+parseBool s = s `elem` truestrings++truestrings :: [T.Text]+truestrings = ["1"]++-- * modifying++-- | Bottom-up rewrite of a Query tree: recursively transform the+-- children of each compound query (Not, And, Or, AnyPosting,+-- AllPostings), then apply f to the resulting node. Leaf queries (Cur,+-- Acct, Date, ...) are passed straight to f. Use this when you want to+-- write a single-node rewrite rule and have it applied throughout the+-- tree without re-doing the structural recursion by hand.+transformQuery :: (Query -> Query) -> Query -> Query+transformQuery f = go+ where+ go (Not q) = f (Not (go q))+ go (And qs) = f (And (map go qs))+ go (Or qs) = f (Or (map go qs))+ go (AnyPosting qs) = f (AnyPosting (map go qs))+ go (AllPostings qs) = f (AllPostings (map go qs))+ go q = f q++simplifyQuery :: Query -> Query+simplifyQuery q0 =+ let q1 = simplify q0+ in if q1 == q0 then q0 else simplifyQuery q1+ where+ simplify (And []) = Any+ simplify (And [q]) = simplify q+ simplify (And qs) | same qs = simplify $ headErr qs -- PARTIAL headErr succeeds because pattern ensures non-null qs+ | None `elem` qs = None+ | all queryIsDate qs = Date $ spansIntersect $ mapMaybe queryTermDateSpan qs+ | otherwise = And $ map simplify dateqs ++ map simplify otherqs+ where (dateqs, otherqs) = partition queryIsDate $ filter (/=Any) qs+ simplify (Or []) = Any+ simplify (Or [q]) = simplifyQuery q+ simplify (Or qs) | same qs = simplify $ headErr qs -- PARTIAL headErr succeeds because pattern ensures non-null qs+ | Any `elem` qs = Any+ -- all queryIsDate qs = Date $ spansUnion $ mapMaybe queryTermDateSpan qs ?+ | otherwise = Or $ map simplify $ filter (/=None) qs+ simplify (Date (DateSpan Nothing Nothing)) = Any+ simplify (Date2 (DateSpan Nothing Nothing)) = Any+ simplify q = q++same [] = True+same (a:as) = all (a==) as++-- | Remove query terms (or whole sub-expressions) from this query+-- which do not match the given predicate. XXX Semantics not completely clear.+-- Also calls simplifyQuery on the result.+filterQuery :: (Query -> Bool) -> Query -> Query+filterQuery p = simplifyQuery . filterQuery' p++-- | Like filterQuery, but returns the filtered query as is, without simplifying.+-- Note this is problematic for complex boolean queries, which if split apart +-- by filterQuery and then re-composed, may be altered. See eg #2371.+filterQuery' :: (Query -> Bool) -> Query -> Query+filterQuery' p (And qs) = And $ map (filterQuery' p) qs+filterQuery' p (Or qs) = Or $ map (filterQuery' p) qs+-- filterQuery' p (Or qs) = Or $ filter (not.(==Any)) $ map (filterQuery' p) qs -- better for some, worse for others+filterQuery' p q = if p q then q else Any++-- | Remove query terms (or whole sub-expressions) from this query+-- which match neither the given predicate nor that predicate negated +-- (eg, if predicate is queryIsAcct, this will keep both "acct:" and "not:acct:" terms).+-- Also calls simplifyQuery on the result.+-- (Since 1.24.1, might be merged into filterQuery in future.)+-- XXX Semantics not completely clear.+filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query+filterQueryOrNotQuery p0 = simplifyQuery . filterQueryOrNotQuery' p0+ where+ filterQueryOrNotQuery' :: (Query -> Bool) -> Query -> Query+ filterQueryOrNotQuery' p (And qs) = And $ map (filterQueryOrNotQuery p) qs+ filterQueryOrNotQuery' p (Or qs) = Or $ map (filterQueryOrNotQuery p) qs+ filterQueryOrNotQuery' p (Not q) | p q = Not $ filterQueryOrNotQuery p q+ filterQueryOrNotQuery' p q = if p q then q else Any++-- | Split a query into its row terms (change: and balance: terms, including negated ones), and the rest.+-- Row terms match report rows, after aggregation, so they must be combined with+-- the rest of the query by AND; one used elsewhere (inside OR, a negated group,+-- any: or all:) gives an error.+--+-- >>> querySplitRowTerms (And [Acct (toRegexCI' "a"), Not (Change AbsGt 1 Nothing)])+-- Right (Not (Change AbsGt 1 Nothing),Acct (RegexpCI "a"))+querySplitRowTerms :: Query -> Either String (Query, Query)+querySplitRowTerms q+ | any (queryHasTerm queryIsRowTerm) others =+ Left "change: and balance: can only be combined with other query terms by AND (not inside OR, a negated group, any: or all:)"+ | otherwise = Right (simplifyQuery $ And rowterms, simplifyQuery $ And others)+ where+ (rowterms, others) = partition isRowTerm $ conjuncts q+ conjuncts (And qs) = concatMap conjuncts qs+ conjuncts q' = [q']++-- | Does this query contain a term satisfying the predicate, at any depth ?+queryHasTerm :: (Query -> Bool) -> Query -> Bool+queryHasTerm p = go+ where+ go q | p q = True+ go (Not q') = go q'+ go (And qs) = any go qs+ go (Or qs) = any go qs+ go (AnyPosting qs) = any go qs+ go (AllPostings qs) = any go qs+ go _ = False++-- | Is this a change: or balance: term, possibly negated ?+isRowTerm :: Query -> Bool+isRowTerm (Not q) = isRowTerm q+isRowTerm q = queryIsRowTerm q++-- * predicates++-- | Does this simple query predicate match any part of this possibly compound query ?+matchesQuery :: (Query -> Bool) -> Query -> Bool+matchesQuery p (And qs) = any (matchesQuery p) qs+matchesQuery p (Or qs) = any (matchesQuery p) qs+matchesQuery p (Not q) = p q+matchesQuery p q = p q++-- | Does this query match everything ?+queryIsNull :: Query -> Bool+queryIsNull Any = True+queryIsNull (And []) = True+queryIsNull (Not (Or [])) = True+queryIsNull _ = False++-- | Is this a simple query of this type (date:) ? +-- Does not match a compound query involving and/or/not.+-- Likewise for the following functions.+queryIsDate :: Query -> Bool+queryIsDate (Date _) = True+queryIsDate _ = False++queryIsDate2 :: Query -> Bool+queryIsDate2 (Date2 _) = True+queryIsDate2 _ = False++queryIsDateOrDate2 :: Query -> Bool+queryIsDateOrDate2 (Date _) = True+queryIsDateOrDate2 (Date2 _) = True+queryIsDateOrDate2 _ = False++queryIsStatus :: Query -> Bool+queryIsStatus (StatusQ _) = True+queryIsStatus _ = False++queryIsCode :: Query -> Bool+queryIsCode (Code _) = True+queryIsCode _ = False++queryIsDesc :: Query -> Bool+queryIsDesc (Desc _) = True+queryIsDesc _ = False++queryIsTag :: Query -> Bool+queryIsTag (Tag _ _) = True+queryIsTag _ = False++queryIsAcct :: Query -> Bool+queryIsAcct (Acct _) = True+queryIsAcct _ = False++queryIsFind :: Query -> Bool+queryIsFind (Find _ _) = True+queryIsFind _ = False++queryIsType :: Query -> Bool+queryIsType (Type _) = True+queryIsType _ = False++queryIsDepth :: Query -> Bool+queryIsDepth (Depth _) = True+queryIsDepth (DepthAcct _ _) = True+queryIsDepth _ = False++-- | Is this a flat depth limit (depth:N), applying to all accounts,+-- rather than a per-account one (depth:REGEX=N) ?+queryIsFlatDepth :: Query -> Bool+queryIsFlatDepth (Depth _) = True+queryIsFlatDepth _ = False++queryIsReal :: Query -> Bool+queryIsReal (Real _) = True+queryIsReal _ = False++queryIsAmt :: Query -> Bool+queryIsAmt (Amt{}) = True+queryIsAmt _ = False++queryIsCur :: Query -> Bool+queryIsCur (Cur _) = True+queryIsCur _ = False++queryIsAmtOrCur :: Query -> Bool+queryIsAmtOrCur = liftA2 (||) queryIsAmt queryIsCur++queryIsChange :: Query -> Bool+queryIsChange (Change{}) = True+queryIsChange _ = False++queryIsBalance :: Query -> Bool+queryIsBalance (Balance{}) = True+queryIsBalance _ = False++-- | Is this a change: or balance: term (a "row term", tested against a report row's summed amounts) ?+queryIsRowTerm :: Query -> Bool+queryIsRowTerm = liftA2 (||) queryIsChange queryIsBalance++-- | Does this query contain a balance: term anywhere (possibly negated) ?+-- Reports then need the postings before the report start, to know the balances.+queryHasBalance :: Query -> Bool+queryHasBalance = queryHasTerm queryIsBalance++-- | Does this query contain a change: term anywhere (possibly negated) ?+queryHasChange :: Query -> Bool+queryHasChange = queryHasTerm queryIsChange++-- | Does this query specify a start date and nothing else (that would+-- filter postings prior to the date) ?+-- When the flag is true, look for a starting secondary date instead.+queryIsStartDateOnly :: Bool -> Query -> Bool+queryIsStartDateOnly _ Any = False+queryIsStartDateOnly _ None = False+queryIsStartDateOnly secondary (Or ms) = all (queryIsStartDateOnly secondary) ms+queryIsStartDateOnly secondary (And ms) = all (queryIsStartDateOnly secondary) ms+queryIsStartDateOnly False (Date (DateSpan (Just _) _)) = True+queryIsStartDateOnly True (Date2 (DateSpan (Just _) _)) = True+queryIsStartDateOnly _ _ = False++-- | Does this query involve a property of transactions (or their postings),+-- making it inapplicable to account declarations ?+queryIsTransactionRelated :: Query -> Bool+queryIsTransactionRelated = matchesQuery (+ queryIsDate+ ||| queryIsDate2+ ||| queryIsStatus+ ||| queryIsCode+ ||| queryIsDesc+ ||| queryIsReal+ ||| queryIsAmt+ ||| queryIsCur+ )++(|||) :: (a->Bool) -> (a->Bool) -> (a->Bool)+p ||| q = \v -> p v || q v++-- * accessors++-- | What start date (or secondary date) does this query specify, if any ?+-- For OR expressions, use the earliest of the dates. NOT is ignored.+queryStartDate :: Bool -> Query -> Maybe Day+queryStartDate secondary (Or ms) = earliestMaybeDate $ map (queryStartDate secondary) ms+queryStartDate secondary (And ms) = latestMaybeDate $ map (queryStartDate secondary) ms+queryStartDate False (Date (DateSpan (Just d) _)) = Just $ fromEFDay d+queryStartDate True (Date2 (DateSpan (Just d) _)) = Just $ fromEFDay d+queryStartDate _ _ = Nothing++-- | What end date (or secondary date) does this query specify, if any ?+-- For OR expressions, use the latest of the dates. NOT is ignored.+queryEndDate :: Bool -> Query -> Maybe Day+queryEndDate secondary (Or ms) = latestMaybeDate' $ map (queryEndDate secondary) ms+queryEndDate secondary (And ms) = earliestMaybeDate' $ map (queryEndDate secondary) ms+queryEndDate False (Date (DateSpan _ (Just d))) = Just $ fromEFDay d+queryEndDate True (Date2 (DateSpan _ (Just d))) = Just $ fromEFDay d+queryEndDate _ _ = Nothing++queryTermDateSpan (Date spn) = Just spn+queryTermDateSpan _ = Nothing++-- | What date span (or with a true argument, what secondary date span) does this query specify ?+-- OR clauses specifying multiple spans return their union (the span enclosing all of them).+-- AND clauses specifying multiple spans return their intersection.+-- NOT clauses are ignored.+queryDateSpan :: Bool -> Query -> DateSpan+queryDateSpan secondary (Or qs) = spansUnion $ map (queryDateSpan secondary) qs+queryDateSpan secondary (And qs) = spansIntersect $ map (queryDateSpan secondary) qs+queryDateSpan _ (Date spn) = spn+queryDateSpan True (Date2 spn) = spn+queryDateSpan _ _ = nulldatespan++-- | What date span does this query specify, treating primary and secondary dates as equivalent ?+-- OR clauses specifying multiple spans return their union (the span enclosing all of them).+-- AND clauses specifying multiple spans return their intersection.+-- NOT clauses are ignored.+queryDateSpan' :: Query -> DateSpan+queryDateSpan' (Or qs) = spansUnion $ map queryDateSpan' qs+queryDateSpan' (And qs) = spansIntersect $ map queryDateSpan' qs+queryDateSpan' (Date spn) = spn+queryDateSpan' (Date2 spn) = spn+queryDateSpan' _ = nulldatespan++-- | What is the earliest of these dates, where Nothing is earliest ?+earliestMaybeDate :: [Maybe Day] -> Maybe Day+earliestMaybeDate = fromMaybe Nothing . minimumMay++-- | What is the latest of these dates, where Nothing is earliest ?+latestMaybeDate :: [Maybe Day] -> Maybe Day+latestMaybeDate = fromMaybe Nothing . maximumMay++-- | What is the earliest of these dates, where Nothing is the latest ?+earliestMaybeDate' :: [Maybe Day] -> Maybe Day+earliestMaybeDate' = fromMaybe Nothing . minimumMay . filter isJust++-- | What is the latest of these dates, where Nothing is the latest ?+latestMaybeDate' :: [Maybe Day] -> Maybe Day+latestMaybeDate' = fromMaybe Nothing . maximumByMay compareNothingMax+ where+ compareNothingMax Nothing Nothing = EQ+ compareNothingMax (Just _) Nothing = LT+ compareNothingMax Nothing (Just _) = GT+ compareNothingMax (Just a) (Just b) = compare a b++-- | The depth limit this query specifies, if it has one+queryDepth :: Query -> DepthSpec+queryDepth (Or qs) = foldMap queryDepth qs+queryDepth (And qs) = foldMap queryDepth qs+queryDepth (Depth d) = DepthSpec (Just d) []+queryDepth (DepthAcct r d) = DepthSpec Nothing [(r,d)]+queryDepth _ = mempty++-- | The account we are currently focussed on, if any, and whether subaccounts are included.+-- Just looks at the first query option.+inAccount :: [QueryOpt] -> Maybe (AccountName,Bool)+inAccount [] = Nothing+inAccount (QueryOptInAcctOnly a:_) = Just (a,False)+inAccount (QueryOptInAcct a:_) = Just (a,True)+inAccount (QueryOptInterval _:rest) = inAccount rest++-- | A query for the account(s) we are currently focussed on, if any.+-- Just looks at the first query option.+inAccountQuery :: [QueryOpt] -> Maybe Query+inAccountQuery [] = Nothing+inAccountQuery (QueryOptInAcctOnly a : _) = Just . Acct $ accountNameToAccountOnlyRegex a+inAccountQuery (QueryOptInAcct a : _) = Just . Acct $ accountNameToAccountRegex a+inAccountQuery (QueryOptInterval _ : rest) = inAccountQuery rest++-- -- | Convert a query to its inverse.+-- negateQuery :: Query -> Query+-- negateQuery = Not++-- matching things with queries++matchesCommodity :: Query -> CommoditySymbol -> Bool+matchesCommodity (Cur r) s = regexMatchText r s+matchesCommodity (Find r _) s = regexMatchText r s+matchesCommodity (Any) _ = True+matchesCommodity (None) _ = False+matchesCommodity (Or qs) s = any (`matchesCommodity` s) qs+matchesCommodity (And qs) s = all (`matchesCommodity` s) qs+matchesCommodity (AnyPosting qs) s = all (`matchesCommodity` s) qs+matchesCommodity (AllPostings qs) s = all1 (`matchesCommodity` s) qs+matchesCommodity _ _ = False++-- | Like matchesCommodity, but also supporting Tag queries,+-- using the provided function to look up a commodity's tags.+matchesCommodityExtra :: (CommoditySymbol -> [Tag]) -> Query -> CommoditySymbol -> Bool+matchesCommodityExtra ctags (Not q) c = not $ matchesCommodityExtra ctags q c+matchesCommodityExtra ctags (Or qs) c = any (\q -> matchesCommodityExtra ctags q c) qs+matchesCommodityExtra ctags (And qs) c = all (\q -> matchesCommodityExtra ctags q c) qs+matchesCommodityExtra ctags (AnyPosting qs) c = all (\q -> matchesCommodityExtra ctags q c) qs+matchesCommodityExtra ctags (AllPostings qs) c = all1 (\q -> matchesCommodityExtra ctags q c) qs+matchesCommodityExtra ctags (Tag npat vpat) c = patternsMatchTags npat vpat $ ctags c+matchesCommodityExtra _ q c = matchesCommodity q c++-- | Does the match expression match this (simple) amount ?+matchesAmount :: Query -> Amount -> Bool+matchesAmount (Not q) a = not $ q `matchesAmount` a+matchesAmount (Any) _ = True+matchesAmount (None) _ = False+matchesAmount (Or qs) a = any (`matchesAmount` a) qs+matchesAmount (And qs) a = all (`matchesAmount` a) qs+matchesAmount (AnyPosting qs) a = all (`matchesAmount` a) qs+matchesAmount (AllPostings qs) a = all1 (`matchesAmount` a) qs+matchesAmount (Amt ord n mc) a = maybe True (== acommodity a) mc && compareAmount ord n a+matchesAmount (Cur r) a = matchesCommodity (Cur r) (acommodity a)+matchesAmount _ _ = True++-- | Is this amount's quantity less than, greater than, equal to, or unsignedly equal to this number ?+compareAmount :: OrdPlus -> Quantity -> Amount -> Bool+compareAmount ord q Amount{aquantity=aq} = case ord of Lt -> aq < q+ LtEq -> aq <= q+ Gt -> aq > q+ GtEq -> aq >= q+ Eq -> aq == q+ AbsLt -> abs aq < abs q+ AbsLtEq -> abs aq <= abs q+ AbsGt -> abs aq > abs q+ AbsGtEq -> abs aq >= abs q+ AbsEq -> abs aq == abs q++-- | Do the change: and balance: terms of this query match a report row (or an entry)+-- with this change and this balance ? Each term matches like an amt: term does+-- (see 'matchesMixedAmount'): if any commodity's total amount, or with a commodity symbol,+-- that commodity's total, passes the comparison. Costs are ignored, so amounts in one+-- commodity at different costs are combined (they are kept apart in a MixedAmount).+-- Other kinds of query term are ignored.+matchesRowAmounts :: Query -> MixedAmount -> MixedAmount -> Bool+matchesRowAmounts (Not q) chg bal | isRowTerm q = not $ matchesRowAmounts q chg bal+matchesRowAmounts (And qs) chg bal = all (\q -> matchesRowAmounts q chg bal) qs+matchesRowAmounts (Change ord n mc) chg _ = Amt ord n mc `matchesMixedAmount` mixedAmountStripCosts chg+matchesRowAmounts (Balance ord n mc) _ bal = Amt ord n mc `matchesMixedAmount` mixedAmountStripCosts bal+matchesRowAmounts _ _ _ = True++-- | Does the query match this mixed amount ? It does if it matches any of the+-- (single-commodity) amounts in it, or for an empty mixed amount, a zero amount.+matchesMixedAmount :: Query -> MixedAmount -> Bool+matchesMixedAmount q ma = case amountsRaw ma of+ [] -> q `matchesAmount` nullamt+ as -> any (q `matchesAmount`) as++-- | Does the query match this account name ?+-- Only acct: and depth: terms can match; any other term (a date:, desc: etc.)+-- fails to match, since an account name on its own has no such properties.+-- (For matching type: and tag: terms against an account's other data,+-- see matchesAccountExtra.)+matchesAccount :: Query -> AccountName -> Bool+matchesAccount (Any) _ = True+matchesAccount (None) _ = False+matchesAccount (Not m) a = not $ matchesAccount m a+matchesAccount (Or ms) a = any (`matchesAccount` a) ms+matchesAccount (And ms) a = all (`matchesAccount` a) ms+matchesAccount (AnyPosting qs) a = all (`matchesAccount` a) qs+matchesAccount (AllPostings qs) a = all1 (`matchesAccount` a) qs+matchesAccount (Acct r) a = regexMatchText r a+matchesAccount (Find r _) a = regexMatchText r a+matchesAccount (Depth d) a = accountNameLevel a <= d+matchesAccount (DepthAcct r d) a = accountNameLevel a <= d || not (regexMatchText r a)+matchesAccount _ _ = False++-- | Like matchesAccount, but with optional extra matching features:+--+-- - If the account's type is provided, any type: terms in the query+-- must match it (and any negated type: terms must not match it).+--+-- - If the account's tags are provided, any tag: terms must match+-- at least one of them (and any negated tag: terms must match none).+--+matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool+matchesAccountExtra atypes atags (Not q ) a = not $ matchesAccountExtra atypes atags q a+matchesAccountExtra atypes atags (Or qs ) a = any (\q -> matchesAccountExtra atypes atags q a) qs+matchesAccountExtra atypes atags (And qs ) a = all (\q -> matchesAccountExtra atypes atags q a) qs+matchesAccountExtra atypes atags (AnyPosting qs ) a = all (\q -> matchesAccountExtra atypes atags q a) qs+matchesAccountExtra atypes atags (AllPostings qs ) a = all1 (\q -> matchesAccountExtra atypes atags q a) qs+matchesAccountExtra atypes _ (Type ts) a = maybe False (\t -> any (t `isAccountSubtypeOf`) ts) $ atypes a+matchesAccountExtra _ atags (Tag npat vpat) a = patternsMatchTags npat vpat $ atags a+matchesAccountExtra _ _ q a = matchesAccount q a++-- | Test a posting against the subqueries of an any: or all: query, with the+-- given posting matcher. The subqueries are tested against the postings of+-- this posting's parent transaction, so that a posting can be matched because+-- of its siblings. The selector function selects the any: or all: sense, ie whether+-- any one of those postings must match, or all of them (requiring at least one).+-- Postings generated by hledger may have no parent transaction; for those,+-- only the posting itself is tested, making any: and all: behave like expr:.+matchesSiblingPostings+ :: ((Posting -> Bool) -> [Posting] -> Bool)+ -- ^ selector fn: which sibling postings (including p) must match: 'any' for any:, or 'all1' for all:+ -> (Query -> Posting -> Bool)+ -- ^ match fn: how to test one subquery against one posting: 'matchesPosting',+ -- or 'matchesPostingExtra' with its account type lookup applied+ -> [Query]+ -- ^ qs: the any:/all: subqueries, which must all match the same posting+ -> Posting+ -- ^ p: the posting being tested+ -> Bool+matchesSiblingPostings selector matchfn qs p =+ selector (\p' -> all (`matchfn` p') qs) postingandsiblings+ where+ postingandsiblings = maybe [p] tpostings $ ptransaction p++-- | Does the match expression match this posting ?+-- When matching account name, and the posting has been transformed+-- in some way, we will match either the original or transformed name.+matchesPosting :: Query -> Posting -> Bool+matchesPosting (Not q) _ | isRowTerm q = True -- change:/balance: terms match report rows, not postings+matchesPosting (Not q) p = not $ q `matchesPosting` p+matchesPosting (Any) _ = True+matchesPosting (None) _ = False+matchesPosting (Or qs) p = any (`matchesPosting` p) qs+matchesPosting (And qs) p = all (`matchesPosting` p) qs+matchesPosting (AnyPosting qs) p = matchesSiblingPostings any matchesPosting qs p+matchesPosting (AllPostings qs) p = matchesSiblingPostings all1 matchesPosting qs p+matchesPosting (Code r) p = maybe False (regexMatchText r . tcode) $ ptransaction p+matchesPosting (Desc r) p = maybe False (regexMatchText r . tdescription) $ ptransaction p+matchesPosting (Acct r) p = matches p || maybe False matches (poriginal p) where matches = regexMatchText r . paccount+matchesPosting (Find r mspan) p = findMatchesPosting r mspan p+matchesPosting (Date spn) p = spn `spanContainsDate` postingDate p+matchesPosting (Date2 spn) p = spn `spanContainsDate` postingDate2 p+matchesPosting (StatusQ s) p = postingStatus p == s+matchesPosting (Real v) p = v == isReal p+matchesPosting q@(Depth _) Posting{paccount=a} = q `matchesAccount` a+matchesPosting q@(DepthAcct _ _) Posting{paccount=a} = q `matchesAccount` a+matchesPosting q@(Amt{}) Posting{pamount=as} = q `matchesMixedAmount` as+matchesPosting (Cur r) Posting{pamount=as} = any (matchesCommodity (Cur r) . acommodity) $ amountsRaw as+matchesPosting (Tag n v) p = case (reString n, v) of+ ("payee", Just v') -> maybe False (regexMatchText v' . transactionPayee) $ ptransaction p+ ("note", Just v') -> maybe False (regexMatchText v' . transactionNote) $ ptransaction p+ (_, mv) -> patternsMatchTags n mv $ postingAllTags p+matchesPosting (Type _) _ = False+matchesPosting (Change{}) _ = True+matchesPosting (Balance{}) _ = True++-- | Like matchesPosting, but if the posting's account's type is provided,+-- any type: terms in the query must match it (and any negated type: terms+-- must not match it).+matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool+matchesPostingExtra _ (Not q ) _ | isRowTerm q = True+matchesPostingExtra atype (Not q ) p = not $ matchesPostingExtra atype q p+matchesPostingExtra atype (Or qs) p = any (\q -> matchesPostingExtra atype q p) qs+matchesPostingExtra atype (And qs) p = all (\q -> matchesPostingExtra atype q p) qs+matchesPostingExtra atype (AnyPosting qs) p = matchesSiblingPostings any (matchesPostingExtra atype) qs p+matchesPostingExtra atype (AllPostings qs) p = matchesSiblingPostings all1 (matchesPostingExtra atype) qs p+matchesPostingExtra atype (Type ts) p =+ -- does posting's account's type, if we can detect it, match any of the given types ?+ (maybe False (\t -> any (t `isAccountSubtypeOf`) ts) . atype $ paccount p)+ -- or, try the same test with the original (pre-aliasing/pivoting) posting's account+ || (fromMaybe False $ do+ porig <- poriginal p+ let a = paccount porig+ t <- atype a+ Just $ any (t `isAccountSubtypeOf`) ts+ )+matchesPostingExtra _ q p = matchesPosting q p++-- | Partially evaluate a posting query, for postings to this account+-- (and with this different original account name, from before aliasing or pivoting, if any).+-- Its account terms (acct:, type:, depth:) are decided as 'matchesPostingExtra' would decide them,+-- becoming Any or None, and simplified away; the rest of the query is kept+-- (including any: and all: terms, which test sibling postings, and find: terms).+-- So for any posting p with these account names,+-- @matchesPostingExtra atype (postingQueryForAccount atype a morig q) p == matchesPostingExtra atype q p@.+-- This lets the account terms be tested once per account, rather than once per posting;+-- checking assert rules uses it this way (see "Hledger.Data.JournalChecks.Assert").+postingQueryForAccount :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe AccountName -> Query -> Query+postingQueryForAccount atype a morig = go+ where+ go (Not q) | isRowTerm q = Any -- as in matchesPosting+ | otherwise = notQ $ go q+ go (And qs) = andQ $ map go qs+ go (Or qs) = orQ $ map go qs+ go (Acct r) = boolQ $ eitherAccount (regexMatchText r)+ go (Type ts) = boolQ $ eitherAccount $ maybe False (\t -> any (t `isAccountSubtypeOf`) ts) . atype+ go q@(Depth _) = boolQ $ matchesAccount q a+ go q@(DepthAcct _ _) = boolQ $ matchesAccount q a+ go q = q+ eitherAccount f = f a || maybe False f morig+ boolQ b = if b then Any else None+ notQ Any = None+ notQ None = Any+ notQ q = Not q+ andQ qs | None `elem` qs = None+ | otherwise = case filter (/= Any) qs of+ [] -> Any+ [q] -> q+ qs' -> And qs'+ orQ qs | Any `elem` qs = Any+ | otherwise = case filter (/= None) qs of+ [] -> None+ [q] -> q+ qs' -> Or qs'++-- | Does the match expression match this transaction ?+-- change:/balance: terms are ignored; reports apply them to entries' amounts (see Hledger.Reports.EntriesReport).+matchesTransaction :: Query -> Transaction -> Bool+matchesTransaction (Not q) _ | isRowTerm q = True+matchesTransaction (Not q) t = not $ q `matchesTransaction` t+matchesTransaction (Any) _ = True+matchesTransaction (None) _ = False+matchesTransaction (Or qs) t = any (`matchesTransaction` t) qs+matchesTransaction (And qs) t = all (`matchesTransaction` t) qs+matchesTransaction (AnyPosting qs) t = any (\p -> all (`matchesPosting` p) qs) $ tpostings t+matchesTransaction (AllPostings qs) t = all1 (\p -> all (`matchesPosting` p) qs) $ tpostings t+matchesTransaction (Code r) t = regexMatchText r $ tcode t+matchesTransaction (Desc r) t = regexMatchText r $ tdescription t+matchesTransaction q@(Acct _) t = any (q `matchesPosting`) $ tpostings t+matchesTransaction (Find r mspan) t = findMatchesTransaction r mspan t+matchesTransaction (Date spn) t = spanContainsDate spn $ tdate t+matchesTransaction (Date2 spn) t = spanContainsDate spn $ transactionDate2 t+matchesTransaction (StatusQ s) t = tstatus t == s+matchesTransaction (Real v) t = v == hasRealPostings t+matchesTransaction q@(Amt{}) t = any (q `matchesPosting`) $ tpostings t+matchesTransaction q@(Depth _) t = any (q `matchesPosting`) $ tpostings t+matchesTransaction q@(DepthAcct _ _) t = any (q `matchesPosting`) $ tpostings t+matchesTransaction q@(Cur _) t = any (q `matchesPosting`) $ tpostings t+matchesTransaction (Tag n v) t = case (reString n, v) of+ ("payee", Just v') -> regexMatchText v' $ transactionPayee t+ ("note", Just v') -> regexMatchText v' $ transactionNote t+ (_, v') -> patternsMatchTags n v' $ transactionAllTags t+matchesTransaction (Type _) _ = False+matchesTransaction (Change{}) _ = True+matchesTransaction (Balance{}) _ = True++-- | Like matchesTransaction, but if the journal's account types are provided,+-- any type: terms in the query must match at least one posting's account type+-- (and any negated type: terms must match none).+matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool+matchesTransactionExtra _ (Not q) _ | isRowTerm q = True+matchesTransactionExtra atype (Not q) t = not $ matchesTransactionExtra atype q t+matchesTransactionExtra atype (Or qs) t = any (\q -> matchesTransactionExtra atype q t) qs+matchesTransactionExtra atype (And qs) t = all (\q -> matchesTransactionExtra atype q t) qs+matchesTransactionExtra atype (AnyPosting qs) t = any (\p -> all (\q -> matchesPostingExtra atype q p) qs) $ tpostings t+matchesTransactionExtra atype (AllPostings qs) t = all1 (\p -> all (\q -> matchesPostingExtra atype q p) qs) $ tpostings t+matchesTransactionExtra atype q@(Type _) t = any (matchesPostingExtra atype q) $ tpostings t+matchesTransactionExtra _ q t = matchesTransaction q t++-- | Does the query match this payee ?+-- Only payee: terms can match; any other term (a desc:, date:, acct: etc.)+-- fails to match, since a payee on its own has no such properties.+matchesPayee :: Query -> Payee -> Bool+matchesPayee (Not q) p = not $ q `matchesPayee` p+matchesPayee (Any) _ = True+matchesPayee (None) _ = False+matchesPayee (Or qs) p = any (`matchesPayee` p) qs+matchesPayee (And qs) p = all (`matchesPayee` p) qs+matchesPayee (AnyPosting qs) p = all (`matchesPayee` p) qs+matchesPayee (AllPostings qs) p = all1 (`matchesPayee` p) qs+matchesPayee (Tag n (Just v)) p | reString n == "payee" = regexMatchText v p -- handles payee: and tag:payee= queries+matchesPayee (Find r _) p = regexMatchText r p+matchesPayee _ _ = False++-- | Does a find: query match this posting ? It does if its regexp matches any of+-- the posting's text fields or its parent transaction's text fields (see+-- 'postingFindTexts', 'transactionFindTexts'), or if its date span, if any,+-- contains the posting's date.+findMatchesPosting :: Regexp -> Maybe DateSpan -> Posting -> Bool+findMatchesPosting r mspan p =+ maybe False (`spanContainsDate` postingDate p) mspan+ || any (regexMatchText r) (postingFindTexts p ++ maybe [] transactionFindTexts (ptransaction p))++-- | Does a find: query match this transaction ? It does if its regexp matches any of+-- the transaction's text fields or any of its postings' text fields (see+-- 'transactionFindTexts', 'postingFindTexts'), or if its date span, if any,+-- contains the transaction's date.+findMatchesTransaction :: Regexp -> Maybe DateSpan -> Transaction -> Bool+findMatchesTransaction r mspan t =+ maybe False (`spanContainsDate` tdate t) mspan+ || any (regexMatchText r) (transactionFindTexts t ++ concatMap postingFindTexts (tpostings t))++-- | The text fields of a posting which a find: query searches:+-- the account name (and the original account name, if the posting has been transformed),+-- the comment, the names and values of all its tags (including hidden ones,+-- and those inherited from account declarations), and the amount as displayed on one line.+-- The amount is last, since rendering it costs the most.+postingFindTexts :: Posting -> [Text]+postingFindTexts p =+ paccount p : maybe [] (pure . paccount) (poriginal p)+ ++ pcomment p : tagTexts (ptags p)+ ++ [T.pack $ showMixedAmountOneLine $ pamount p]++-- | The text fields of a transaction (not including its postings) which a find: query searches:+-- the description, code, comment, and the names and values of all its tags.+transactionFindTexts :: Transaction -> [Text]+transactionFindTexts t = tdescription t : tcode t : tcomment t : tagTexts (ttags t)++-- | The names and values of these tags, as separate texts.+tagTexts :: [Tag] -> [Text]+tagTexts = concatMap (\(n,v) -> [n,v])++-- | Do this name regex and optional value regex match the name and value of any of these tags ?+patternsMatchTags :: Regexp -> Maybe Regexp -> [Tag] -> Bool+patternsMatchTags namepat valuepat = any (matches namepat valuepat)+ where+ matches npat vpat (n,v) = regexMatchText npat n && maybe (const True) regexMatchText vpat v++-- | Does the query match the name and optionally the value of this tag ?+-- Non-tag: query terms are ignored (this might disrupt some boolean queries).+matchesTag :: Query -> Tag -> Bool+matchesTag (Not q) t = not $ q `matchesTag` t+matchesTag (Any) _ = True+matchesTag (None) _ = False+matchesTag (Or qs) t = any (`matchesTag` t) $ filter queryIsTag qs+matchesTag (And qs) t = all (`matchesTag` t) $ filter queryIsTag qs+matchesTag (AnyPosting qs) t = all (`matchesTag` t) $ filter queryIsTag qs+matchesTag (AllPostings qs) t = all1 (`matchesTag` t) $ filter queryIsTag qs+matchesTag (Tag npat mvpat) t = patternsMatchTags npat mvpat [t]+matchesTag _ _ = False++-- | Does the query match this market price ?+matchesPriceDirective :: Query -> PriceDirective -> Bool+matchesPriceDirective (None) _ = False+matchesPriceDirective (Not q) p = not $ matchesPriceDirective q p+matchesPriceDirective (Or qs) p = any (`matchesPriceDirective` p) qs+matchesPriceDirective (And qs) p = all (`matchesPriceDirective` p) qs+matchesPriceDirective (AnyPosting qs) p = all (`matchesPriceDirective` p) qs+matchesPriceDirective (AllPostings qs) p = all1 (`matchesPriceDirective` p) qs+matchesPriceDirective q@(Amt{}) p = matchesAmount q (pdamount p)+matchesPriceDirective q@(Cur _) p = matchesCommodity q (pdcommodity p)+matchesPriceDirective (Date spn) p = spanContainsDate spn (pddate p)+matchesPriceDirective (Find r mspan) p = findMatchesPriceDirective r mspan p+matchesPriceDirective _ _ = True++-- | Does a find: query match this price directive ? It does if its regexp matches+-- the directive's commodity symbol or price amount (as displayed),+-- or if its date span, if any, contains the directive's date.+findMatchesPriceDirective :: Regexp -> Maybe DateSpan -> PriceDirective -> Bool+findMatchesPriceDirective r mspan PriceDirective{pddate, pdcommodity, pdamount} =+ maybe False (`spanContainsDate` pddate) mspan+ || any (regexMatchText r) [pdcommodity, T.pack $ showAmountWithZeroCommodity pdamount]+++-- tests++tests_Query = testGroup "Query" [+ testCase "simplifyQuery" $ do+ (simplifyQuery $ Or [Acct $ toRegex' "a"]) @?= (Acct $ toRegex' "a")+ (simplifyQuery $ Or [Any,None]) @?= (Any)+ (simplifyQuery $ And [Any,None]) @?= (None)+ (simplifyQuery $ And [Any,Any]) @?= (Any)+ (simplifyQuery $ And [Acct $ toRegex' "b",Any]) @?= (Acct $ toRegex' "b")+ (simplifyQuery $ And [Any,And [Date (DateSpan Nothing Nothing)]]) @?= (Any)+ (simplifyQuery $ And [Date (DateSpan Nothing (Just $ Exact $ fromGregorian 2013 01 01)), Date (DateSpan (Just $ Exact $ fromGregorian 2012 01 01) Nothing)])+ @?= (Date (DateSpan (Just $ Exact $ fromGregorian 2012 01 01) (Just $ Exact $ fromGregorian 2013 01 01)))+ (simplifyQuery $ And [Or [],Or [Desc $ toRegex' "b b"]]) @?= (Desc $ toRegex' "b b")++ ,testCase "parseQuery" $ do+ (parseQuery nulldate "acct:'expenses:autres d\233penses' desc:b") @?= Right (And [Acct $ toRegexCI' "expenses:autres d\233penses", Desc $ toRegexCI' "b"], [])+ parseQuery nulldate "inacct:a desc:\"b b\"" @?= Right (Desc $ toRegexCI' "b b", [QueryOptInAcct "a"])+ parseQuery nulldate "inacct:a inacct:b" @?= Right (Any, [QueryOptInAcct "a", QueryOptInAcct "b"])+ parseQuery nulldate "desc:'x x'" @?= Right (Desc $ toRegexCI' "x x", [])+ parseQuery nulldate "'a a' 'b" @?= Right (Or [Acct $ toRegexCI' "a a",Acct $ toRegexCI' "'b"], [])+ parseQuery nulldate "\"" @?= Right (Acct $ toRegexCI' "\"", [])+ parseQuery nulldate "find:a" @?= Right (Find (toRegexCI' "a") Nothing, [])+ parseQuery nulldate "::a ::b" @?= Right (And [Find (toRegexCI' "a") Nothing, Find (toRegexCI' "b") Nothing], [])+ parseQuery nulldate "not:::'a b'" @?= Right (Not $ Find (toRegexCI' "a b") Nothing, [])+ parseQuery nulldate "::2024" @?= Right (Find (toRegexCI' "2024") (Just $ DateSpan (Just $ Flex $ fromGregorian 2024 1 1) (Just $ Flex $ fromGregorian 2025 1 1)), [])++ ,testCase "parseBooleanQuery" $ do+ parseBooleanQuery nulldate "(tag:'atag=a')" @?= Right (Tag (toRegexCI' "atag") (Just $ toRegexCI' "a"), [])+ parseBooleanQuery nulldate "( tag:\"atag=a\" )" @?= Right (Tag (toRegexCI' "atag") (Just $ toRegexCI' "a"), [])+ parseBooleanQuery nulldate "(acct:'expenses:food')" @?= Right (Acct $ toRegexCI' "expenses:food", [])+ parseBooleanQuery nulldate "(((acct:'expenses:food')))" @?= Right (Acct $ toRegexCI' "expenses:food", [])+ parseBooleanQuery nulldate "acct:'expenses:food' AND desc:'b'" @?= Right (And [Acct $ toRegexCI' "expenses:food", Desc $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate "((desc:'a') AND (desc:'b') OR (desc:'c'))" @?= Right (Or [And [Desc $ toRegexCI' "a", Desc $ toRegexCI' "b"], Desc $ toRegexCI' "c"], [])+ parseBooleanQuery nulldate "((desc:'a') OR (desc:'b') AND (desc:'c'))" @?= Right (Or [Desc $ toRegexCI' "a", And [Desc $ toRegexCI' "b", Desc $ toRegexCI' "c"]], [])+ parseBooleanQuery nulldate "((desc:'a') AND desc:'b' AND (desc:'c'))" @?= Right (And [Desc $ toRegexCI' "a", Desc $ toRegexCI' "b", Desc $ toRegexCI' "c"], [])+ parseBooleanQuery nulldate "(NOT (desc:'a') AND (desc:'b'))" @?= Right (And [Not $ Desc $ toRegexCI' "a", Desc $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate "((desc:'a') AND (NOT desc:'b'))" @?= Right (And [Desc $ toRegexCI' "a", Not $ Desc $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate "(desc:'a' AND desc:'b')" @?= Right (And [Desc $ toRegexCI' "a", Desc $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate "(acct:'a' acct:'b')" @?= Right (Or [Acct $ toRegexCI' "a", Acct $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate " acct:'a' acct:'b'" @?= Right (Or [Acct $ toRegexCI' "a", Acct $ toRegexCI' "b"], [])+ parseBooleanQuery nulldate "not:a" @?= Right (Not $ Acct $ toRegexCI' "a", [])+ parseBooleanQuery nulldate "expenses:food OR (tag:A expenses:drink)" @?= Right (Or [Acct $ toRegexCI' "expenses:food", And [Acct $ toRegexCI' "expenses:drink", Tag (toRegexCI' "A") Nothing]], [])+ parseBooleanQuery nulldate "not a" @?= Right (Not $ Acct $ toRegexCI' "a", [])+ parseBooleanQuery nulldate "nota" @?= Right (Acct $ toRegexCI' "nota", [])+ parseBooleanQuery nulldate "not (acct:a)" @?= Right (Not $ Acct $ toRegexCI' "a", [])++ ,testCase "words''" $ do+ (words'' [] "a b") @?= ["a","b"]+ (words'' [] "'a b'") @?= ["a b"]+ (words'' [] "not:a b") @?= ["not:a","b"]+ (words'' [] "not:'a b'") @?= ["not:a b"]+ (words'' [] "'not:a b'") @?= ["not:a b"]+ (words'' ["desc:"] "not:desc:'a b'") @?= ["not:desc:a b"]+ (words'' queryprefixes "\"acct:expenses:autres d\233penses\"") @?= ["acct:expenses:autres d\233penses"]+ (words'' queryprefixes "\"") @?= ["\""]++ ,testCase "filterQuery" $ do+ filterQuery queryIsDepth Any @?= Any+ filterQuery queryIsDepth (Depth 1) @?= Depth 1+ filterQuery (not.queryIsDepth) (And [And [StatusQ Cleared,Depth 1]]) @?= StatusQ Cleared+ filterQuery queryIsDepth (And [Date nulldatespan, Not (Or [Any, Depth 1])]) @?= Any -- XXX unclear++ ,testCase "parseQueryTerm" $ do+ parseQueryTerm nulldate "a" @?= Right (Acct $ toRegexCI' "a", [])+ parseQueryTerm nulldate "acct:expenses:autres d\233penses" @?= Right (Acct $ toRegexCI' "expenses:autres d\233penses", [])+ parseQueryTerm nulldate "not:desc:a b" @?= Right (Not $ Desc $ toRegexCI' "a b", [])+ parseQueryTerm nulldate "status:1" @?= Right (StatusQ Cleared, [])+ parseQueryTerm nulldate "status:*" @?= Right (StatusQ Cleared, [])+ parseQueryTerm nulldate "status:!" @?= Right (StatusQ Pending, [])+ parseQueryTerm nulldate "status:0" @?= Right (StatusQ Unmarked, [])+ parseQueryTerm nulldate "status:" @?= Right (StatusQ Unmarked, [])+ parseQueryTerm nulldate "payee:x" @?= (,[]) <$> payeeTag (Just "x")+ parseQueryTerm nulldate "note:x" @?= (,[]) <$> noteTag (Just "x")+ parseQueryTerm nulldate "real:1" @?= Right (Real True, [])+ parseQueryTerm nulldate "date:2008" @?= Right (Date $ DateSpan (Just $ Flex $ fromGregorian 2008 01 01) (Just $ Flex $ fromGregorian 2009 01 01), [])+ parseQueryTerm nulldate "date:from 2012/5/17" @?= Right (Date $ DateSpan (Just $ Exact $ fromGregorian 2012 05 17) Nothing, [])+ parseQueryTerm nulldate "date:20180101-201804" @?= Right (Date $ DateSpan (Just $ Exact $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 04 01), [])+ parseQueryTerm nulldate "inacct:a" @?= Right (Any, [QueryOptInAcct "a"])+ parseQueryTerm nulldate "tag:a" @?= Right (Tag (toRegexCI' "a") Nothing, [])+ parseQueryTerm nulldate "tag:a=some value" @?= Right (Tag (toRegexCI' "a") (Just $ toRegexCI' "some value"), [])+ parseQueryTerm nulldate "amt:<0" @?= Right (Amt Lt 0 Nothing, [])+ parseQueryTerm nulldate "amt:>10000.10" @?= Right (Amt AbsGt 10000.1 Nothing, [])+ parseQueryTerm nulldate "amt:>$100" @?= Right (Amt AbsGt 100 (Just "$"), [])+ parseQueryTerm nulldate "change:<-100 EUR" @?= Right (Change Lt (-100) (Just "EUR"), [])+ parseQueryTerm nulldate "balance:>=+1000" @?= Right (Balance GtEq 1000 Nothing, [])++ ,testCase "parseAmountQueryTerm" $ do+ parseAmountQueryTerm "<0" @?= Right (Lt,0) -- special case for convenience, since AbsLt 0 would be always false+ parseAmountQueryTerm ">0" @?= Right (Gt,0) -- special case for convenience and consistency with above+ parseAmountQueryTerm " > - 0 " @?= Right (Gt,0) -- accept whitespace around the argument parts+ parseAmountQueryTerm ">10000.10" @?= Right (AbsGt,10000.1)+ parseAmountQueryTerm "=0.23" @?= Right (AbsEq,0.23)+ parseAmountQueryTerm "0.23" @?= Right (AbsEq,0.23)+ parseAmountQueryTerm "<=+0.23" @?= Right (LtEq,0.23)+ parseAmountQueryTerm "-0.23" @?= Right (Eq,(-0.23))+ assertLeft $ parseAmountQueryTerm "-0,23"+ assertLeft $ parseAmountQueryTerm "=.23"++ ,testCase "parseAmountQueryArg" $ do+ parseAmountQueryArg "change" ">100" @?= Right (AbsGt,100,Nothing)+ parseAmountQueryArg "change" "<0" @?= Right (Lt,0,Nothing)+ parseAmountQueryArg "change" "0" @?= Right (AbsEq,0,Nothing)+ parseAmountQueryArg "change" ">=+100" @?= Right (GtEq,100,Nothing)+ parseAmountQueryArg "change" "<-100" @?= Right (Lt,-100,Nothing)+ parseAmountQueryArg "change" ">$100" @?= Right (AbsGt,100,Just "$")+ parseAmountQueryArg "change" ">-$100" @?= Right (Gt,-100,Just "$")+ parseAmountQueryArg "change" ">$-100" @?= Right (Gt,-100,Just "$")+ parseAmountQueryArg "change" "> 100 EUR" @?= Right (AbsGt,100,Just "EUR")+ parseAmountQueryArg "change" ">100EUR" @?= Right (AbsGt,100,Just "EUR")+ parseAmountQueryArg "change" "<EUR 100.5" @?= Right (AbsLt,100.5,Just "EUR")+ parseAmountQueryArg "change" "=\"A B\" -5" @?= Right (Eq,-5,Just "A B")+ parseAmountQueryArg "change" "5 \"A B\"" @?= Right (AbsEq,5,Just "A B")+ assertLeft $ parseAmountQueryArg "change" ""+ assertLeft $ parseAmountQueryArg "change" ">$"+ assertLeft $ parseAmountQueryArg "change" ">-$-100"+ assertLeft $ parseAmountQueryArg "change" ">1,000"++ ,testCase "querySplitRowTerms" $ do+ let c1 = Change AbsGt 1 Nothing+ b1 = Balance Lt 0 Nothing+ a = Acct $ toRegexCI' "a"+ querySplitRowTerms (And [a, c1]) @?= Right (c1, a)+ querySplitRowTerms (And [a, Not c1, b1]) @?= Right (And [Not c1, b1], a)+ querySplitRowTerms c1 @?= Right (c1, Any)+ querySplitRowTerms a @?= Right (Any, a)+ assertLeft $ querySplitRowTerms (Or [a, c1])+ assertLeft $ querySplitRowTerms (Not (And [a, b1]))+ assertLeft $ querySplitRowTerms (AnyPosting [c1])+ assertLeft $ parseQuery nulldate "expr:'change:>1 or a'"+ assertRight $ parseQuery nulldate "expr:'not balance:>1 and a'"+ assertBool "" $ queryHasBalance (And [a, Not b1])+ assertBool "" $ not $ queryHasBalance (And [a, c1])++ ,testCase "matchesRowAmounts" $ do+ let c ord n = Change ord n Nothing+ b ord n = Balance ord n Nothing+ eur = Just "EUR"+ usd2 = mixedAmount $ usd 2+ mixed = mixedAmount (usd 200) <> mixedAmount nullamt{acommodity="EUR", aquantity=1}+ chg `and'` bal = (chg, bal)+ matches q (chg, bal) = matchesRowAmounts q chg bal+ assertBool "" $ matches (c AbsGt 1) (mixedAmount (usd (-2)) `and'` nullmixedamt)+ assertBool "" $ not $ matches (c Gt 1) (mixedAmount (usd (-2)) `and'` nullmixedamt)+ assertBool "" $ matches (c AbsEq 0) (nullmixedamt `and'` usd2)+ assertBool "" $ matches (b Lt 0) (usd2 `and'` mixedAmount (usd (-5))) -- balance: tests the balance, not the change+ assertBool "" $ not $ matches (b Lt 0) (mixedAmount (usd (-5)) `and'` usd2)+ assertBool "" $ matches (c AbsGt 100) (mixed `and'` nullmixedamt) -- multi-commodity: matches if any part does+ assertBool "" $ not $ matches (c AbsGt 1000) (mixed `and'` nullmixedamt)+ assertBool "" $ not $ matches (Change AbsGt 100 eur) (mixed `and'` nullmixedamt) -- with a symbol, just that commodity's part+ assertBool "" $ matches (Change AbsLt 100 eur) (mixed `and'` nullmixedamt)+ assertBool "" $ not $ matches (Change AbsLt 100 eur) (usd2 `and'` nullmixedamt) -- no amount in that commodity: no match+ assertBool "" $ not $ matches (Not $ c AbsGt 1) (usd2 `and'` nullmixedamt)+ assertBool "" $ matches (And [c Gt 1, b Lt 3]) (usd2 `and'` usd2)+ assertBool "" $ not $ matches (And [c Gt 1, b Gt 3]) (usd2 `and'` usd2)+ assertBool "" $ matches Any (usd2 `and'` usd2)++ ,testCase "queryStartDate" $ do+ let small = Just $ fromGregorian 2000 01 01+ big = Just $ fromGregorian 2000 01 02+ queryStartDate False (And [Date $ DateSpan (Exact <$> small) Nothing, Date $ DateSpan (Exact <$> big) Nothing]) @?= big+ queryStartDate False (And [Date $ DateSpan (Exact <$> small) Nothing, Date $ DateSpan Nothing Nothing]) @?= small+ queryStartDate False (Or [Date $ DateSpan (Exact <$> small) Nothing, Date $ DateSpan (Exact <$> big) Nothing]) @?= small+ queryStartDate False (Or [Date $ DateSpan (Exact <$> small) Nothing, Date $ DateSpan Nothing Nothing]) @?= Nothing++ ,testCase "queryEndDate" $ do+ let small = Just $ fromGregorian 2000 01 01+ big = Just $ fromGregorian 2000 01 02+ queryEndDate False (And [Date $ DateSpan Nothing (Exact <$> small), Date $ DateSpan Nothing (Exact <$> big)]) @?= small+ queryEndDate False (And [Date $ DateSpan Nothing (Exact <$> small), Date $ DateSpan Nothing Nothing]) @?= small+ queryEndDate False (Or [Date $ DateSpan Nothing (Exact <$> small), Date $ DateSpan Nothing (Exact <$> big)]) @?= big+ queryEndDate False (Or [Date $ DateSpan Nothing (Exact <$> small), Date $ DateSpan Nothing Nothing]) @?= Nothing++ ,testCase "matchesAccount" $ do+ assertBool "" $ (Acct $ toRegex' "b:c") `matchesAccount` "a:bb:c:d"+ assertBool "" $ not $ (Acct $ toRegex' "^a:b") `matchesAccount` "c:a:b"+ assertBool "" $ Depth 2 `matchesAccount` "a"+ assertBool "" $ Depth 2 `matchesAccount` "a:b"+ assertBool "" $ not $ Depth 2 `matchesAccount` "a:b:c"+ assertBool "" $ not $ Date nulldatespan `matchesAccount` "a"+ assertBool "" $ not $ Date2 nulldatespan `matchesAccount` "a"+ assertBool "" $ not $ Tag (toRegex' "a") Nothing `matchesAccount` "a"++ ,testCase "matchesAccountExtra" $ do+ let tagq = Tag (toRegexCI' "type") Nothing+ assertBool "" $ not $ matchesAccountExtra (const Nothing) (const []) tagq "a"+ assertBool "" $ matchesAccountExtra (const Nothing) (const [("type","")]) tagq "a"++ ,testGroup "matchesPosting" [+ testCase "positive match on cleared posting status" $+ assertBool "" $ (StatusQ Cleared) `matchesPosting` nullposting{pstatus=Cleared}+ ,testCase "negative match on cleared posting status" $+ assertBool "" $ not $ (Not $ StatusQ Cleared) `matchesPosting` nullposting{pstatus=Cleared}+ ,testCase "positive match on unmarked posting status" $+ assertBool "" $ (StatusQ Unmarked) `matchesPosting` nullposting{pstatus=Unmarked}+ ,testCase "negative match on unmarked posting status" $+ assertBool "" $ not $ (Not $ StatusQ Unmarked) `matchesPosting` nullposting{pstatus=Unmarked}+ ,testCase "positive match on true posting status acquired from transaction" $+ assertBool "" $ (StatusQ Cleared) `matchesPosting` nullposting{pstatus=Unmarked,ptransaction=Just nulltransaction{tstatus=Cleared}}+ ,testCase "real:1 on real posting" $ assertBool "" $ (Real True) `matchesPosting` nullposting{preal=RealPosting}+ ,testCase "real:1 on virtual posting fails" $ assertBool "" $ not $ (Real True) `matchesPosting` nullposting{preal=VirtualPosting}+ ,testCase "real:1 on balanced virtual posting fails" $ assertBool "" $ not $ (Real True) `matchesPosting` nullposting{preal=BalancedVirtualPosting}+ ,testCase "acct:" $ assertBool "" $ (Acct $ toRegex' "'b") `matchesPosting` nullposting{paccount="'b"}+ ,testCase "tag:" $ do+ assertBool "" $ not $ (Tag (toRegex' "a") (Just $ toRegex' "r$")) `matchesPosting` nullposting+ assertBool "" $ (Tag (toRegex' "foo") Nothing) `matchesPosting` nullposting{ptags=[("foo","")]}+ assertBool "" $ (Tag (toRegex' "foo") Nothing) `matchesPosting` nullposting{ptags=[("foo","baz")]}+ assertBool "" $ (Tag (toRegex' "foo") (Just $ toRegex' "a")) `matchesPosting` nullposting{ptags=[("foo","bar")]}+ assertBool "" $ not $ (Tag (toRegex' "foo") (Just $ toRegex' "a$")) `matchesPosting` nullposting{ptags=[("foo","bar")]}+ assertBool "" $ not $ (Tag (toRegex' " foo ") (Just $ toRegex' "a")) `matchesPosting` nullposting{ptags=[("foo","bar")]}+ assertBool "" $ not $ (Tag (toRegex' "foo foo") (Just $ toRegex' " ar ba ")) `matchesPosting` nullposting{ptags=[("foo foo","bar bar")]}+ ,testCase "a tag match on a posting also sees inherited tags" $ assertBool "" $ (Tag (toRegex' "txntag") Nothing) `matchesPosting` nullposting{ptransaction=Just nulltransaction{ttags=[("txntag","")]}}+ ,testCase "cur:" $ do+ let toSym = fst . either error' id . parseQueryTerm (fromGregorian 2000 01 01) . ("cur:"<>)+ assertBool "" $ not $ toSym "$" `matchesPosting` nullposting{pamount=mixedAmount $ usd 1} -- becomes "^$$", ie testing for null symbol+ assertBool "" $ (toSym "\\$") `matchesPosting` nullposting{pamount=mixedAmount $ usd 1} -- have to quote $ for regexpr+ assertBool "" $ (toSym "shekels") `matchesPosting` nullposting{pamount=mixedAmount nullamt{acommodity="shekels"}}+ assertBool "" $ not $ (toSym "shek") `matchesPosting` nullposting{pamount=mixedAmount nullamt{acommodity="shekels"}}+ ,testCase "any: and all: match a posting by looking at its siblings" $ do+ let foodp = nullposting{paccount="expenses:food"}+ tie ps = txnTieKnot nulltransaction{tpostings=ps}+ cashtxn = tie [foodp, nullposting{paccount="assets:cash"}]+ cardtxn = tie [foodp, nullposting{paccount="liabilities:card"}]+ anycash = AnyPosting [Acct $ toRegex' "cash"]+ -- does the query match the food posting of this transaction ?+ -- all1, not all, so that an empty selection can't pass vacuously+ matchesFoodPostingOf q = all1 (matchesPosting q) . filter ((=="expenses:food").paccount) . tpostings+ -- expenses:food is selected by any:cash only in the transaction which also posts to cash+ assertBool "" $ matchesFoodPostingOf anycash cashtxn+ assertBool "" $ not $ matchesFoodPostingOf anycash cardtxn+ -- all: requires every sibling posting to match+ assertBool "" $ all1 (matchesPosting $ AllPostings [Acct $ toRegex' "expenses|assets"]) $ tpostings cashtxn+ assertBool "" $ not $ all1 (matchesPosting $ AllPostings [Acct $ toRegex' "assets"]) $ tpostings cashtxn+ -- a posting with no parent transaction, eg one generated by a report, is tested on its own+ assertBool "" $ (AnyPosting [Acct $ toRegex' "food"]) `matchesPosting` foodp+ assertBool "" $ not $ anycash `matchesPosting` foodp+ ]++ ,testCase "matchesTransaction" $ do+ assertBool "" $ Any `matchesTransaction` nulltransaction+ assertBool "" $ not $ (Desc $ toRegex' "x x") `matchesTransaction` nulltransaction{tdescription="x"}+ assertBool "" $ (Desc $ toRegex' "x x") `matchesTransaction` nulltransaction{tdescription="x x"}+ -- see posting for more tag tests+ assertBool "" $ (Tag (toRegex' "foo") (Just $ toRegex' "a")) `matchesTransaction` nulltransaction{ttags=[("foo","bar")]}+ assertBool "" $ (Tag (toRegex' "payee") (Just $ toRegex' "payee")) `matchesTransaction` nulltransaction{tdescription="payee|note"}+ assertBool "" $ (Tag (toRegex' "note") (Just $ toRegex' "note")) `matchesTransaction` nulltransaction{tdescription="payee|note"}+ -- a tag match on a transaction also matches posting tags+ assertBool "" $ (Tag (toRegex' "postingtag") Nothing) `matchesTransaction` nulltransaction{tpostings=[nullposting{ptags=[("postingtag","")]}]}++ -- hledger print expr:'cash and amt:>0' means "show transactions with (at least one posting involving a cash account) and (at least one posting with a positive amount)"+ let exprq = And [Acct $ toRegex' "cash", Amt Gt 0 Nothing]+ assertBool "" $ exprq `matchesTransaction` nulltransaction{tpostings=[nullposting{paccount="cash", pamount=1}]}+ assertBool "" $ exprq `matchesTransaction` nulltransaction{tpostings = [nullposting{paccount="cash"}, nullposting{paccount="food", pamount=1}]}++ -- hledger print any:'cash and amt:>0' means "show transactions where at least one posting posts a positive amount to a cash account".+ let anyq = AnyPosting [Acct $ toRegex' "cash", Amt Gt 0 Nothing]+ assertBool "" $ anyq `matchesTransaction` nulltransaction{tpostings=[nullposting{paccount="cash", pamount=1}]}+ assertBool "" $ not $ anyq `matchesTransaction` nulltransaction{tpostings = [nullposting{paccount="cash"}, nullposting{paccount="food", pamount=1}]}++ -- hledger print all:'cash and amt:0' means "show transactions where all postings involve a cash account and have a zero amount".+ assertBool "" $ AllPostings [Amt Eq 0 Nothing] `matchesTransaction`+ nulltransaction{tpostings = [nullposting{paccount = "cash"}, nullposting{paccount = "food"}]}+ assertBool "" $ not $ AllPostings [Acct $ toRegex' "cash", Amt Eq 0 Nothing] `matchesTransaction`+ nulltransaction{tpostings = [nullposting{paccount = "cash"}, nullposting{paccount = "food"}]}+ ]
Hledger/Read.hs view
@@ -1,157 +1,504 @@-{-| +--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-| -Read hledger data from various data formats, and related utilities.+This is the entry point to hledger's reading system, which can read+Journals from various data formats. Use this module if you want to parse+journal data or read journal files. Generally it should not be necessary+to import modules below this one. +== Journal reading++Reading an input file (in journal, csv, timedot, or timeclock format..)+involves these steps:++- select an appropriate file format "reader"+ based on filename extension/file path prefix/function parameter.+ A reader contains a parser and a finaliser (usually @journalFinalise@).++- run the parser to get a ParsedJournal+ (this may run additional sub-parsers to parse included files)++- run the finaliser to get a complete Journal, which passes standard checks++- if reading multiple files: merge the per-file Journals into one+ overall Journal++- if using -s/--strict: run additional strict checks++- if running print --new: save .latest files for each input file.+ (import also does this, as its final step.)++== Journal merging++Journal implements the Semigroup class, so two Journals can be merged+into one Journal with @j1 <> j2@. This is implemented by the+@journalConcat@ function, whose documentation explains what merging+Journals means exactly.++== Journal finalising++This is post-processing done after parsing an input file, such as+inferring missing information, normalising amount styles,+checking for errors and so on - a delicate and influential stage+of data processing. +In hledger it is done by @journalFinalise@, which converts a+preliminary ParsedJournal to a validated, ready-to-use Journal.+This is called immediately after the parsing of each input file.+It is not called when Journals are merged.++== Journal reading API++There are three main Journal-reading functions:++- readJournal to read from a Text value.+ Selects a reader and calls its parser and finaliser,+ then does strict checking if needed.++- readJournalFile to read one file, or stdin if the file path is @-@.+ Uses the file path/file name to help select the reader,+ calls readJournal,+ then writes .latest files if needed.++- readJournalFiles to read multiple files.+ Calls readJournalFile for each file (without strict checking or .latest file writing)+ then merges the Journals into one,+ then does strict checking and .latest file writing at the end if needed.++Each of these also has an easier variant with ' suffix,+which uses default options and has a simpler type signature.++One more variant, @readJournalFilesAndLatestDates@, is like+readJournalFiles but exposing the latest transaction date+(and how many on the same day) seen for each file.+This is used by the import command.+ -} +--- ** language+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}++--- ** exports module Hledger.Read (- tests_Hledger_Read,- readJournalFile,- readJournal,- journalFromPathAndString,- ledgeraccountname,- myJournalPath,- myJournal,- someamount,- journalenvvar,- journaldefaultfilename,- requireJournalFile,- ensureJournalFile,-)-where-import Control.Monad.Error-import Data.Either (partitionEithers)-import Data.List-import Safe (headDef)-import System.Directory (doesFileExist, getHomeDirectory)++ -- * Journal files+ defaultJournal,+ defaultJournalSafely,+ defaultJournalWith,+ defaultJournalWithSafely,+ defaultJournalPath,+ defaultJournalPathSafely,+ defaultExistingJournalPath,+ defaultExistingJournalPathSafely,+ requireJournalFileExists,+ ensureJournalFileExists,+ journalEnvVar,+ -- journalEnvVar2,+ journalDefaultFilename,++ -- * Journal parsing+ runExceptT,+ readJournal,+ readJournalFile,+ readPossibleJournalFile,+ readPossibleJournalFiles,+ readJournalFiles,+ readJournalFilesAndLatestDates,++ -- * Easy journal parsing+ readJournal',+ readJournal'',+ readJournalFile',+ readJournalFiles',+ orDieTrying,++ -- * Misc+ isWindowsUnsafeDotPath,++ -- * Re-exported+ JournalReader.tmpostingrulep,+ JournalReader.parseAssertDirective,+ findReader,+ splitReaderPrefix,+ runJournalParser,+ module Hledger.Read.Common,+ module Hledger.Read.InputOptions,+ module Hledger.Read.LatestDates,++ -- * Tests+ tests_Read,++) where++--- ** imports+import Control.Exception qualified as C+import Control.Monad (unless, when, (>=>))+import "mtl" Control.Monad.Except (ExceptT(..), runExceptT, liftEither)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.Default (def)+import Data.Foldable (asum)+import Data.List (intercalate, union)+import Data.List.NonEmpty (nonEmpty, NonEmpty((:|)))+import Data.Containers.ListUtils (nubOrd)+import Data.Map qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust)+import Data.Semigroup (sconcat)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import System.Directory (createDirectoryIfMissing, doesFileExist) import System.Environment (getEnv)-import System.Exit (exitFailure)-import System.FilePath ((</>))-import System.IO (IOMode(..), withFile, stderr)-import Test.HUnit-import Text.Printf+import System.FilePath ((</>), splitDirectories, takeDirectory, takeFileName)+import System.Info (os)+import System.IO (Handle, hPutStrLn, stderr) +import Hledger.Data.Amount (nullamt, showAmount) import Hledger.Data.Dates (getCurrentDay)-import Hledger.Data.Types (Journal(..), Reader(..))-import Hledger.Data.Journal (nullctx)+import Hledger.Data.Journal (commodityCombine, journalNumberAndTieTransactions, nulljournal)+import Hledger.Data.JournalChecks (journalStrictChecks)+import Hledger.Data.Types+import Hledger.Read.Common+import Hledger.Read.InputOptions import Hledger.Read.JournalReader as JournalReader-import Hledger.Read.TimelogReader as TimelogReader+import Hledger.Read.LatestDates+import Hledger.Read.CsvReader (tests_CsvReader)+import Hledger.Read.RulesReader (tests_RulesReader) import Hledger.Utils-import Prelude hiding (getContents, writeFile)-import Hledger.Utils.UTF8 (getContents, hGetContents, writeFile) +--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings -journalenvvar = "LEDGER_FILE"-journalenvvar2 = "LEDGER"-journaldefaultfilename = ".hledger.journal"+--- ** journal reading --- Here are the available readers. The first is the default, used for unknown data formats.-readers :: [Reader]-readers = [- JournalReader.reader- ,TimelogReader.reader- ]+journalEnvVar = "LEDGER_FILE"+journalDefaultFilename = ".hledger.journal" -formats = map rFormat readers+-- | Read the default journal file specified by the environment, +-- with default input options, or raise an error.+defaultJournal :: IO Journal+defaultJournal = defaultJournalSafely >>= either error' return -- PARTIAL: -readerForFormat :: String -> Maybe Reader-readerForFormat s | null rs = Nothing- | otherwise = Just $ head rs- where - rs = filter ((s==).rFormat) readers :: [Reader]+-- | Like defaultJournal, but return an error message instead of raising an error.+defaultJournalSafely :: IO (Either String Journal)+defaultJournalSafely = defaultJournalWithSafely definputopts --- | Read a Journal from this string (and file path), auto-detecting the--- data format, or give a useful error string. Tries to parse each known--- data format in turn. If none succeed, gives the error message specific--- to the intended data format, which if not specified is guessed from the--- file suffix and possibly the data.-journalFromPathAndString :: Maybe String -> FilePath -> String -> IO (Either String Journal)-journalFromPathAndString format fp s = do- let readers' = case format of Just f -> case readerForFormat f of Just r -> [r]- Nothing -> []- Nothing -> readers- (errors, journals) <- partitionEithers `fmap` mapM tryReader readers'- case journals of j:_ -> return $ Right j- _ -> return $ Left $ errMsg errors- where- tryReader r = (runErrorT . (rParser r) fp) s- errMsg [] = unknownFormatMsg- errMsg es = printf "could not parse %s data in %s\n%s" (rFormat r) fp e- where (r,e) = headDef (head readers, head es) $ filter detects $ zip readers es- detects (r,_) = (rDetector r) fp s- unknownFormatMsg = printf "could not parse %sdata in %s" (fmt formats) fp- where fmt [] = ""- fmt [f] = f ++ " "- fmt fs = intercalate ", " (init fs) ++ " or " ++ last fs ++ " "+-- | Like defaultJournal, but use the given input options.+defaultJournalWith :: InputOpts -> IO Journal+defaultJournalWith iopts = defaultJournalWithSafely iopts >>= either error' return -- PARTIAL: --- | Read a journal from this file, using the specified data format or--- trying all known formats, or give an error string; also create the file--- if it doesn't exist.-readJournalFile :: Maybe String -> FilePath -> IO (Either String Journal)-readJournalFile format "-" = getContents >>= journalFromPathAndString format "(stdin)"-readJournalFile format f = do- requireJournalFile f- withFile f ReadMode $ \h -> hGetContents h >>= journalFromPathAndString format f+-- | Like defaultJournalWith, but return an error message instead of raising an error.+defaultJournalWithSafely :: InputOpts -> IO (Either String Journal)+defaultJournalWithSafely iopts = (do+ f <- defaultJournalPath+ runExceptT $ readJournalFile iopts f+ )+ `C.catches` [ -- XXX+ C.Handler (\(e :: C.ErrorCall) -> return $ Left $ show e)+ ,C.Handler (\(e :: C.IOException) -> return $ Left $ show e)+ ] --- | If the specified journal file does not exist, give a helpful error and quit.-requireJournalFile :: FilePath -> IO ()-requireJournalFile f = do+-- | Get the default journal file path - either $LEDGER_FILE or $HOME/.hledger.journal file.+--+-- This looks for the LEDGER_FILE environment variable, like Ledger.+-- The value should be a file path, possibly with ~ at the start meaning the current user's home directory.+-- Or the value can be a glob pattern (containing *, ?, [ or {) ), in which case the first matching file path is used.+-- When it's a glob pattern that matches no existing files, an error is raised.+--+-- If LEDGER_FILE is unset or set to the empty string, this returns a default file path:+-- @.hledger.journal@ in the user's home directory,+-- or if we can't find the user's home directory, in the current directory.+--+-- The referenced file can be nonexistent.+--+defaultJournalPath :: IO String+defaultJournalPath = do+ p <- getEnv journalEnvVar `C.catch` (\(_::C.IOException) -> return "")+ if null p+ then do+ homedir <- fromMaybe "" <$> getHomeSafe+ let defaultfile = homedir </> journalDefaultFilename+ return defaultfile+ else+ expandPathOrGlob "." p++-- | Like defaultJournalPath, but return an error message instead of raising an error.+defaultJournalPathSafely :: IO (Either String String)+defaultJournalPathSafely = (do+ f <- defaultJournalPath+ return $ Right f+ )+ `C.catches` [+ C.Handler (\(e :: C.ErrorCall) -> return $ Left $ show e)+ ,C.Handler (\(e :: C.IOException) -> return $ Left $ show e)+ ]++-- | Like defaultJournalPath, but also checks that the file exists, and raises an error if it doesn't.+defaultExistingJournalPath :: IO String+defaultExistingJournalPath = do+ f <- defaultJournalPath+ requireJournalFileExists f+ return f++-- | Like defaultExistingJournalPath, but returns an error message instead of raising an error.+defaultExistingJournalPathSafely :: IO (Either String String)+defaultExistingJournalPathSafely = (do+ f <- defaultExistingJournalPath+ return $ Right f+ )+ `C.catches` [+ C.Handler (\(e :: C.ErrorCall) -> return $ Left $ show e)+ ,C.Handler (\(e :: C.IOException) -> return $ Left $ show e)+ ]++-- | @readJournal iopts mfile txt@+--+-- Read a Journal from some handle, with strict checks if enabled,+-- or return an error message.+--+-- The reader (data format) is chosen based on, in this order:+--+-- - a reader name provided in @iopts@+--+-- - a reader prefix in the @mfile@ path+--+-- - a file extension in @mfile@+--+-- If none of these is available, or if the reader name is unrecognised,+-- the journal reader is used.+--+-- If a file path is not provided, "-" is assumed (and may appear in error messages,+-- `files` output etc, where it will be a slight lie: it will mean "not from a file",+-- not necessarily "from standard input".+--+readJournal :: InputOpts -> Maybe FilePath -> Handle -> ExceptT String IO Journal+readJournal iopts@InputOpts{strict_, _defer} mpath hdl = do+ let r :: Reader IO = fromMaybe JournalReader.reader $ findReader (mformat_ iopts) mpath+ dbg6IO "readJournal: trying reader" (rFormat r)+ j <- rReadFn r iopts (fromMaybe "-" mpath) hdl+ when (strict_ && not _defer) $ liftEither $ journalStrictChecks j+ return j++-- | Read a Journal from this file, or from stdin if the file path is -,+-- with strict checks if enabled, or return an error message.+-- XXX or, calls error if the file does not exist.+--+-- (Note strict checks are disabled temporarily here when this is called by readJournalFiles).+-- The file path can have a READER: prefix.+--+-- The reader (data format) to use is determined from (in priority order):+-- the @mformat_@ specified in the input options, if any;+-- the file path's READER: prefix, if any;+-- a recognised file name extension.+-- if none of these identify a known reader, the journal reader is used.+--+-- The input options can also configure balance assertion checking, automated posting+-- generation, a rules file for converting CSV data, etc.+--+-- If using --new, and if latest-file writing is enabled in input options,+-- and not deferred by readJournalFiles, and after passing strict checks if enabled,+-- a .latest.FILE file will be created/updated (for the main file only, not for included files),+-- to remember the latest transaction date processed.+--+readJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal+readJournalFile iopts@InputOpts{new_, new_save_, _defer} prefixedfile = do+ (j, mlatestdates) <- readJournalFileAndLatestDates iopts prefixedfile+ when (new_ && new_save_ && not _defer) $ liftIO $+ case mlatestdates of+ Nothing -> return ()+ Just (LatestDatesForFile f ds) -> saveLatestDates ds f+ return j++-- The implementation of readJournalFile.+-- With --new, it also returns the latest transaction date(s) read from each file.+-- readJournalFiles uses this to update .latest files only after a successful read of all.+readJournalFileAndLatestDates :: InputOpts -> PrefixedFilePath -> ExceptT String IO (Journal, Maybe LatestDatesForFile)+readJournalFileAndLatestDates iopts prefixedfile = do+ let+ (mfmt, f) = splitReaderPrefix prefixedfile+ iopts' = iopts{mformat_=asum [mfmt, mformat_ iopts]}+ -- The file's content: replacement text from the input options, if any, otherwise the file (which must exist).+ moverride <- liftIO $ fileOverride iopts f+ h <-+ dbg6Msg ("readJournalFile: "++takeFileName f) $+ liftIO $ case moverride of+ Just t -> textToHandle t+ Nothing -> requireJournalFileExists f >> openFileOrStdin f+ -- <- T.readFile f -- or without line ending translation, for testing+ j <- readJournal iopts' (Just f) h+ if new_ iopts+ then do+ ds <- liftIO $ previousLatestDates f+ let (newj, newds) = journalFilterSinceLatestDates ds j+ return (newj, Just $ LatestDatesForFile f newds)+ else+ return (j, Nothing)++-- | Like readJournalFile, but if the file does not exist, returns an empty journal+-- with the file path set. This is useful for commands like add and import that+-- need to work with a potentially non-existent journal file.+readPossibleJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal+readPossibleJournalFile iopts prefixedfile = do+ let (_, f) = splitReaderPrefix prefixedfile+ if f == "-"+ then readJournalFile iopts prefixedfile+ else do+ exists <- liftIO $ doesFileExist f+ if exists+ then readJournalFile iopts prefixedfile+ else return $ nulljournal{jfiles = [JournalFile f "" 0]}++-- | Like readJournalFiles, but if the first file does not exist, provides an empty+-- journal with that file path set. Other files must exist as normal.+-- This is useful for commands like add and import that write to the first file,+-- which might not exist yet, while also reading other files for completions etc.+readPossibleJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal+readPossibleJournalFiles iopts pfs = case pfs of+ [] -> return nulljournal+ (f:fs) -> do+ let iopts' = iopts{_defer=True}+ j1 <- readPossibleJournalFile iopts' f+ js <- mapM (readJournalFile iopts') fs+ let combined = journalNumberAndTieTransactions $ sconcat (j1 :| js)+ when (strict_ iopts) $ liftEither $ journalStrictChecks combined+ return combined++-- | Read a Journal from each specified file path (using @readJournalFile@)+-- and combine them into one; or return the first error message.+--+-- Combining Journals means concatenating them, basically.+-- The parse state resets at the start of each file, which means that+-- directives & aliases do not affect subsequent sibling or parent files.+-- They do affect included child files though.+-- Also the final parse state saved in the Journal does span all files.+--+-- Strict checks, if enabled, are temporarily deferred until all files are read,+-- to ensure they see the whole journal, and/or to avoid redundant work.+-- (Some checks, like assertions and ordereddates, might still be doing redundant work ?)+--+-- Writing .latest files, if enabled, is also deferred till the end,+-- and is done only if strict checks pass.+--+readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal+readJournalFiles iopts@InputOpts{strict_, new_, new_save_, _scanfiles} prefixedfiles = do+ let iopts' = iopts{_defer=True}+ (j, latestdatesforfiles) <-+ dbg6Msg ("readJournalFiles: "++show prefixedfiles) $+ readJournalFilesAndLatestDates iopts' prefixedfiles+ when (strict_ && not _scanfiles) $ liftEither $ journalStrictChecks j+ when (new_ && new_save_) $ liftIO $ saveLatestDatesForFiles latestdatesforfiles+ return j++-- The implementation of readJournalFiles.+-- With --new, it also returns the latest transaction date(s) read in each file+-- (used by the import command).+-- This also renumbers the transactions if needed, ensuring their tindex values are unique;+-- that's also done elsewhere, but some code (accountTransactionsReport) needs it done sooner.+readJournalFilesAndLatestDates :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO (Journal, [LatestDatesForFile])+readJournalFilesAndLatestDates iopts pfs = do+ (js, lastdates) <- unzip <$> mapM (readJournalFileAndLatestDates iopts) pfs+ mapM_ dbg1MsgIO $ commodityStyleConflicts js+ let j = combineCommodityDeclarations js $ maybe def sconcat $ nonEmpty js+ return (journalNumberAndTieTransactions j, catMaybes lastdates)++-- | Set a combined journal's commodity declarations to those of its parts combined in reading order,+-- so that a later file's declaration of a commodity adds to or overrides an earlier file's+-- (as a later declaration in the same file does). See 'commodityCombine'.+combineCommodityDeclarations :: [Journal] -> Journal -> Journal+combineCommodityDeclarations js j = j{+ jdeclaredcommodities = M.unionsWith commodityCombine $ reverse $ map jdeclaredcommodities js+ ,jdeclaredcommoditytags = M.unionsWith union $ reverse $ map jdeclaredcommoditytags js+ }++-- | Debug messages for commodities declared with different display styles in different file trees.+-- When journals are combined, the last file tree's declared style is used (see 'combineCommodityDeclarations'),+-- as for a repeated declaration within one file tree, so this is not a warning.+commodityStyleConflicts :: [Journal] -> [String]+commodityStyleConflicts js =+ [ intercalate "\n" $ ("commodity " <> T.unpack sym <> " is declared with different display styles; using the last:")+ : [ " " <> sourcePosFileLine (csourcepos c) <> ": " <> showAmount nullamt{acommodity=sym, aquantity=1000, astyle=st}+ | c <- cs, Just st <- [cformat c] ]+ | (sym, cs) <- M.toList declsBySymbol+ , length (nubOrd [st{asrounding=NoRounding} | c <- cs, Just st <- [cformat c]]) > 1+ ]+ where+ declsBySymbol = M.fromListWith (flip (<>)) [(csymbol c, [c]) | j <- js, c <- M.elems $ jdeclaredcommodities j, isJust $ cformat c]++-- | An easy version of 'readJournal' which assumes default options, and fails in the IO monad.+readJournal' :: Handle -> IO Journal+readJournal' = orDieTrying . readJournal definputopts Nothing++-- | An even easier version of readJournal' which takes a 'Text' instead of a 'Handle'.+readJournal'' :: Text -> IO Journal+readJournal'' = textToHandle >=> readJournal'++-- | An easy version of 'readJournalFile' which assumes default options, and fails+-- in the IO monad.+readJournalFile' :: PrefixedFilePath -> IO Journal+readJournalFile' = orDieTrying . readJournalFile definputopts++-- | An easy version of 'readJournalFiles'' which assumes default options, and fails+-- in the IO monad.+readJournalFiles' :: [PrefixedFilePath] -> IO Journal+readJournalFiles' = orDieTrying . readJournalFiles definputopts++--- ** utilities++-- | Extract ExceptT to the IO monad, failing with an error message if necessary.+orDieTrying :: MonadIO m => ExceptT String m a -> m a+orDieTrying a = either (liftIO . fail) return =<< runExceptT a++-- | If the specified journal file does not exist (and is not "-"), call error with an informative message.+-- (Using "journal file" generically here; it could be in any of hledger's supported formats.)+requireJournalFileExists :: FilePath -> IO ()+requireJournalFileExists "-" = return ()+requireJournalFileExists f = do exists <- doesFileExist f- when (not exists) $ do- hPrintf stderr "The hledger journal file \"%s\" was not found.\n" f- hPrintf stderr "Please create it first, eg with hledger add, hledger web, or a text editor.\n"- hPrintf stderr "Or, specify an existing journal file with -f or LEDGER_FILE.\n"- exitFailure+ unless exists $ error' $ unlines+ [ "data file \"" <> f <> "\" was not found."+ ,"Please create it first, eg with \"hledger add\" or a text editor."+ ,"Or, specify an existing data file with -f or $LEDGER_FILE."+ ] -- | Ensure there is a journal file at the given path, creating an empty one if needed.-ensureJournalFile :: FilePath -> IO ()-ensureJournalFile f = do+-- On Windows, also ensure that the path contains no trailing dots+-- which could cause data loss (see 'isWindowsUnsafeDotPath').+ensureJournalFileExists :: FilePath -> IO ()+ensureJournalFileExists f = do+ when (os=="mingw32" && isWindowsUnsafeDotPath f) $+ error' $ "Part of file path \"" <> show f <> "\"\n ends with a dot, which is unsafe on Windows; please use a different path.\n" exists <- doesFileExist f- when (not exists) $ do- hPrintf stderr "Creating hledger journal file \"%s\".\n" f+ unless exists $ do+ hPutStrLn stderr $ "Creating hledger journal file " <> show f+ -- Create parent directories if they don't exist+ let dir = takeDirectory f+ unless (null dir || dir == ".") $+ createDirectoryIfMissing True dir -- note Hledger.Utils.UTF8.* do no line ending conversion on windows, -- we currently require unix line endings on all platforms.- newJournalContent >>= writeFile f+ newJournalContent >>= T.writeFile f +-- | Does any part of this path contain non-. characters and end with a . ?+-- Such paths are not safe to use on Windows (cf #1056).+isWindowsUnsafeDotPath :: FilePath -> Bool+isWindowsUnsafeDotPath = any (\x -> last x == '.' && any (/='.') x) . splitDirectories+ -- | Give the content for a new auto-created journal file.-newJournalContent :: IO String+newJournalContent :: IO Text newJournalContent = do d <- getCurrentDay- return $ printf "; journal created %s by hledger\n" (show d)---- | Read a Journal from this string, using the specified data format or--- trying all known formats, or give an error string.-readJournal :: Maybe String -> String -> IO (Either String Journal)-readJournal format s = journalFromPathAndString format "(string)" s---- | Get the user's journal file path. Like ledger, we look first for the--- LEDGER_FILE environment variable, and if that does not exist, for the--- legacy LEDGER environment variable. If neither is set, or the value is--- blank, return the default journal file path, which is--- ".hledger.journal" in the users's home directory, or if we cannot--- determine that, in the current directory.-myJournalPath :: IO String-myJournalPath = do- s <- envJournalPath- if null s then defaultJournalPath else return s- where- envJournalPath = getEnv journalenvvar `catch` (\_ -> getEnv journalenvvar2 `catch` (\_ -> return ""))- defaultJournalPath = do- home <- getHomeDirectory `catch` (\_ -> return "")- return $ home </> journaldefaultfilename---- | Read the user's default journal file, or give an error.-myJournal :: IO Journal-myJournal = myJournalPath >>= readJournalFile Nothing >>= either error' return--tests_Hledger_Read = TestList- [- tests_Hledger_Read_JournalReader,- tests_Hledger_Read_TimelogReader,+ return $ "; journal created " <> T.pack (show d) <> " by hledger\n" - "journalFile" ~: do- assertBool "journalFile should parse an empty file" (isRight $ parseWithCtx nullctx JournalReader.journalFile "")- jE <- readJournal Nothing "" -- don't know how to get it from journalFile- either error' (assertBool "journalFile parsing an empty file should give an empty journal" . null . jtxns) jE+--- ** tests +tests_Read = testGroup "Read" [+ tests_Common+ ,tests_CsvReader+ ,tests_JournalReader+ ,tests_RulesReader ]
+ Hledger/Read/Common.hs view
@@ -0,0 +1,2557 @@+--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-|++File reading/parsing utilities used by multiple readers, and a good+amount of the parsers for journal format, to avoid import cycles+when JournalReader imports other readers.++Some of these might belong in Hledger.Read.JournalReader or Hledger.Read.++-}++--- ** language+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE NoMonoLocalBinds #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}+{-# HLINT ignore "Functor law" #-}++--- ** exports+module Hledger.Read.Common (+ Reader (..),+ readerReadsOwnInput,+ includeFileParser,+ PrefixedFilePath,+ isStdin,+ InputOpts(..),+ HasInputOpts(..),+ definputopts,+ rawOptsToInputOpts,+ handleReadFnToTextReadFn,++ -- * parsing utilities+ parseAndFinaliseJournal,+ initialiseAndParseJournal,+ journalFinalise,+ journalAddForecast,+ journalAddAutoPostings,+ journalCheckAssertsWith,+ setYear,+ getYear,+ getSourcePos',+ setDefaultCommodityAndStyle,+ getDefaultCommodityAndStyle,+ getDefaultAmountStyle,+ getAmountStyle,+ journalDecimalMarkStyle,+ journalAmountStyleFor,+ shareText,+ shareAmountStyle,+ addDeclaredAccountTags,+ addDeclaredAccountType,+ pushParentAccount,+ getParentAccount,+ addAccountAlias,+ getAccountAliases,+ journalAddFile,++ -- * parsers+ -- ** transaction bits+ statusp,+ codep,+ descriptionp,++ -- ** dates+ datep,+ datetimep,+ timeofdayp,+ secondarydatep,++ -- ** account names+ modifiedaccountnamep,+ aliasedaccountnamep,+ applyParentAndOptionAliases,+ accountNameApplyModifiers,+ accountnamep,+ accountnamenosemicolonp,+ parentaccountnamep,++ -- ** account aliases+ accountaliasp,++ -- ** amounts+ spaceandamountormissingp,+ amountp,+ AmountParseKind(..),+ amountp',+ postingamountp,+ simpleamountp,+ commoditysymbolp,+ costp,+ balanceassertionp,+ lotcostp,+ numberp,+ fromRawNumber,+ rawnumberp,+ interpretRawNumber,+ RawNumber(..),+ AmbiguousNumber(..),+ DigitGrp(..),+ isDigitSeparatorChar,+ parseamount,+ parseamountWithStyles,+ parseamount',+ parsemixedamount,+ parsemixedamount',++ -- ** comments+ isLineCommentStart,+ isSameLineCommentStart,+ multilinecommentp,+ emptyorcommentlinep,+ emptyorcommentlinep2,+ followingcommentp,+ transactioncommentp,+ commentlinetagsp,+ postingcommentp,++ -- ** bracketed dates+ bracketeddatetagsp,++ -- ** misc+ doublequotedtextp,+ noncommenttextp,+ noncommenttext1p,+ singlespacedtext1p,+ singlespacednoncommenttext1p,+ singlespacedtextsatisfying1p,+ singlespacep,+ skipNonNewlineSpaces,+ skipNonNewlineSpaces1,+ aliasesFromOpts,++ -- * tests+ tests_Common,+)+where++--- ** imports+import Control.Monad (foldM, forM_, liftM2, when, unless, (>=>), (<=<))+import Control.Monad.Fail qualified as Fail (fail)+import Control.Exception (evaluate)+import Control.Exception.Safe (tryIO)+import Control.Monad.Except (ExceptT(..), liftEither, runExceptT, withExceptT)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Control.Monad.State.Strict (MonadState, evalStateT, modify', get)+import Control.Monad.Trans.Class (lift)+import Data.Bifunctor (bimap, first, second)+import Data.Char (digitToInt, isDigit, isSpace)+import Data.Decimal (DecimalRaw (Decimal), Decimal)+import Data.Either (rights)+import Data.Function ((&))+import Data.Functor ((<&>), ($>), void)+import Data.List (find, genericReplicate, intercalate, sortOn, union)+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe)+import Data.Map qualified as M+import Data.Set qualified as S+import Data.Semigroup qualified as Sem+import Data.Text (Text, stripEnd)+import Data.Text qualified as T+import Data.Time.Calendar (Day, fromGregorianValid, toGregorian)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..))+import Data.Word (Word8)+import System.Directory (canonicalizePath)+import System.FilePath (takeFileName)+import System.IO (Handle)+import Text.Megaparsec+import Text.Megaparsec.Char (char, char', digitChar, newline, string)+import Text.Megaparsec.Char.Lexer (decimal)+import Text.Printf (printf)++import Hledger.Data+import Hledger.Query (Query(..), filterQuery, parseQueryTerm, queryEndDate, queryStartDate, queryIsDate, simplifyQuery)+import Hledger.Reports.ReportOptions (ReportOpts(..), queryFromFlags, rawOptsToReportOpts)+import Hledger.Utils+import Hledger.Read.InputOptions+++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++--- ** types++-- main types; a few more below++-- | A hledger journal reader is a storage format name,+-- a list of file extensions assumed to be in this format,+-- and an IO action that reads data in this format, returning a Journal.+--+-- The journal parser used by the latter is also stored separately for direct use+-- by the journal reader's includedirectivep to parse included files.+-- The type variable m is needed for this parser.+-- Lately it requires an InputOpts, basically to support --old-timeclock.+data Reader m = Reader {+ -- The canonical name of the format handled by this reader. "journal", "timedot", "csv" etc.+ rFormat :: StorageFormat+ -- The file extensions recognised as containing this format.+ ,rExtensions :: [String]+ -- An IO action for reading this format, producing a journal or an error message.+ -- It accepts input options, a file path to show in error messages, and a handle to read data from.+ ,rReadFn :: InputOpts -> FilePath -> Handle -> ExceptT String IO Journal+ -- The megaparsec parser called by the above, provided separately for parsing included files.+ -- It is given the included file's text as input, or empty text if the reader reads its own input+ -- (see readerReadsOwnInput).+ ,rParser :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal+ }++instance Show (Reader m) where show r = show (rFormat r) ++ " reader"++-- | Does this reader's rParser read the included file itself, ignoring the text it is given ?+-- The CSV and rules readers do, since their data may be in a non-UTF-8 encoding declared by+-- the rules file, or (for rules files) in a separate data file.+readerReadsOwnInput :: Reader m -> Bool+readerReadsOwnInput r = case rFormat r of+ Sep _ -> True+ Rules -> True+ _ -> False++-- | Make an include file parser (see rParser) from an IO action which reads the file+-- at the given path and converts it to an unfinalised journal, with lists in reverse order+-- as journalFinalise expects. This is for readers of non-journal formats like CSV.+-- The megaparsec input is ignored; the file path is taken from the parse state's include file stack.+-- The account aliases in effect (from alias directives, then --alias options) are applied to the result,+-- as they would be for inlined journal entries (but not the parent account from apply account directives;+-- see 'accountNameApplyModifiers').+-- Any error, including an IO error, is rethrown as a final parse error showing the include file stack.+includeFileParser :: MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal+includeFileParser readfn = do+ j <- get+ f <- maybe (finalMessageFailure "includeFileParser: no include file in parse state") (pure . fst) $+ listToMaybe $ jparseincludefilestack j+ ej <- liftIO $ tryIO $ runExceptT $ readfn f >>= liftEither . journalApplyAliases (jparsealiases j ++ jparseoptaliases j)+ either (finalMessageFailure . show) (either finalMessageFailure pure) ej++-- | A file path optionally prefixed by a reader name and colon (journal:, csv:, timedot:, etc.).+-- The file path part can also be - meaning standard input.+type PrefixedFilePath = FilePath++-- | Is this the special file path meaning standard input ? (-, possibly prefixed)+isStdin :: PrefixedFilePath -> Bool+isStdin f = case splitAtElement ':' f of+ [_,"-"] -> True+ ["-"] -> True+ _ -> False++-- | Parse an InputOpts from a RawOpts and a provided date.+-- This will fail with a usage error if the forecast period expression cannot be parsed.+rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts+rawOptsToInputOpts day usecoloronstdout rawopts =++ let+ -- Allow/disallow implicit-cost conversion transactions, according to policy in Check.md.+ -- Disallow them if we see the --strict flag, or if we see a "balanced" argument with the "check" command,+ -- which we assume means the user is running "hledger check balanced".+ -- XXX #2377 The check was originally named "balancednoautoconversion",+ -- but later it was renamed, so this is no longer good; any command with "balanced"+ -- as an argument will also enable this check, normally enabled only in strict mode.+ noinferbalancingcosts = -- keep synced with Check.*+ boolopt "strict" rawopts + || (stringopt "args" rawopts == "balanced" && stringopt "command" rawopts == "check")++ -- Do we really need to do all this work just to get the requested end date? This is duplicating+ -- much of reportOptsToSpec.+ ropts = rawOptsToReportOpts day usecoloronstdout rawopts+ argsquery = map fst . rights . map (parseQueryTerm day) $ querystring_ ropts+ datequery = simplifyQuery . filterQuery queryIsDate . And $ queryFromFlags ropts : argsquery++ txnbalancingprecision = either err id $ transactionBalancingPrecisionFromOpts rawopts+ where err e = error' $ "could not parse --txn-tolerance: " ++ e -- PARTIAL:++ styles = either err id $ commodityStyleFromRawOpts rawopts+ where err e = error' $ "could not parse --commodity-style: '" ++ e ++ "'" -- PARTIAL:++ in definputopts{+ -- files_ = listofstringopt "file" rawopts+ mformat_ = Nothing+ ,mrules_file_ = maybestringopt "rules" rawopts+ ,aliases_ = listofstringopt "alias" rawopts+ ,anon_ = boolopt "obfuscate" rawopts+ ,new_ = boolopt "new" rawopts+ ,new_save_ = True+ ,pivot_ = stringopt "pivot" rawopts+ ,forecast_ = forecastPeriodFromRawOpts day rawopts+ ,verbose_tags_ = boolopt "verbose-tags" rawopts+ ,reportspan_ = DateSpan (Exact <$> queryStartDate False datequery) (Exact <$> queryEndDate False datequery)+ ,auto_ = boolopt "auto" rawopts+ ,infer_equity_ = boolopt "infer-equity" rawopts && conversionop_ ropts /= Just ToCost+ ,infer_costs_ = boolopt "infer-costs" rawopts+ ,ignore_lots_ = boolopt "ignore-lots" rawopts+ ,balancingopts_ = defbalancingopts{+ ignore_assertions_ = boolopt "ignore-assertions" rawopts+ , infer_balancing_costs_ = not noinferbalancingcosts+ , txn_balancing_ = txnbalancingprecision+ , infer_imbalance_ = boolopt "infer-imbalance" rawopts+ , commodity_styles_ = Just styles+ }+ ,strict_ = boolopt "strict" rawopts+ ,_ioDay = day+ ,_oldtimeclock = boolopt "oldtimeclock" rawopts+ }++handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal+handleReadFnToTextReadFn p iopts fp =+ p iopts fp <=< dbgTimeIO 1 ("read " <> takeFileName fp) <=< lift . hGetContentsPortably Nothing++-- | Get the date span from --forecast's PERIODEXPR argument, if any.+-- This will fail with a usage error if the period expression cannot be parsed,+-- or if it contains a report interval.+forecastPeriodFromRawOpts :: Day -> RawOpts -> Maybe DateSpan+forecastPeriodFromRawOpts d rawopts = do+ arg <- maybestringopt "forecast" rawopts+ let period = parsePeriodExpr d . textStripQuotes $ T.pack arg+ return $ if null arg then nulldatespan else either badParse (getSpan arg) period+ where+ badParse e = usageError $ "could not parse forecast period: "++customErrorBundlePretty e+ getSpan arg (interval, requestedspan) = case interval of+ NoInterval -> requestedspan+ _ -> usageError $ "--forecast's argument should not contain a report interval ("+ ++ show interval ++ " in \"" ++ arg ++ "\")"++-- | Given the raw options, return either+-- * if all options were successfully parsed: a map of successfully parsed commodity styles,+-- * if one or more options failed to parse: the first option which failed to parse+commodityStyleFromRawOpts :: RawOpts -> Either String (M.Map CommoditySymbol AmountStyle)+commodityStyleFromRawOpts rawOpts =+ foldM (\r -> fmap (\(c,a) -> M.insert c a r) . parseCommodity) mempty optList+ where+ optList = listofstringopt "commodity-style" rawOpts+ parseCommodity optStr = case parseamount optStr of+ Left _ -> Left optStr+ Right (Amount acommodity _ astyle _ _) -> Right (acommodity, astyle)++-- | Get the --txn-tolerance option's value.+-- (The deprecated --txn-balancing flag sets this too; see hiddenflagsformainmode.)+transactionBalancingPrecisionFromOpts :: RawOpts -> Either String TransactionBalancingPrecision+transactionBalancingPrecisionFromOpts rawopts =+ case maybestringopt "txn-tolerance" rawopts of+ Nothing -> Right TBPEntry+ Just "entry" -> Right TBPEntry+ Just "display" -> Right TBPDisplay+ Just s -> Left $ "'"<>s<>"', should be one of: entry, display"++-- | Given a parser to ParsedJournal, input options, file path and+-- content: run the parser on the content, and finalise the result to+-- get a Journal; or throw an error.+parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts+ -> FilePath -> Text -> ExceptT String IO Journal+parseAndFinaliseJournal parser iopts f txt =+ initialiseAndParseJournal parser iopts f txt >>= journalFinalise iopts f txt++-- | Given a parser to ParsedJournal, input options, file path and+-- content: run the parser on the content. This is all steps of+-- 'parseAndFinaliseJournal' without the finalisation step, and is used when+-- you need to perform other actions before finalisatison, as in parsing+-- Timeclock and Timedot files.+initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts+ -> FilePath -> Text -> ExceptT String IO Journal+initialiseAndParseJournal parser iopts f txt = do+ cf <- liftIO $ canonicalizePath f+ prettyParseErrors (runParserT (evalStateT parser (initJournal cf)) f txt)+ >>= dbgTimeIO 1 ("parse " <> takeFileName f)+ >>= \j -> j <$ dbgFastPathStats (jparsefastpathstats j)+ where+ y = first3 . toGregorian $ _ioDay iopts+ initJournal cf = nulljournal{jparsedefaultyear = Just y, jparseincludefilestack = [(f, cf)]}+ -- 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)++-- | With --debug, report what share of a parsed file's entries (including its included files')+-- the journal parser's fast path accepted, and why it declined the others; see the fast path+-- section of Hledger.Read.JournalReader. Nothing is reported for files with no such entries.+dbgFastPathStats :: MonadIO m => FastPathStats -> m ()+dbgFastPathStats FastPathStats{..}+ | debugLevel < 1 || null shares = return ()+ | otherwise = dbgMsgIO 1 $ "fast path was used for " ++ intercalate ", " shares ++ declined+ where+ shares = [share fpsTxnsFast fpsTxnsGeneral "transactions" | fpsTxnsFast + fpsTxnsGeneral > 0]+ ++ [share fpsPricesFast fpsPricesGeneral "prices" | fpsPricesFast + fpsPricesGeneral > 0]+ -- eg "51% of 900 transactions" (the percentage rounded)+ share fast general what = show ((200 * fast + total) `div` (2 * total)) ++ "% of " ++ show total ++ " " ++ what+ where total = fast + general+ declined+ | M.null fpsDeclines = ""+ | otherwise = "; declined: " ++ intercalate ", "+ [show n ++ " " ++ T.unpack reason | (reason, n) <- sortOn (negate . snd) $ M.toList fpsDeclines]++{- HLINT ignore journalFinalise "Redundant <&>" -} -- silence this warning, the code is clearer as is+-- note this activates TH, may slow compilation ? https://github.com/ndmitchell/hlint/blob/master/README.md#customizing-the-hints+--+-- | Post-process a parsed Journal: infer missing information, check validity,+-- and enrich postings with computed metadata.+-- See doc\/SPEC-finalising.md for the full pipeline specification.+maxExpectedForecastTxns :: Int+maxExpectedForecastTxns = 100000++journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal+journalFinalise InputOpts{_scanfiles=True} f txt pj =+ -- just finding the files read: record the main file's info, put lists in parse order, and stop+ return $ pj & journalAddFile (JournalFile f txt 0) & journalReverse+journalFinalise iopts@InputOpts{auto_,balancingopts_,ignore_lots_,infer_costs_,infer_equity_,strict_,verbose_tags_,_ioDay} f txt pj = do+ let+ BalancingOpts{commodity_styles_, ignore_assertions_} = balancingopts_+ -- Hack: peek at the command line to know if certain checks were requested.+ checking checkname = "check" `elem` args && checkname `elem` args where args = progArgs+ checkordereddates = checking "ordereddates"+ checkassertions = not ignore_assertions_ || strict_ || checking "assertions"+ lotschecking = not ignore_lots_ || strict_ || checking "lots" -- are lot checks wanted ?+ lenientlots = not lotschecking+ haslots = journalHasLotFeatures pj -- does the journal use lots at all ? if not, the lot stages are skipped, they would do nothing+ checklots = haslots && lotschecking -- run the lot classification, calculation and checking stages ?+ -- With --debug, report each stage's run time and memory allocation (dbgTime forces the stage's result to measure it).+ timed name stage = dbgTime 1 name . stage -- a stage returning a Journal+ timedE name stage = fmap (dbgTime 1 name) . stage -- a stage returning an Either error Journal++ t <- liftIO getPOSIXTime+ -- Warn before generating an implausible number of forecast transactions+ -- (in practice, a mistyped date in a periodic rule or --forecast period), so the user can cancel (#1683).+ -- They are counted without being generated, in constant memory.+ forM_ (forecastPeriod iopts pj) $ \forecastspan -> do+ let n = sum [ length $ periodicTransactionDates pt forecastspan | pt <- jperiodictxns pj ]+ when (n > maxExpectedForecastTxns) $ warnIO $ printf+ ("--forecast would generate %d transactions (forecast period %s),\n"+ <> "using a lot of memory. If not intended, press control-C now, and check for a mistyped date.")+ n (showDateSpan forecastspan)+ j <- liftEither $+ pj{jglobalcommoditystyles=fromMaybe mempty commodity_styles_}++ -- Setup+ & timed "journalSetLastReadTime" (journalSetLastReadTime t) -- save the last read time+ & timed "journalAddFile" (journalAddFile (JournalFile f txt 0)) -- save the main file's info+ & timed "journalReverse" journalReverse -- convert all lists to the order they were parsed++ -- Account types and amount styles+ & timed "journalAddAccountTypes" journalAddAccountTypes -- build a map of all known account types+ -- XXX does not see conversion accounts generated by journalInferEquityFromCosts below, requiring a workaround in journalCheckAccounts. Do it later ?+ & timedE "journalStyleAmounts" journalStyleAmounts -- infer and apply commodity styles (but don't round) - should be done early+ >>= timedE "journalApplyCommodityAliases" journalApplyCommodityAliases -- convert amounts in commodity aliases to their commodity++ -- Forecast and account tags+ <&> timed "journalAddForecast" (journalAddForecast verbose_tags_ (forecastPeriod iopts pj)) -- add forecast transactions if enabled+ <&> timed "journalPostingsAddAccountTags" journalPostingsAddAccountTags -- propagate account tags to postings (queryable but hidden)++ -- Pre-balancing cost/equity tagging+ >>= timedE "journalTagCostsAndEquityAndMaybeInferCosts" (journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ False) -- tag equity conversion postings and redundant costs, to help the transaction balancer ignore them++ -- Lot cost basis and transacted cost inference, and gain posting tagging+ -- These enrichment stages always run, so lot entries balance the same+ -- with or without --ignore-lots; with --ignore-lots (unless overridden+ -- by --strict or `hledger check lots`) they are lenient, skipping their+ -- errors and leaving the affected postings/transactions unchanged.+ -- They run before auto postings, whose preliminary balancing needs them too.+ >>= (if haslots then timedE "journalInferBasisFromAccountNames" (journalInferBasisFromAccountNames lenientlots) else pure) -- infer cost basis from lot subaccount names (validating them, unless lenient)+ <&> (if haslots then timed "journalInferPostingsTransactedCost" journalInferPostingsTransactedCost else id) -- in acquire-shaped postings, infer a transacted cost from cost basis+ >>= (if checklots then timedE "journalCheckAcquireBasis" journalCheckAcquireBasis else pure) -- error if an acquire-shaped posting's written cost basis and transacted cost differ (before balancing, so this is reported rather than an unbalanced entry)+ >>= (if haslots then timedE "journalTagGainPostings" (journalTagGainPostings lenientlots verbose_tags_) else pure) -- in disposals, tag user-written gain postings so the balancer sets them aside++ -- Auto postings+ >>= (if auto_ && not (null $ jtxnmodifiers pj)+ then timedE "journalAddAutoPostings" $ journalAddAutoPostings verbose_tags_ _ioDay -- add auto postings if enabled; does preliminary transaction balancing+ balancingopts_{lotful_commodities_ = journalLotfulCommodities pj+ ,account_lots_tags_ = journalAccountLotsTags pj+ ,lenient_lots_ = lenientlots+ ,verbose_balancing_tags_ = verbose_tags_}+ else pure)++ -- Transaction balancing+ >>= (\j -> if checkordereddates then journalCheckOrdereddates j $> j else Right j) -- maybe check that journal entries are in date order+ >>= (\j -> do+ -- Infer balance assignments/amounts, and maybe check balance assertions.+ -- An assertion failure is not raised immediately: it is deferred until+ -- the stages below have run without error, so lot errors (usually the+ -- more fundamental problem) are reported first.+ (j2, massertionerr) <- timedE "journalBalanceTransactionsAndDeferAssertions"+ (journalBalanceTransactionsAndDeferAssertions+ balancingopts_{ignore_assertions_=not checkassertions, account_types_ = jaccounttypes j+ ,lotful_commodities_ = journalLotfulCommodities j+ ,account_lots_tags_ = journalAccountLotsTags j+ ,lenient_lots_ = lenientlots+ ,verbose_balancing_tags_ = verbose_tags_+ ,imbalance_account_ = journalAccountForType defaultImbalanceAccount Imbalance j}) j+ j3 <- Right j2++ -- Lot classification+ -- Runs after balancing, when all posting amounts are known (inferred+ -- amounts included), so every entry shape classifies the same way as+ -- if its amounts had been written explicitly (#2686, #2690, #2692).+ <&> (if checklots then timed "journalClassifyLotPostings" (journalClassifyLotPostings verbose_tags_) else id) -- detect and classify lot postings (acquire/dispose/transfer..), maybe with visible tags++ -- Post-balancing enrichment+ >>= timedE "journalInferCommodityStyles" journalInferCommodityStyles -- infer commodity styles once more now that all posting amounts are present+ <&> timed "journalPostingsAddCommodityTags" journalPostingsAddCommodityTags -- propagate amounts' commodity tags to postings (queryable but hidden)++ -- Cost inference+ >>= (if infer_costs_ then timedE "journalTagCostsAndEquityAndMaybeInferCosts" (journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ True) else pure) -- maybe infer costs from equity postings++ -- Market prices and renumbering+ <&> timed "journalInferMarketPricesFromTransactions" journalInferMarketPricesFromTransactions -- infer market prices from commodity-exchanging transactions+ <&> timed "journalRenumberAccountDeclarations" journalRenumberAccountDeclarations -- renumber account declarations for consistent ordering++ -- Lot and capital gains calculation/checking+ -- (skipped by --ignore-lots or -I; forced back on by --strict or `hledger check lots`)+ >>= (if checklots then timedE "journalCheckLotsTagValues" journalCheckLotsTagValues else pure) -- validate lots: tag values on commodity/account declarations+ >>= (if checklots then timedE "journalCheckLotsMethodCoherence" journalCheckLotsMethodCoherence else pure) -- reject a global (*ALL) method mixed with other methods for one commodity+ >>= (if checklots then timedE "journalCalculateLots" (journalCalculateLots verbose_tags_) else pure) -- evaluate lot selectors, calculate lot balances, add lot subaccounts+ >>= (if checklots then timedE "journalAddOrCheckGainPostings" (journalAddOrCheckGainPostings verbose_tags_) else pure) -- in disposal transactions, add the realised-gain posting, or check a user-written one+ <&> (if haslots then timed "journalStripBalancerCopiedBases" journalStripBalancerCopiedBases else id) -- remove balancer-copied basis annotations, kept until now as classification evidence++ -- Equity inference+ <&> (if infer_equity_ then timed "journalInferEquityFromCosts" (journalInferEquityFromCosts verbose_tags_) else id) -- maybe infer equity postings from costs; after lot processing, so lot disposals convert at cost basis++ -- Now report any balance assertion failure detected above,+ -- then check any assert directives (on the finalised journal, so lot subaccounts are seen).+ maybe (Right j3) Left massertionerr+ >>= (if checkassertions && not (null $ jasserts j3)+ then timedE "journalCheckAsserts" (\j4 -> journalCheckAssertsWith iopts j4 $> j4)+ else pure))++ -- The last stage's timing line appears when its result is forced; with --debug, do that now.+ when (debugLevel > 0) $ liftIO $ void $ evaluate j+ return j++-- | Check a finalised journal's assert rules, as journal loading does, with these input options:+-- resolving relative dates with their today's date, and ignoring forecast transactions+-- if they were generated only for display (see '_forecastOnlyForDisplay').+-- Also used by hledger-ui to recheck the rules in memory.+journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()+journalCheckAssertsWith InputOpts{_forecastOnlyForDisplay, _ioDay} j =+ journalCheckAsserts _ioDay $+ if _forecastOnlyForDisplay then j{jtxns = filter (not . isForecast) $ jtxns j} else j+ where isForecast = isJust . lookup generatedTransactionTagName . ttags++-- | Apply any auto posting rules to generate extra postings on this journal's transactions.+-- With a true first argument, adds visible tags to generated postings and modified transactions.+journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal+journalAddAutoPostings verbosetags d bopts =+ -- Balance all transactions without checking balance assertions,+ journalBalanceTransactions bopts{ignore_assertions_=True}+ -- then add the auto postings+ -- (Note adding auto postings after balancing means #893b fails;+ -- adding them before balancing probably means #893a, #928, #938 fail.)+ >=> journalModifyTransactions verbosetags d++-- | Generate periodic transactions from all periodic transaction rules in the journal.+-- These transactions are added to the in-memory Journal (but not the on-disk file).+--+-- The start & end date for generated periodic transactions are determined in+-- a somewhat complicated way; see the hledger manual -> Periodic transactions.+journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal+journalAddForecast _ Nothing j = j+journalAddForecast verbosetags (Just forecastspan) j = j{jtxns = jtxns j ++ forecasttxns}+ where+ {-# HLINT ignore "Move concatMap out" #-}+ forecasttxns =+ map (txnTieKnot . transactionTransformPostings (styleAmounts $ journalCommodityStyles j))+ . filter (spanContainsDate forecastspan . tdate)+ . concatMap (\pt -> runPeriodicTransaction verbosetags pt forecastspan)+ $ jperiodictxns j++-- | For each posting whose account name contains a lot subaccount (e.g.+-- @assets:broker:{2026-01-15, $50}@), parse the cost basis from the subaccount+-- name and set or merge it into the posting's amounts' @acostbasis@.+-- This allows users to write lot subaccounts explicitly without redundant @{...}@+-- amount annotations.+--+-- With a true first argument (lenient mode, used by --ignore-lots), a posting+-- whose lot subaccount name is invalid or conflicting is left unchanged+-- (treated as an ordinary subaccount) instead of raising an error.+journalInferBasisFromAccountNames :: Bool -> Journal -> Either String Journal+journalInferBasisFromAccountNames lenient j = do+ txns' <- mapM processTransaction (jtxns j)+ Right j{jtxns = txns'}+ where+ parseAmt s = case parseamount s of+ Right a -> Just a+ Left _ -> Nothing++ processTransaction t = do+ ps' <- mapM processPosting (tpostings t)+ Right t{tpostings = ps'}++ processPosting p+ | lenient = Right $ either (const p) id $ inferPosting p+ | otherwise = inferPosting p++ inferPosting p = case lotSubaccountName (paccount p) of+ Nothing -> Right p+ Just name -> do+ cb <- first (lotErr p) $ parseLotName parseAmt name+ when (isNothing (cbDate cb) || isNothing (cbCost cb)) $+ Left $ lotErr p $ "lot subaccount name must contain a date and cost: " ++ T.unpack name+ let updateAmt a = case acostbasis a of+ Nothing -> Right a{acostbasis = Just cb}+ Just existing -> do+ merged <- first (lotConflictErr p) $ mergeCostBasis cb existing+ Right a{acostbasis = Just merged}+ amts' <- mapM updateAmt (amountsRaw (pamount p))+ Right p{pamount = foldMap mixedAmount amts'}++ -- Wrap a lot-subaccount parse error with a verbose source-position excerpt+ -- highlighting the posting's account name, and remind the reader that final+ -- @:{...}@ components are reserved for lot subaccount syntax.+ lotErr p msg = lotPosErr p $ msg+ ++ "\n\nA final account name part enclosed in { } must be a valid lot subaccount name."+ ++ "\nPlease adjust the account name, or use --ignore-lots/-I."++ -- Likewise for a lot subaccount name which disagrees with the amount's lot annotation.+ lotConflictErr p msg = lotPosErr p $ msg+ ++ "\n\nThe lot subaccount name and the amount's lot annotation must agree."+ ++ "\nPlease make them match, or remove one of them."++ lotPosErr :: Posting -> String -> String+ lotPosErr p msg = printf "%s:%d:\n%s\n%s" f line ex msg+ where (f, line, _, ex) = makePostingAccountErrorExcerpt p++setYear :: Year -> JournalParser m ()+setYear y = modify' (\j -> j{jparsedefaultyear=Just y})++getYear :: JournalParser m (Maybe Year)+getYear = fmap jparsedefaultyear get++dp :: String -> TextParser m ()+dp = const $ return () -- no-op+-- dp = dbgparse 0 -- trace parse state at this --debug level++-- | Get the decimal mark that has been specified for parsing, if any+-- (eg by the CSV decimal-mark rule, or possibly a future journal directive).+-- Return it as an AmountStyle that amount parsers can use.+getDecimalMarkStyle :: JournalParser m (Maybe AmountStyle)+getDecimalMarkStyle = journalDecimalMarkStyle <$> get++-- | The amount style implied by a decimal-mark directive or CSV rule in effect, if any.+journalDecimalMarkStyle :: Journal -> Maybe AmountStyle+journalDecimalMarkStyle Journal{jparsedecimalmark} = (\c -> amountstyle{asdecimalmark=Just c}) <$> jparsedecimalmark++setDefaultCommodityAndStyle :: (CommoditySymbol,AmountStyle) -> JournalParser m ()+setDefaultCommodityAndStyle cs = modify' (\j -> j{jparsedefaultcommodity=Just cs})++getDefaultCommodityAndStyle :: JournalParser m (Maybe (CommoditySymbol,AmountStyle))+getDefaultCommodityAndStyle = jparsedefaultcommodity `fmap` get++-- | Get amount style associated with default currency.+--+-- Returns 'AmountStyle' used to defined by a latest default commodity directive+-- prior to current position within this file or its parents.+getDefaultAmountStyle :: JournalParser m (Maybe AmountStyle)+getDefaultAmountStyle = fmap snd <$> getDefaultCommodityAndStyle++-- | Get the 'AmountStyle' declared by the most recently parsed (in the current or parent files,+-- prior to the current position) commodity directive for the given commodity, if any.+getAmountStyle :: CommoditySymbol -> JournalParser m (Maybe AmountStyle)+getAmountStyle commodity = flip journalAmountStyleFor commodity <$> get++-- | The 'AmountStyle' declared by the most recently parsed commodity directive for the given+-- commodity, or failing that by the most recent default commodity directive, if any.+journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle+journalAmountStyleFor Journal{jdeclaredcommodities, jparsedefaultcommodity} commodity =+ listToMaybe $ catMaybes [M.lookup commodity jdeclaredcommodities >>= cformat, snd <$> jparsedefaultcommodity]++-- | Return an identical amount style parsed earlier, if there is one, so that amounts share it;+-- otherwise remember and return this one. Journals use few distinct styles, so this saves memory.+shareAmountStyle :: AmountStyle -> JournalParser m AmountStyle+shareAmountStyle s = do+ styles <- jparseamountstyles <$> get+ case S.lookupLE s styles of+ Just s' | s' == s -> return s'+ _ -> do+ modify' $ \j -> j{jparseamountstyles = S.insert s styles}+ return s++-- | Return an identical text parsed earlier (an account name or commodity symbol), if there is one,+-- so that they share one copy; otherwise remember (a compact copy of) this one and return that.+-- Journals use relatively few distinct account names and commodity symbols, so this saves memory.+shareText :: Text -> JournalParser m Text+shareText t = do+ texts <- jparsetexts <$> get+ case S.lookupLE t texts of+ Just t' | t' == t -> return t'+ _ -> do+ let t' = T.copy t -- don't retain the whole input text this is a slice of+ modify' $ \j -> j{jparsetexts = S.insert t' texts}+ return t'++addDeclaredAccountTags :: AccountName -> [Tag] -> JournalParser m ()+addDeclaredAccountTags acct atags =+ modify' (\j -> j{jdeclaredaccounttags = M.insertWith (flip union) acct atags (jdeclaredaccounttags j)})++addDeclaredAccountType :: AccountName -> AccountType -> JournalParser m ()+addDeclaredAccountType acct atype =+ modify' (\j -> j{jdeclaredaccounttypes = M.insertWith (++) atype [acct] (jdeclaredaccounttypes j)})++pushParentAccount :: AccountName -> JournalParser m ()+pushParentAccount acct = modify' (\j -> j{jparseparentaccounts = acct : jparseparentaccounts j})++getParentAccount :: JournalParser m AccountName+getParentAccount = fmap (concatAccountNames . reverse . jparseparentaccounts) get++-- | Get the current source position, like megaparsec's getSourcePos but+-- cheaper on large inputs. megaparsec walks every character since the last+-- position it calculated, checking each one's width; this instead starts+-- from the most recently calculated position kept in the parse state (see+-- 'ParsePos'), counts the newlines since then with a fast scan, and walks+-- only the current line, using megaparsec's column rules. The journal+-- parsers should use this rather than getSourcePos. On the first call, or+-- if the parser has somehow moved backwards, it falls back to getSourcePos.+-- (Though, measured in 2026 on a 100k-transaction journal, this saved only+-- about 4% of total run time: the per-character walk is cheap in optimised code,+-- and this still scans the text, just faster.)+getSourcePos' :: JournalParser m SourcePos+getSourcePos' = do+ o <- getOffset+ manchor <- jparsepos <$> get+ pos <- case manchor of+ Just (ParsePos anchor@(SourcePos f l _) o0 s0) | o >= o0 -> do+ let+ consumed = T.take (o - o0) s0 -- the text between the anchor and here+ newlines = T.count "\n" consumed+ -- walk the current line only: from the anchor if that is on this line, else from the line's start+ (startpos, lineprefix)+ | newlines == 0 = (anchor, consumed)+ | otherwise = (SourcePos f (mkPos $ unPos l + newlines) pos1, T.takeWhileEnd (/= '\n') consumed)+ return $ pstateSourcePos $ reachOffsetNoLine (T.length lineprefix) PosState+ { pstateInput = lineprefix, pstateOffset = 0, pstateSourcePos = startpos+ , pstateTabWidth = defaultTabWidth, pstateLinePrefix = "" }+ _ -> getSourcePos+ s <- getInput+ modify' $ \j -> j{jparsepos = Just $ ParsePos pos o s}+ return pos++addAccountAlias :: MonadState Journal m => AccountAlias -> m ()+addAccountAlias a = modify' (\(j@Journal{..}) -> j{jparsealiases=a:jparsealiases})++getAccountAliases :: MonadState Journal m => m [AccountAlias]+getAccountAliases = fmap jparsealiases get++-- getTransactionCount :: MonadState Journal m => m Integer+-- getTransactionCount = fmap jparsetransactioncount get+--+-- setTransactionCount :: MonadState Journal m => Integer -> m ()+-- setTransactionCount i = modify' (\j -> j{jparsetransactioncount=i})+--+-- -- | Increment the transaction index by one and return the new value.+-- incrementTransactionCount :: MonadState Journal m => m Integer+-- incrementTransactionCount = do+-- modify' (\j -> j{jparsetransactioncount=jparsetransactioncount j + 1})+-- getTransactionCount++journalAddFile :: JournalFile -> Journal -> Journal+journalAddFile f j@Journal{jfiles=fs} = j{jfiles=fs++[f]}+ -- append, unlike the other fields, even though we do a final reverse,+ -- to compensate for additional reversal due to including/monoid-concatting++-- A version of `match` that is strict in the returned text+match' :: TextParser m a -> TextParser m (Text, a)+match' p = do+ (!txt, p') <- match p+ pure (txt, p')++--- ** parsers+--- *** transaction bits++statusp :: TextParser m Status+statusp = do+ -- a status mark may follow, after optional spaces; check cheaply, since usually there is none+ (_, mc) <- peekAfterSpaces+ case mc of+ Just '*' -> Cleared <$ (skipNonNewlineSpaces *> char '*')+ Just '!' -> Pending <$ (skipNonNewlineSpaces *> char '!')+ _ -> pure Unmarked++codep :: TextParser m Text+codep = do+ -- a code in parentheses may follow, after spaces; check cheaply, since usually there is none+ (spaced, mc) <- peekAfterSpaces+ if spaced && mc == Just '('+ then do+ skipNonNewlineSpaces1+ char '('+ code <- takeWhileP Nothing $ \c -> c /= ')' && c /= '\n'+ char ')' <?> "closing bracket ')' for transaction code"+ pure code+ else pure ""++-- | Parse possibly empty text until a semicolon or newline.+-- Whitespace is preserved (for now - perhaps helps preserve alignment +-- of same-line comments ?).+descriptionp :: TextParser m Text+descriptionp = noncommenttextp <?> "description"++--- *** dates++-- | Parse a date in YYYY-MM-DD format.+-- Slash (/) and period (.) are also allowed as separators.+-- The year may be omitted if a default year has been set.+-- Leading zeroes may be omitted.+datep :: JournalParser m Day+datep = do+ mYear <- getYear+ lift $ datep' mYear++datep' :: Maybe Year -> TextParser m Day+datep' mYear = do+ startOffset <- getOffset+ d1 <- yearorintp <?> "year or month"+ sep <- datesepchar <?> "date separator"+ d2 <- decimal <?> "month or day"+ case d1 of+ Left y -> fullDate startOffset y sep d2+ Right m -> partialDate startOffset mYear m d2+ <?> "full or partial date"+ where+ fullDate :: Int -> Year -> Char -> Month -> TextParser m Day+ fullDate startOffset year sep month = do+ sep2 <- satisfy isDateSepChar <?> "date separator"+ day <- decimal <?> "day"+ endOffset <- getOffset+ when (sep /= sep2) $ + customFailure $ parseErrorAtRegion startOffset endOffset $+ "This date has different separators, please use consistent separators."+ case fromGregorianValid year month day of+ Nothing -> + customFailure $ parseErrorAtRegion startOffset endOffset $+ "This is not a valid date, please fix it."+ Just date -> pure $! date++ partialDate :: Int -> Maybe Year -> Month -> MonthDay -> TextParser m Day+ partialDate startOffset myr month day = do+ endOffset <- getOffset+ case myr of+ Just year ->+ case fromGregorianValid year month day of+ Nothing -> + customFailure $ parseErrorAtRegion startOffset endOffset $+ "This is not a valid date, please fix it."+ Just date -> pure $! date++ Nothing ->+ customFailure $ parseErrorAtRegion startOffset endOffset $+ "This partial date can not be parsed because the current year is unknown.\n"+ ++"Please make it a full date, or add a default year directive."++{-# INLINABLE datep' #-}++-- | Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format.+-- Slash (/) and period (.) are also allowed as date separators.+-- The year may be omitted if a default year has been set.+-- Seconds are optional.+-- The timezone is optional and ignored (the time is always interpreted as a local time).+-- Leading zeroes may be omitted (except in a timezone).+datetimep :: JournalParser m LocalTime+datetimep = do+ mYear <- getYear+ lift $ datetimep' mYear++datetimep' :: Maybe Year -> TextParser m LocalTime+datetimep' mYear = do+ day <- datep' mYear+ skipNonNewlineSpaces1+ time <- timeofdayp+ pure $ LocalTime day time++-- | Parse a time of day (HH:MM[:SS]), and skip any time zone suffix (like +0100) following it.+timeofdayp :: TextParser m TimeOfDay+timeofdayp = do+ time <- timeOfDay+ optional timeZone -- ignoring time zones+ pure time++ where+ timeOfDay :: TextParser m TimeOfDay+ timeOfDay = do+ off1 <- getOffset+ h' <- twoDigitDecimal <?> "hour"+ off2 <- getOffset+ unless (h' >= 0 && h' <= 23) $ customFailure $+ parseErrorAtRegion off1 off2 "invalid time (bad hour)"++ char ':' <?> "':' (hour-minute separator)"+ off3 <- getOffset+ m' <- twoDigitDecimal <?> "minute"+ off4 <- getOffset+ unless (m' >= 0 && m' <= 59) $ customFailure $+ parseErrorAtRegion off3 off4 "invalid time (bad minute)"++ s' <- option 0 $ do+ char ':' <?> "':' (minute-second separator)"+ off5 <- getOffset+ s' <- twoDigitDecimal <?> "second"+ off6 <- getOffset+ unless (s' >= 0 && s' <= 59) $ customFailure $+ parseErrorAtRegion off5 off6 "invalid time (bad second)"+ -- we do not support leap seconds+ pure s'++ pure $ TimeOfDay h' m' (fromIntegral s')++ twoDigitDecimal :: TextParser m Int+ twoDigitDecimal = do+ d1 <- digitToInt <$> digitChar+ d2 <- digitToInt <$> (digitChar <?> "a second digit")+ pure $ d1*10 + d2++ timeZone :: TextParser m String+ timeZone = do+ plusminus <- satisfy $ \c -> c == '-' || c == '+'+ fourDigits <- count 4 (digitChar <?> "a digit (for a time zone)")+ pure $ plusminus:fourDigits++secondarydatep :: Day -> TextParser m Day+secondarydatep primaryDate = char '=' *> datep' (Just primaryYear)+ where primaryYear = first3 $ toGregorian primaryDate++-- | Parse a year number or an Int. Years must contain at least four+-- digits.+yearorintp :: TextParser m (Either Year Int)+yearorintp = do+ yearOrMonth <- takeWhile1P (Just "digit") isDigit+ let n = readDecimal yearOrMonth+ return $ if T.length yearOrMonth >= 4 then Left n else Right (fromInteger n)++--- *** account names++-- | Parse an account name plus one following space if present (see accountnamep);+-- then apply the alias directives, parent account prefix and --alias options currently in effect,+-- in that order (see 'accountNameApplyModifiers', which explains this).+-- This calls error if any account alias with an invalid regular expression exists.+-- The flag says whether account names may include semicolons; currently account names+-- in journal format may, but account names in timeclock/timedot formats may not.+modifiedaccountnamep :: Bool -> JournalParser m AccountName+modifiedaccountnamep allowsemicolon = aliasedaccountnamep allowsemicolon >>= applyParentAndOptionAliases++-- | Parse an account name like modifiedaccountnamep, but apply only the alias directives,+-- not the parent account prefix or --alias options (see 'accountNameApplyModifiers').+aliasedaccountnamep :: Bool -> JournalParser m AccountName+aliasedaccountnamep allowsemicolon = do+ als <- getAccountAliases+ a <- lift $ if allowsemicolon then accountnamep else accountnamenosemicolonp+ -- XXX or accountNameApplyAliasesMemo ? doesn't seem to make a difference (retest that function)+ orAliasError a $ accountNameApplyAliases als a++-- | Add the parent account prefix to an account name (with alias directives already applied),+-- then apply the --alias options (see 'accountNameApplyModifiers').+-- This calls error if an --alias option has an invalid regular expression.+applyParentAndOptionAliases :: AccountName -> JournalParser m AccountName+applyParentAndOptionAliases a = do+ parent <- getParentAccount+ optals <- jparseoptaliases <$> get+ orAliasError a $ accountNameApplyAliases optals $ joinAccountNames parent a++-- | Return an aliased account name, or call error with the alias problem.+-- This should not happen, regexaliasp will have displayed a better error already.+-- (XXX why does customFailure cause error to be displayed there, but not here ?)+orAliasError :: AccountName -> Either RegexError AccountName -> JournalParser m AccountName+orAliasError _ (Right a') = return $! a'+orAliasError a (Left e) = error' $ "problem in account alias applied to "++T.unpack a++": "++e -- PARTIAL:++-- | Rewrite an account name as written in a journal entry, using the given alias directives+-- (most recent first), parent account (from apply account directives) and --alias options.+-- Can fail with a bad replacement pattern in a regular expression alias.+--+-- This is the reference for how account names are modified during parsing. There are three modifiers,+-- applied in this order:+--+-- 1. alias directives and account directives' alias: tags (kept in 'jparsealiases'),+-- applied to the name as written. This is as in Ledger, and it means a file's aliases keep working+-- when the file is included under apply account (#2733). Before hledger 2, these were applied after step 2.+--+-- 2. the parent account from apply account directives ('jparseparentaccounts'), prepended.+--+-- 3. --alias options ('jparseoptaliases'), applied to the full account name,+-- since that is the name users see in reports. These are kept separately from 1,+-- so that end aliases can forget alias directives without forgetting them.+--+-- The code is split up because of a few special cases:+--+-- - The parsers apply these in two parts: 'aliasedaccountnamep' does step 1, and+-- 'applyParentAndOptionAliases' does steps 2 and 3. Normally both are used ('modifiedaccountnamep').+-- But accountdirectivep also needs the name after step 1 only: it is the target of the directive's+-- alias: tags, which (like alias directives) are applied before step 2, so a target which already+-- included the parent account would get it added twice.+--+-- - The journal reader's fast path for simple transactions (fasttransactionp) does all three steps+-- with this function, since it works on text rather than in the parser.+--+-- - Entries from included CSV/rules files get steps 1 and 3, but not 2 ('includeFileParser').+-- (Included timeclock/timedot files are parsed with 'modifiedaccountnamep', so they get all three.)+--+-- - When a non-journal file is read directly, 'jparseoptaliases' is empty, and its reader+-- applies step 3 itself after parsing.+accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName+accountNameApplyModifiers als parent optals a =+ accountNameApplyAliases optals . joinAccountNames parent =<< accountNameApplyAliases als a++-- | Parse an account name, plus one following space if present.+-- Account names have one or more parts separated by the account separator character,+-- and are terminated by two or more whitespace characters (spaces or tabs), or end of input.+-- Each part is at least one character long, may have single spaces inside it, and starts with a non-whitespace.+-- (We should have required them to start with an alphanumeric, but didn't.)+-- An empty part (from a leading, trailing or repeated separator) is an error.+-- Note, this means account names can contain all kinds of punctuation, including ; which usually starts a following comment.+-- Parent parsers usually remove the following comment before using this parser.+accountnamep :: TextParser m AccountName+accountnamep = nonemptypartsp id singlespacedtext1p++-- Like accountnamep, but stops parsing if it reaches a semicolon.+accountnamenosemicolonp :: TextParser m AccountName+accountnamenosemicolonp = nonemptypartsp id singlespacednoncommenttext1p++-- | Parse the parent account name of an apply account directive.+-- Like accountnamep, but one trailing account separator is allowed, and dropped (as in Ledger, #2858).+parentaccountnamep :: TextParser m AccountName+parentaccountnamep = nonemptypartsp (\a -> fromMaybe a $ T.stripSuffix acctsep a) singlespacedtext1p++-- | Run an account name parser, and normalise its result with the given function;+-- fail with an error highlighting the name if the result has an empty part.+nonemptypartsp :: (AccountName -> AccountName) -> TextParser m AccountName -> TextParser m AccountName+nonemptypartsp f p = do+ off1 <- getOffset+ a <- p+ off2 <- getOffset+ let a' = f a+ when (accountNameHasEmptyPart a') $ customFailure $ parseErrorAtRegion off1 off2 $+ "account name \"" ++ T.unpack a ++ "\" has an empty part.\n"+ ++ "Account names can't begin or end with " ++ sep ++ ", or contain " ++ sep ++ sep ++ "."+ return a'+ where sep = [acctsepchar]++-- | Parse a single line of possibly empty text enclosed in double quotes.+doublequotedtextp :: TextParser m Text+doublequotedtextp = between (char '"') (char '"') $+ takeWhileP Nothing $ \c -> not $ isNewline c || c == '"'++-- | Parse possibly empty text, including whitespace, +-- until a comment start (semicolon) or newline.+noncommenttextp :: TextParser m T.Text+noncommenttextp = takeWhileP Nothing (\c -> not $ isSameLineCommentStart c || isNewline c)++-- | Parse non-empty text, including whitespace, +-- until a comment start (semicolon) or newline.+noncommenttext1p :: TextParser m T.Text+noncommenttext1p = takeWhile1P Nothing (\c -> not $ isSameLineCommentStart c || isNewline c)++-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,+-- until a double space or newline.+singlespacedtext1p :: TextParser m T.Text+singlespacedtext1p = singlespacedtextsatisfying1p (const True)++-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,+-- until a comment start (semicolon), double space, or newline.+singlespacednoncommenttext1p :: TextParser m T.Text+singlespacednoncommenttext1p = singlespacedtextsatisfying1p (not . isSameLineCommentStart)++-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,+-- where all characters satisfy the given predicate.+singlespacedtextsatisfying1p :: (Char -> Bool) -> TextParser m T.Text+singlespacedtextsatisfying1p f = do+ firstPart <- partp+ otherParts <- manyWhile nextissinglespaceandpart $ try $ singlespacep *> partp+ pure $! T.unwords $ firstPart : otherParts+ where+ partp = takeWhile1P Nothing (\c -> f c && not (isSpace c))+ -- is the next part separated from here by exactly one space ? (checked cheaply before parsing)+ nextissinglespaceandpart = do+ next2 <- peekChars2+ pure $ case next2 of+ (Just c1, Just c2) -> isNonNewlineSpace c1 && f c2 && not (isSpace c2)+ _ -> False++-- | Parse one non-newline whitespace character that is not followed by another one.+-- (A single tab is not a separator, unlike in Ledger; hledger 1 and 2 agree on this.)+singlespacep :: TextParser m ()+singlespacep = spacenonewline *> notFollowedBy spacenonewline++--- *** amounts++-- | Parse whitespace then an amount, or return the special "missing" marker amount.+spaceandamountormissingp :: JournalParser m MixedAmount+spaceandamountormissingp =+ option missingmixedamt $ try $ do+ lift $ skipNonNewlineSpaces1+ mixedAmount <$> amountp++-- | Parse a single-commodity amount, applying the default commodity if there is no commodity symbol;+-- optionally followed by, in any order:+-- a Ledger-style cost, Ledger-style valuation expression, and/or Ledger-style cost basis, which is one or more of+-- lot cost, lot date, and/or lot note (we loosely call this triple the lot's cost basis).+-- The cost basis makes it a lot rather than just an amount. Both cost basis info and valuation expression+-- are discarded for now.+-- The main amount's sign is significant; here are the possibilities and their interpretation.+-- Also imagine an optional VALUATIONEXPR added to any of these (omitted for clarity):+-- @+--+-- AMT -- acquiring an amount+-- AMT COST -- acquiring an amount at some cost+-- AMT COST COSTBASIS -- acquiring a lot at some cost, saving its cost basis+-- AMT COSTBASIS COST -- like the above+-- AMT COSTBASIS -- like the above with cost same as the cost basis+--+-- -AMT -- releasing an amount+-- -AMT SELLPRICE -- releasing an amount at some selling price+-- -AMT SELLPRICE COSTBASISSEL -- releasing a lot at some selling price, selecting it by its cost basis+-- -AMT COSTBASISSEL SELLPRICE -- like the above+-- -AMT COSTBASISSEL -- like the above with selling price same as the selected lot's cost basis amount+--+-- COST/SELLPRICE can be @ UNITAMT, @@ TOTALAMT, (@) UNITAMT, or (@@) TOTALAMT. The () are ignored.+-- COSTBASIS is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order, with LOTCOST defaulting to COST.+-- COSTBASISSEL is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order.+-- {LOTCOST} can be {UNITAMT}, {{TOTALAMT}}, {=UNITAMT}, or {{=TOTALAMT}}. The = is ignored.+-- VALUATIONEXPR can be ((VALUE AMOUNT)) or ((VALUE FUNCTION)).+--+-- @+-- Ledger amount syntax is really complex.+-- Rule of thumb: curly braces, parentheses, and/or square brackets+-- in an amount means a Ledger-style cost basis is involved.+--+-- To parse an amount's numeric quantity we need to know which character +-- represents a decimal mark. We find it in one of three ways:+--+-- 1. If a decimal mark has been set explicitly in the journal parse state+-- (by a decimal-mark directive or CSV rule), we use that, strictly+--+-- 2. Or if the journal has a commodity declaration for the amount's commodity,+-- we get the decimal mark from that, and use it only to interpret ambiguous numbers+-- (see AmountParseKind for details)+--+-- 3. Otherwise we will parse any valid decimal mark appearing in the+-- number, as long as the number appears well formed.+-- (This means we handle files with any supported decimal mark without configuration,+-- but it also allows different decimal marks in different amounts,+-- which is a bit too loose. There's an open issue.)+--+amountp :: JournalParser m Amount+amountp = amountp' OrdinaryAmount++-- | The kinds of amount which are parsed a little differently.+--+-- A decimal-mark directive (or CSV rule) declares how numbers are written in the data,+-- and data amounts (OrdinaryAmount, MultiplierAmount) must obey it strictly;+-- violations are parse errors, reported at the number.+-- A commodity or D directive declares a display style, given as a sample amount (StyleAmount),+-- which may use a different decimal mark from the data.+-- When there's no decimal-mark directive, a commodity's display style is also used+-- to interpret ambiguous numbers like 1,000, but it is not enforced.+data AmountParseKind+ = OrdinaryAmount+ -- ^ An amount in the data: in a posting, cost, balance assertion, price directive, CSV record, etc.+ -- If a decimal-mark directive is in effect, the number must use only that decimal mark:+ -- 1,000.00 is rejected when , is declared, and 1.2.34 when . is declared.+ | MultiplierAmount+ -- ^ A multiplier in an auto posting rule (*AMT). The default commodity is not applied to it.+ -- Otherwise it's parsed like an OrdinaryAmount.+ | StyleAmount+ -- ^ The sample amount in a commodity directive (or its format subdirective) or a D directive,+ -- declaring a display style. Its decimal mark may differ from the one declared by decimal-mark,+ -- so that is not enforced; but it is still used to interpret ambiguous numbers like 1,000.+ deriving (Eq, Show)++-- An amount with optional cost, valuation, and/or cost basis, as described above.+amountp' :: AmountParseKind -> JournalParser m Amount+amountp' kind =+ -- dbg "amountp'" $+ label "amount" $ do+ amt <- simpleamountp kind <* lift skipNonNewlineSpaces+ amountannotationsp amt++-- | A posting amount. Like amountp', except that the amount may also be written as a simple+-- arithmetic expression, which is evaluated to a single amount (see amountexprp) (#2648).+-- Any cost, valuation or lot annotations come after the expression, and apply to its result.+postingamountp :: AmountParseKind -> JournalParser m Amount+postingamountp kind =+ label "amount" $ do+ amt <- amountexprp kind <* lift skipNonNewlineSpaces+ amountannotationsp amt++-- | The cost, valuation and lot annotations which may follow an amount+-- (and any spaces after it). Returns the amount with its cost and cost basis set.+amountannotationsp :: Amount -> JournalParser m Amount+amountannotationsp amt = do+ let spaces = lift $ skipNonNewlineSpaces+ -- A cost, valuation expression or lot annotation may follow, in any order, each at most once.+ -- Each begins with a distinctive character or two, so look at those and run just the right+ -- parser, stopping at anything else or at a repeated kind. (A permutation parser was used before,+ -- but its failed attempts at the other alternatives made each cost cost ~3x as much as a posting.)+ -- costp, valuationexprp and lotnotep all begin with a parenthesis; costp is tried first,+ -- and backtracks if no @ follows, so that errors within a cost's amount are reported.+ let annotations mcost mval mcb mdate mnote = do+ (mc1, mc2) <- lift peekChars2+ case (mc1, mc2) of+ (Just '@', _) | isNothing mcost -> costp amt <* spaces >>= \x -> annotations (Just x) mval mcb mdate mnote+ (Just '(', Just '@') | isNothing mcost -> costp amt <* spaces >>= \x -> annotations (Just x) mval mcb mdate mnote+ (Just '(', Just '(') | isNothing mval -> valuationexprp <* spaces >>= \x -> annotations mcost (Just x) mcb mdate mnote+ (Just '{', _) | isNothing mcb -> lotcostp (aquantity amt) <* spaces >>= \x -> annotations mcost mval (Just x) mdate mnote+ (Just '[', _) | isNothing mdate -> lotdatep <* spaces >>= \x -> annotations mcost mval mcb (Just x) mnote+ (Just '(', _) | isNothing mnote -> lotnotep <* spaces >>= \x -> annotations mcost mval mcb mdate (Just x)+ _ -> pure (mcost, mval, mcb, mdate, mnote)+ (mcost, _valuationexpr, mlotcb, mlotdate, mlotnote) <- annotations Nothing Nothing Nothing Nothing Nothing+ -- Reject mixing consolidated {DATE,...} or {"LABEL",...} with ledger-style [DATE] or (NOTE)+ let isConsolidated = case mlotcb of+ Just cb | isJust (cbDate cb) || isJust (cbLabel cb) -> True+ _ -> False+ when (isConsolidated && (isJust mlotdate || isJust mlotnote)) $+ Fail.fail "hledger lot syntax {...} cannot be combined with ledger-style [DATE] or (NOTE)"+ let mcostbasis =+ case (mlotcb, mlotdate, mlotnote) of+ (Nothing, Nothing, Nothing) -> Nothing+ _ -> Just $ CostBasis+ { cbCost = mlotcb >>= cbCost+ , cbDate = (mlotcb >>= cbDate) <|> mlotdate+ , cbLabel = (mlotcb >>= cbLabel) <|> mlotnote+ }+ pure $ amt { acost = mcost, acostbasis = mcostbasis }++-- An amount with optional cost, but no cost basis.+amountnobasisp :: JournalParser m Amount+amountnobasisp =+ -- dbg "amountnobasisp" $ + label "amount" $ do+ let spaces = lift $ skipNonNewlineSpaces+ amt <- simpleamountp OrdinaryAmount+ spaces+ mprice <- optional $ costp amt <* spaces+ pure $ amt { acost = mprice }++-- An amount with no cost or cost basis.+-- A commodity-less amount will have the default commodity applied to it, unless it's a multiplier.+simpleamountp :: AmountParseKind -> JournalParser m Amount+simpleamountp = simpleamountp' Nothing++-- | Like simpleamountp, but when given a nesting depth, parses an operand of an amount expression+-- (see amountexprp), inside that many parentheses. There, an unquoted commodity symbol written+-- after the number can't begin with /, and inside parentheses can't contain ),+-- so that 10 EUR / 4 and (10 EUR + 5 EUR) are read as expressions.+simpleamountp' :: Maybe Int -> AmountParseKind -> JournalParser m Amount+simpleamountp' mdepth kind =+ -- dbg "simpleamountp" $+ do+ sign <- lift signp+ -- A symbol-first amount starts with a quote or a simple commodity symbol character;+ -- anything else (a digit or decimal mark, usually) is parsed as a number-first amount.+ -- Checking cheaply avoids a failed parse attempt for the latter, the common case.+ mc <- lift peekChar+ if maybe False startsCommoditySymbol mc then leftsymbolamountp sign else rightornosymbolamountp sign++ where+ startsCommoditySymbol c = c == '"' || not (isNonsimpleCommodityChar c)++ isoperand = isJust mdepth+ inparens = maybe False (> 0) mdepth+ rightsymbolp :: TextParser n CommoditySymbol+ rightsymbolp+ | inparens = quotedcommoditysymbolp <|> takeWhile1P Nothing (\c -> not (isNonsimpleCommodityChar c) && c /= ')')+ | otherwise = commoditysymbolp++ -- An amount with commodity symbol on the left.+ leftsymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount+ leftsymbolamountp sign = label "amount" $ do+ c <- shareText =<< lift commoditysymbolp+ mdecmarkStyle <- getDecimalMarkStyle+ mcommodityStyle <- getAmountStyle c+ -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461+ let suggestedStyle = mdecmarkStyle <|> mcommodityStyle+ commodityspaced <- lift skipNonNewlineSpaces'+ sign2 <- lift $ signp+ offBeforeNum <- getOffset+ ambiguousRawNum <- lift rawnumberp+ mExponent <- lift optionalexponentp+ offAfterNum <- getOffset+ let numRegion = (offBeforeNum, offAfterNum)+ (q,prec,mdec,mgrps) <- interpretNumber numRegion suggestedStyle ambiguousRawNum mExponent+ s <- shareAmountStyle amountstyle{ascommodityside=L, ascommodityspaced=commodityspaced, asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps}+ return nullamt{acommodity=c, aquantity=sign (sign2 q), astyle=s, acost=Nothing}++ -- An amount with commodity symbol on the right or no commodity symbol.+ -- A no-symbol amount will have the default commodity applied to it+ -- unless we are parsing a multiplier amount (*AMT).+ rightornosymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount+ rightornosymbolamountp sign = label "amount" $ do+ offBeforeNum <- getOffset+ ambiguousRawNum <- lift rawnumberp+ mExponent <- lift optionalexponentp+ offAfterNum <- getOffset+ let numRegion = (offBeforeNum, offAfterNum)+ -- A commodity symbol may follow the number, possibly after spaces; check cheaply first.+ (_, mnext) <- lift peekAfterSpaces+ mSpaceAndCommodity <- lift $+ if maybe False (\c -> startsCommoditySymbol c && not (isoperand && c == '/') && not (inparens && c == ')')) mnext+ then optional $ try $ (,) <$> skipNonNewlineSpaces' <*> rightsymbolp+ else pure Nothing+ case mSpaceAndCommodity of+ -- right symbol amount+ Just (commodityspaced, c0) -> do+ c <- shareText c0+ mdecmarkStyle <- getDecimalMarkStyle+ mcommodityStyle <- getAmountStyle c+ -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461+ let msuggestedStyle = mdecmarkStyle <|> mcommodityStyle+ (q,prec,mdec,mgrps) <- interpretNumber numRegion msuggestedStyle ambiguousRawNum mExponent+ s <- shareAmountStyle amountstyle{ascommodityside=R, ascommodityspaced=commodityspaced, asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps}+ return nullamt{acommodity=c, aquantity=sign q, astyle=s, acost=Nothing}+ -- no symbol amount+ Nothing -> do+ -- look for a number style to use when parsing, based on+ -- these things we've already parsed, in this order of preference:+ mdecmarkStyle <- getDecimalMarkStyle -- a decimal-mark CSV rule+ mcommodityStyle <- getAmountStyle "" -- a commodity directive for the no-symbol commodity+ mdefaultStyle <- getDefaultAmountStyle -- a D default commodity directive+ -- XXX no-symbol amounts in periodic transaction rules and auto posting rules ? #1461+ let msuggestedStyle = mdecmarkStyle <|> mcommodityStyle <|> mdefaultStyle+ (q,prec,mdec,mgrps) <- interpretNumber numRegion msuggestedStyle ambiguousRawNum mExponent+ -- if a default commodity has been set, apply it and its style to this amount+ -- (unless it's a multiplier in an automated posting);+ -- the number's own decimal mark and digit groups are kept where the default style has none+ defcs <- getDefaultCommodityAndStyle+ let (c,s) = case defcs of+ Just (defc,defs) | kind /= MultiplierAmount ->+ (defc, defs{asprecision=max (asprecision defs) prec+ ,asdecimalmark=asdecimalmark defs <|> mdec+ ,asdigitgroups=asdigitgroups defs <|> mgrps})+ _ -> ("", amountstyle{asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps})+ s' <- shareAmountStyle s+ return nullamt{acommodity=c, aquantity=sign q, astyle=s', acost=Nothing}++ -- For reducing code duplication. Doesn't parse anything. Has the type+ -- of a parser only in order to read the parse state and throw parse errors (for convenience).+ interpretNumber+ :: (Int, Int) -- offsets+ -> Maybe AmountStyle+ -> Either AmbiguousNumber RawNumber+ -> Maybe Integer+ -> JournalParser m (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)+ interpretNumber posRegion msuggestedStyle ambiguousNum mExp = do+ -- The decimal mark declared by a decimal-mark directive or CSV rule, which all numbers must use,+ -- except those declaring a display style.+ mrequiredmark <- if kind == StyleAmount then pure Nothing else jparsedecimalmark <$> get+ case interpretRawNumber mrequiredmark msuggestedStyle ambiguousNum mExp of+ Left errMsg -> customFailure $+ uncurry parseErrorAtRegion posRegion errMsg+ Right (q,p,d,g) -> pure (q, Precision p, d, g)++-- | A simple arithmetic expression involving amounts, evaluated to a single amount (#2648). Eg:+--+-- > $-21.60 + $-27.68 + $-5.03+-- > 10 EUR - 2.50 EUR+-- > $47.97 * 0.05+-- > ($200 + $15.75) / 3+-- > $10 + 5+-- > 1 / 1.14 EUR+--+-- The operands are simple amounts (see simpleamountp), or parenthesised expressions.+-- The operators are + - * and /. * and / are applied before + and -; otherwise, left to right.+-- Spaces around operators are optional, except before a / which follows a commodity symbol (10 EUR / 4).+-- A - or + directly before an operand or parenthesis is its sign.+--+-- + and - combine amounts of the same commodity; a number with no commodity symbol takes the+-- other side's commodity. The result has the larger of their precisions.+-- * and / take a plain number (with no commodity symbol) on at least one side.+-- Their result has the commodity and display style of the other side's amount+-- (with two plain numbers, the left one). So 1 / 1.14 EUR is 0.877.. EUR, as in Ledger.+-- So a result's precision is the most decimal places written in the amounts it was calculated from+-- (not counting plain numbers used with * or /).+-- The results of * and / are exact here, and so may have more decimal places than their precision.+-- They are rounded once the whole entry has been read, since the number of decimal places+-- depends on the other amounts in the entry (see transactionRoundCalculatedAmounts in+-- Hledger.Read.JournalReader). In a cost, they are kept exact (see costp).+-- Anything else (eg adding different commodities, or dividing by zero) is a parse error.+--+-- The operands are parsed without applying the default commodity (D), so that a number can+-- take its commodity from the expression; if the result has no commodity, the default commodity+-- is applied to it, as for a simple amount (unless it's a multiplier amount).+--+-- An amount with no operators is parsed the same as by simpleamountp.+amountexprp :: AmountParseKind -> JournalParser m Amount+amountexprp kind = do+ a <- sump (0 :: Int)+ if kind /= MultiplierAmount && T.null (acommodity a) then withDefaultCommodity a else pure a+ where+ spaces = lift skipNonNewlineSpaces++ -- if a default commodity has been set, apply it and its style (like simpleamountp)+ withDefaultCommodity a = do+ defcs <- getDefaultCommodityAndStyle+ case defcs of+ Just (defc, defs) -> do+ s <- shareAmountStyle defs{asprecision = max (asprecision defs) (asprecision $ astyle a)+ ,asdecimalmark = asdecimalmark defs <|> asdecimalmark (astyle a)+ ,asdigitgroups = asdigitgroups defs <|> asdigitgroups (astyle a)}+ pure a{acommodity = defc, astyle = s}+ Nothing -> pure a++ -- a sum or difference of products (depth is the number of enclosing parentheses)+ sump depth = productp depth >>= sumrestp depth+ sumrestp depth a = do+ mop <- lift peekChar+ case mop of+ Just op | op `elem` ['+','-'] -> do+ off <- getOffset+ b <- char op *> spaces *> productp depth+ off' <- getOffset+ c <- addAmounts (off, off') op a b+ sumrestp depth c+ _ -> pure a++ -- a product or quotient of factors+ productp depth = factorp depth >>= productrestp depth+ productrestp depth a = do+ mop <- lift peekChar+ case mop of+ Just op | op `elem` ['*','/'] -> do+ off <- getOffset+ b <- char op *> spaces *> factorp depth+ off' <- getOffset+ c <- multiplyAmounts (off, off') op a b+ productrestp depth c+ _ -> pure a++ -- a simple amount, or a parenthesised expression with an optional sign; and any following spaces.+ -- (Look ahead cheaply, so that ordinary amounts are parsed without backtracking.)+ -- Operands are parsed as multiplier amounts, ie without applying the default commodity.+ factorp depth = do+ s <- getInput+ case T.uncons s of+ Just ('(', _) -> parensp depth+ Just (c, rest) | c `elem` ['-','+'], "(" `T.isPrefixOf` T.dropWhile isNonNewlineSpace rest -> do+ a <- anySingle *> spaces *> parensp depth+ pure $ if c == '-' then a{aquantity = negate $ aquantity a} else a+ _ -> do+ a <- simpleamountp' (Just depth) MultiplierAmount+ -- In 10 EUR/4, the commodity symbol is read as EUR/. Explain that, rather than just+ -- reporting the unexpected 4. (A number can't follow an amount, so this is safe.)+ -- The symbol is checked first, so that the usual case needs no lookahead.+ when (ascommodityside (astyle a) == R && "/" `T.isSuffixOf` acommodity a) $ do+ off <- getOffset+ (spaced, mnext) <- lift peekAfterSpaces+ let looksdivided = case mnext of+ Just c | isDigit c -> True+ | not spaced -> c `elem` ['(','.','-','+']+ _ -> False+ when looksdivided $+ customFailure $ parseErrorAtRegion (off-1) off $+ "this / is read as part of the commodity symbol " ++ T.unpack (acommodity a)+ ++ "; to divide, write a space before it (eg 10 EUR / 4)"+ a <$ spaces++ parensp depth = char '(' *> spaces *> sump (depth+1) <* (char ')' <?> "closing parenthesis") <* spaces++ exprError (off, off') msg = customFailure $ parseErrorAtRegion off off' msg++ hascommodity = not . T.null . acommodity++ addAmounts reg op a b+ | hascommodity a && hascommodity b && acommodity a /= acommodity b = exprError reg $+ "can't " ++ (if op == '+' then "add" else "subtract") ++ " amounts with different commodities ("+ ++ T.unpack (acommodity a) ++ " and " ++ T.unpack (acommodity b) ++ ")"+ | otherwise = do+ -- a number with no commodity takes the other side's commodity and style+ let a' = if hascommodity a || not (hascommodity b) then a else b+ q = (if op == '+' then (+) else (-)) (aquantity a) (aquantity b)+ s <- shareAmountStyle (astyle a'){asprecision = max (asprecision $ astyle a) (asprecision $ astyle b)}+ pure a'{aquantity = q, astyle = s}++ multiplyAmounts reg op a b+ | op == '*' && hascommodity a && hascommodity b = exprError reg+ "can't multiply two amounts with commodity symbols; one side of * should be a plain number"+ | op == '/' && hascommodity a && hascommodity b = exprError reg+ "can't divide two amounts with commodity symbols; one side of / should be a plain number"+ | op == '/' && aquantity b == 0 = exprError reg "can't divide by zero"+ | op == '*' && hascommodity b = pure $ multiplyAmount (aquantity a) b+ | op == '*' = pure $ multiplyAmount (aquantity b) a+ -- a number divided by an amount, eg 1 / 1.14 EUR (inverting a rate), is in the amount's commodity, as in Ledger+ | hascommodity b = pure b{aquantity = aquantity a / aquantity b}+ | otherwise = pure $ divideAmount (aquantity b) a++-- | Try to parse a single-commodity amount from a string+parseamount :: String -> Either HledgerParseErrors Amount+parseamount s = runParser (evalStateT (amountp <* eof) nulljournal) "" (T.pack s)++-- | Try to parse a single-commodity amount from a string, using these commodities' styles to read an ambiguous number+-- (eg 10.000 EUR is ten thousand if EUR's decimal mark is a comma, or if it has no decimal places).+parseamountWithStyles :: M.Map CommoditySymbol AmountStyle -> String -> Either HledgerParseErrors Amount+parseamountWithStyles styles s = runParser (evalStateT (amountp <* eof) j) "" (T.pack s)+ where+ j = nulljournal{jdeclaredcommodities = M.mapWithKey commodity styles}+ commodity c st = Commodity{csymbol=c, cformat=Just st, ccomment="", ctags=[], caliases=[], csourcepos=initialPos ""}++-- | Parse a single-commodity amount from a string, or get an error.+parseamount' :: String -> Amount+parseamount' s =+ case parseamount s of+ Right amt -> amt+ Left err -> error' $ show err -- PARTIAL: XXX should throwError++-- | Like parseamount', but returns a MixedAmount.+parsemixedamount :: String -> Either HledgerParseErrors MixedAmount+parsemixedamount = fmap mixedAmount . parseamount++-- | Like parseamount', but returns a MixedAmount.+parsemixedamount' :: String -> MixedAmount+parsemixedamount' = mixedAmount . parseamount'++-- | Parse a minus or plus sign followed by zero or more spaces,+-- or nothing, returning a function that negates or does nothing.+signp :: Num a => TextParser m (a -> a)+signp = do+ -- check the next character first: most amounts have no sign+ mc <- peekChar+ case mc of+ Just '-' -> negate <$ (char '-' *> skipNonNewlineSpaces)+ Just '+' -> id <$ (char '+' *> skipNonNewlineSpaces)+ _ -> pure id++commoditysymbolp :: TextParser m CommoditySymbol+commoditysymbolp = (do+ mc <- peekChar+ if mc == Just '"' then quotedcommoditysymbolp else simplecommoditysymbolp+ ) <?> "commodity symbol"++quotedcommoditysymbolp :: TextParser m CommoditySymbol+quotedcommoditysymbolp =+ between (char '"') (char '"') $ takeWhileP Nothing f+ where f c = c /= ';' && c /= '\n' && c /= '\"'++simplecommoditysymbolp :: TextParser m CommoditySymbol+simplecommoditysymbolp = takeWhile1P Nothing (not . isNonsimpleCommodityChar)++-- | Ledger-style cost notation:+-- @ UNITAMT, @@ TOTALAMT, (@) UNITAMT, or (@@) TOTALAMT. The () are ignored.+-- The amount can be an amount expression (see amountexprp) (#2857).+costp :: Amount -> JournalParser m AmountCost+costp baseAmt =+ -- dbg "costp" $+ label "transaction price" $ do+ -- https://www.ledger-cli.org/3.0/doc/ledger3.html#Virtual-posting-costs+ -- (optional parts are checked for cheaply before parsing, as usual)+ -- ( might begin something else, like a valuation expression or lot note, so backtrack if no @ follows+ parenthesised <- (== Just '(') <$> lift peekChar+ if parenthesised then void $ try $ string "(@" else void $ char '@'+ totalCost <- (== Just '@') <$> lift peekChar+ when totalCost $ void $ char '@'+ when parenthesised $ void $ char ')'++ lift skipNonNewlineSpaces+ priceAmount <- showCalculatedFully <$> amountexprp OrdinaryAmount -- <?> "unpriced amount (specifying a price)"++ let amtsign' = signum $ aquantity baseAmt+ amtsign = if amtsign' == 0 then 1 else amtsign'++ pure $ if totalCost+ then TotalCost priceAmount{aquantity=amtsign * aquantity priceAmount}+ else UnitCost priceAmount+ where+ -- A cost calculated with * or / in an amount expression has more decimal places than were written.+ -- Unlike a posting amount, it is kept exact (not rounded), so that eg (1 / 1.14 EUR) works as a rate.+ -- Show it exactly, or if it's a repeating decimal, with 8 decimal places (or more if written).+ showCalculatedFully a+ | amountInternalPrecision a > amountDisplayPrecision a =+ amountSetPrecisionMin (amountDisplayPrecision a) $ amountSetFullPrecisionUpTo Nothing a+ | otherwise = a++-- | A valuation function or value can be written in double parentheses after an amount.+valuationexprp :: JournalParser m ()+valuationexprp =+ -- dbg "valuationexprp" $+ label "valuation expression" $ do+ string "(("+ _ <- T.strip . T.pack <$> (many $ noneOf [')','\n']) -- XXX other line endings ?+ string "))"+ return ()++balanceassertionp :: JournalParser m BalanceAssertion+balanceassertionp = do+ sourcepos <- getSourcePos'+ char '='+ istotal <- (== Just '=') <$> lift peekChar+ when istotal $ void $ char '='+ isinclusive <- (== Just '*') <$> lift peekChar+ when isinclusive $ void $ char '*'+ lift skipNonNewlineSpaces+ -- this amount can have a cost, but not a cost basis.+ -- balance assertions ignore it, but balance assignments will use it+ a <- amountnobasisp <?> "amount (for a balance assertion or assignment)"+ return BalanceAssertion+ { baamount = a+ , batotal = istotal+ , bainclusive = isinclusive+ , baposition = sourcepos+ }++-- Parse lot cost in curly braces.+-- Accepts either:+-- Ledger-style: {UNITCOST} or {{TOTALCOST}} or {=FIXEDUNITCOST} or {{=FIXEDTOTALCOST}} or {}+-- Consolidated: {DATE, "LABEL", COST} or {{DATE, "LABEL", TOTALCOST}}+-- with all fields optional and in DLC order+-- If total cost syntax {{}} is used, the parsed cost is converted to unit cost+-- by dividing by the posting quantity (with full Decimal precision, so that+-- `{{T}}` and `@@T` yield equal per-unit Decimals — important for the strict+-- comparison in `journalCheckAcquireBasis`).+lotcostp :: Quantity -> JournalParser m CostBasis+lotcostp postingqty =+ -- dbg "lotcostp" $+ label "lot cost" $ do+ char '{'+ doublebrace <- option False $ char '{' >> pure True+ lift skipNonNewlineSpaces+ -- Peek to decide: consolidated vs ledger+ -- consolidated starts with date (digit), label ("), or empty }+ -- ledger starts with =, amount, or empty }+ c <- lookAhead anySingle+ cb <- case c of+ '}' -> pure (CostBasis Nothing Nothing Nothing)+ '=' -> ledgerCost+ '"' -> consolidatedNoDate+ _ -> tryDateOrLedger+ -- A comma, quote or digit here means another part follows the cost,+ -- ie the parts are out of order; say so, rather than "expecting '}'".+ mnext <- optional $ lookAhead anySingle+ when (maybe False startsAnotherPart mnext) wrongOrderError+ char '}'+ when doublebrace $ void $ char '}'+ pure $ if doublebrace then mapCbCost convertToUnitCost cb else cb+ where+ -- Apply a function to the cost amount, if any, of a CostBasis.+ mapCbCost f (CostBasis md ml mc) = CostBasis md ml (fmap f mc)++ startsAnotherPart c = c == ',' || c == '"' || isDigit c++ wrongOrderError = do+ off <- getOffset+ customFailure $ parseErrorAt off+ "cost basis parts must be in this order (if present): {DATE, \"LABEL\", COST}"++ -- Does a date (YYYY-D...) come next ?+ looksLikeDatep = option False $ lookAhead $ try $+ count 4 digitChar >> char '-' >> digitChar >> pure True++ -- The inner parsers below leave the closing }(}) for the outer parser.++ tryDateOrLedger = do+ -- Does input look like a date (YYYY-D...) ? If so, commit to consolidated+ -- date parsing (no try), so invalid dates give clear errors instead of+ -- falling through to the amount parser with a confusing message.+ looksLikeDate <- looksLikeDatep+ if looksLikeDate+ then do+ d <- datep+ lift skipNonNewlineSpaces+ void $ lookAhead (oneOf [',','}'])+ consolidatedAfterDate d+ else ledgerCost -- not a date, parse as ledger amount++ consolidatedAfterDate d = do+ -- after date: optional ", LABEL", optional ", COST"+ mlabel <- optional $ try $ char ',' >> lift skipNonNewlineSpaces >> quotedLabelp <* lift skipNonNewlineSpaces+ mcost <- optional $ char ',' >> lift skipNonNewlineSpaces >> simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces+ pure $ CostBasis (Just d) mlabel mcost++ consolidatedNoDate = do+ -- parse "LABEL", then optional ", COST" (a date here is out of order)+ mlabel <- Just <$> quotedLabelp+ lift skipNonNewlineSpaces+ mcost <- optional $ do+ char ',' >> lift skipNonNewlineSpaces+ looksLikeDate <- looksLikeDatep+ when looksLikeDate wrongOrderError+ simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces+ pure $ CostBasis Nothing mlabel mcost++ quotedLabelp = do+ char '"'+ lbl <- T.pack <$> many (noneOf ['"', '\n'])+ char '"'+ pure lbl++ ledgerCost = do+ _fixed <- fmap isJust $ optional $ char '='+ lift skipNonNewlineSpaces+ ma <- optional $ simpleamountp OrdinaryAmount+ lift skipNonNewlineSpaces+ pure $ CostBasis Nothing Nothing ma++ -- Divide with full Decimal precision (so `{{T}}` and `@@T` give equal+ -- per-unit Decimals for the strict basis check), and widen display+ -- precision to show the quotient's digits. A total basis is unsigned,+ -- like a total cost: divide by the quantity's magnitude so a negative+ -- posting (a disposal, or a short open) gets a positive unit basis.+ convertToUnitCost = divideAmountAndUpdatePrecision (abs postingqty)++-- Parse a Ledger-style [LOTDATE].+lotdatep :: JournalParser m Day+lotdatep =+ -- dbg "lotdatep" $+ label "ledger-style lot date" $ do+ char '['+ lift skipNonNewlineSpaces+ d <- datep+ lift skipNonNewlineSpaces+ char ']'+ return d++-- Parse a Ledger-style (LOT NOTE).+-- Any double-quote characters inside the parentheses are stripped,+-- because they would disrupt round-tripping of hledger's label syntax.+lotnotep :: JournalParser m Text+lotnotep =+ -- dbg "lotnotep" $+ label "ledger-style lot note" $ do+ char '('+ lift skipNonNewlineSpaces+ note <- stripEnd . T.pack <$> (many $ noneOf [')','\n']) -- XXX other line endings ?+ char ')'+ return $ T.filter (/= '"') note++-- | Parse a string representation of a number for its value and display+-- attributes.+--+-- Some international number formats are accepted, eg either period or comma+-- may be used for the decimal mark, and the other of these may be used for+-- separating digit groups in the integer part. See+-- http://en.wikipedia.org/wiki/Decimal_separator for more examples.+--+-- This returns: the parsed numeric value, the precision (number of digits+-- seen following the decimal mark), the decimal mark character used if any,+-- and the digit group style if any.+--+numberp :: Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)+numberp suggestedStyle = label "number" $ do+ -- a number is an optional sign followed by a sequence of digits possibly+ -- interspersed with periods, commas, or both+ -- dbgparse 0 "numberp"+ sign <- signp+ ambiguousNum <- rawnumberp+ mExp <- optionalexponentp+ dbg7 "numberp suggestedStyle" suggestedStyle `seq` return ()+ case dbg7 "numberp quantity,precision,mdecimalpoint,mgrps"+ $ interpretRawNumber Nothing suggestedStyle ambiguousNum mExp of+ Left errMsg -> Fail.fail errMsg+ Right (q, p, d, g) -> pure (sign q, p, d, g)++exponentp :: TextParser m Integer+exponentp = char' 'e' *> signp <*> decimal <?> "exponent"++-- | Parse an exponent if one follows, checking the next character first,+-- since most numbers have none.+optionalexponentp :: TextParser m (Maybe Integer)+optionalexponentp = do+ mc <- peekChar+ if mc == Just 'e' || mc == Just 'E' then optional (try exponentp) else pure Nothing++-- | Interpret a possibly-ambiguous raw number as a decimal number.+-- The suggested style (from a decimal-mark or commodity directive, eg), if any,+-- is used to disambiguate it.+-- If a required decimal mark is given (from a decimal-mark directive, eg),+-- the number must use only that decimal mark.+interpretRawNumber+ :: Maybe Char+ -> Maybe AmountStyle+ -> Either AmbiguousNumber RawNumber+ -> Maybe Integer+ -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)+interpretRawNumber mrequiredmark msuggestedStyle ambiguousNum mExp = do+ raw <- checkDecimalMark $ either (disambiguateNumber msuggestedStyle) id ambiguousNum+ fromRawNumber raw mExp+ where+ checkDecimalMark raw = case mrequiredmark of+ Just d+ | Just m <- rawDecimalMark raw, m /= d ->+ declared d $ "but this number's decimal mark is " ++ show m+ -- rawnumberp decides that a mark appearing more than once is a digit group mark.+ -- If that's the declared decimal mark, the number is probably mistyped (eg 1.2.34);+ -- don't silently read it as a larger number.+ | Just d == rawDigitGroupMark raw ->+ declared d "so it can appear only once"+ _ -> Right raw+ declared d msg = Left $ "invalid number: the decimal mark is declared to be " ++ show d ++ ", " ++ msg+ rawDecimalMark (NoSeparators _ mdec) = fst <$> mdec+ rawDecimalMark (WithSeparators _ _ mdec) = fst <$> mdec+ rawDigitGroupMark (WithSeparators sep _ _) = Just sep+ rawDigitGroupMark NoSeparators{} = Nothing++-- | Interpret a raw number as a decimal number.+--+-- Returns:+-- - the decimal number+-- - the precision (number of digits after the decimal point)+-- - the decimal point character, if any+-- - the digit group style, if any (digit group character and sizes of digit groups)+fromRawNumber+ :: RawNumber+ -> Maybe Integer+ -> Either String+ (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)+fromRawNumber (WithSeparators{}) (Just _) =+ Left "invalid number: digit separators and exponents may not be used together"+fromRawNumber raw mExp = do+ (quantity, precision) <- toQuantity (fromMaybe 0 mExp) (digitGroup raw) (decimalGroup raw)+ -- force the Maybes' contents, so that parsed amount styles don't retain the raw number+ let !mdec = forceMaybe $ mDecPt raw+ !mgrps = forceMaybe $ digitGroupStyle raw+ return (quantity, precision, mdec, mgrps)+ where+ forceMaybe m = case m of+ Just x -> x `seq` m+ Nothing -> m+ toQuantity :: Integer -> DigitGrp -> DigitGrp -> Either String (Quantity, Word8)+ toQuantity e preDecimalGrp postDecimalGrp+ | precision < 0 = Right (Decimal 0 (digitGrpNum * 10^(-precision)), 0)+ | precision < 256 = Right (Decimal precision8 digitGrpNum, precision8)+ | otherwise = Left "invalid number: numbers with more than 255 decimal places are currently not supported"+ where+ digitGrpNum = digitGroupNumber $ preDecimalGrp <> postDecimalGrp+ precision = toInteger (digitGroupLength postDecimalGrp) - e+ precision8 = fromIntegral precision :: Word8++ mDecPt (NoSeparators _ mDecimals) = fst <$> mDecimals+ mDecPt (WithSeparators _ _ mDecimals) = fst <$> mDecimals+ decimalGroup (NoSeparators _ mDecimals) = maybe mempty snd mDecimals+ decimalGroup (WithSeparators _ _ mDecimals) = maybe mempty snd mDecimals+ digitGroup (NoSeparators digitGrp _) = digitGrp+ digitGroup (WithSeparators _ digitGrps _) = mconcat digitGrps+ digitGroupStyle (NoSeparators _ _) = Nothing+ digitGroupStyle (WithSeparators sep grps _) = Just . DigitGroups sep $ groupSizes grps++ -- Outputs digit group sizes from least significant to most significant+ groupSizes :: [DigitGrp] -> [Word8]+ groupSizes digitGrps = reverse $ case map (fromIntegral . digitGroupLength) digitGrps of+ (a:b:cs) | a < b -> b:cs+ gs -> gs++disambiguateNumber :: Maybe AmountStyle -> AmbiguousNumber -> RawNumber+disambiguateNumber msuggestedStyle (AmbiguousNumber grp1 sep grp2) =+ -- If present, use the suggested style to disambiguate;+ -- otherwise, assume that the separator is a decimal point where possible.+ if isDecimalMark sep &&+ maybe True (sep `isValidDecimalBy`) msuggestedStyle+ then NoSeparators grp1 (Just (sep, grp2))+ else WithSeparators sep [grp1, grp2] Nothing+ where+ -- A style with neither a decimal mark nor digit groups (eg from a CSV currency rule+ -- like "currency $", unlike a D or commodity directive) says nothing about the number.+ isValidDecimalBy :: Char -> AmountStyle -> Bool+ isValidDecimalBy c = \case+ AmountStyle{asdecimalmark = Just d} -> d == c+ AmountStyle{asdigitgroups = Just (DigitGroups g _)} -> g /= c+ _ -> True++-- | Parse and interpret the structure of a number without external hints.+-- Numbers are digit strings, possibly separated into digit groups by one+-- of two types of separators. (1) Numbers may optionally have a decimal+-- mark, which may be either a period or comma. (2) Numbers may+-- optionally contain digit group marks, which must all be either a+-- period, a comma, or a space.+--+-- It is our task to deduce the characters used as decimal mark and+-- digit group mark, based on the allowed syntax. For instance, we+-- make use of the fact that a decimal mark can occur at most once and+-- must be to the right of all digit group marks.+--+-- >>> parseTest rawnumberp "1,234,567.89"+-- Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))+-- >>> parseTest rawnumberp "1,000"+-- Left (AmbiguousNumber "1" ',' "000")+-- >>> parseTest rawnumberp "1 000"+-- Right (WithSeparators ' ' ["1","000"] Nothing)+-- >>> parseTest rawnumberp "1'000"+-- Right (WithSeparators '\'' ["1","000"] Nothing)+-- >>> parseTest rawnumberp "1_000"+-- Right (WithSeparators '_' ["1","000"] Nothing)+--+rawnumberp :: TextParser m (Either AmbiguousNumber RawNumber)+rawnumberp = label "number" $ do+ -- (The next characters are inspected directly in a few places below,+ -- avoiding failed parse attempts on this hot path.)+ mc <- peekChar+ rawNumber <- if maybe False isDecimalMark mc then Right <$> leadingDecimalPt else leadingDigits++ -- Guard against mistyped numbers+ mExtraDecimalSep <- peekChar+ when (maybe False isDecimalMark mExtraDecimalSep) $+ Fail.fail "invalid number (invalid use of separator)"++ next2 <- peekChars2+ case next2 of+ (Just ' ', Just d) | isDigit d -> do+ off <- getOffset+ customFailure $ parseErrorAt (off + 1) "invalid number (excessive trailing digits)"+ _ -> pure ()++ return $ dbg7 "rawnumberp" rawNumber+ where++ leadingDecimalPt :: TextParser m RawNumber+ leadingDecimalPt = do+ decPt <- satisfy isDecimalMark+ decGrp <- digitgroupp+ pure $ NoSeparators mempty (Just (decPt, decGrp))++ leadingDigits :: TextParser m (Either AmbiguousNumber RawNumber)+ leadingDigits = do+ grp1 <- digitgroupp+ -- More digit groups (after a separator) or a decimal mark may follow; most often neither does.+ next2 <- peekChars2+ let more = case next2 of+ (Just c1, _) | isDecimalMark c1 -> True+ (Just c1, Just c2) | isDigitSeparatorChar c1 && isDigit c2 -> True+ _ -> False+ if more+ then withSeparators grp1 <|> fmap Right (trailingDecimalPt grp1)+ <|> pure (Right $ NoSeparators grp1 Nothing)+ else pure (Right $ NoSeparators grp1 Nothing)++ withSeparators :: DigitGrp -> TextParser m (Either AmbiguousNumber RawNumber)+ withSeparators grp1 = do+ (sep, grp2) <- try $ (,) <$> satisfy isDigitSeparatorChar <*> digitgroupp+ grps <- many $ try $ char sep *> digitgroupp++ let digitGroups = grp1 : grp2 : grps+ fmap Right (withDecimalPt sep digitGroups)+ <|> pure (withoutDecimalPt grp1 sep grp2 grps)++ withDecimalPt :: Char -> [DigitGrp] -> TextParser m RawNumber+ withDecimalPt digitSep digitGroups = do+ decPt <- satisfy $ \c -> isDecimalMark c && c /= digitSep+ decDigitGrp <- option mempty digitgroupp++ pure $ WithSeparators digitSep digitGroups (Just (decPt, decDigitGrp))++ withoutDecimalPt+ :: DigitGrp+ -> Char+ -> DigitGrp+ -> [DigitGrp]+ -> Either AmbiguousNumber RawNumber+ withoutDecimalPt grp1 sep grp2 grps+ | null grps && isDecimalMark sep =+ Left $ AmbiguousNumber grp1 sep grp2+ | otherwise = Right $ WithSeparators sep (grp1:grp2:grps) Nothing++ trailingDecimalPt :: DigitGrp -> TextParser m RawNumber+ trailingDecimalPt grp1 = do+ decPt <- satisfy isDecimalMark+ pure $ NoSeparators grp1 (Just (decPt, mempty))++isDigitSeparatorChar :: Char -> Bool+isDigitSeparatorChar c = c == '.' || c == ',' || c == '\'' || c == '_' || isDigitSeparatorSpaceChar c++-- | Kinds of unicode space character we accept as digit group marks.+-- See also https://en.wikipedia.org/wiki/Decimal_separator#Digit_grouping .+isDigitSeparatorSpaceChar :: Char -> Bool+isDigitSeparatorSpaceChar c =+ c == ' ' -- space+ || c == ' ' -- no-break space+ || c == ' ' -- en space+ || c == ' ' -- em space+ || c == ' ' -- punctuation space+ || c == ' ' -- thin space+ || c == ' ' -- narrow no-break space+ || c == ' ' -- medium mathematical space++-- | Some kinds of number literal we might parse.+data RawNumber+ = NoSeparators DigitGrp (Maybe (Char, DigitGrp))+ -- ^ A number with no digit group marks (eg 100),+ -- or with a leading or trailing comma or period+ -- which (apparently) we interpret as a decimal mark (like 100. or .100)+ | WithSeparators Char [DigitGrp] (Maybe (Char, DigitGrp))+ -- ^ A number with identifiable digit group marks+ -- (eg 1,000,000 or 1,000.50 or 1 000)+ deriving (Show, Eq)++-- | Another kind of number literal: this one contains either a digit+-- group separator or a decimal mark, we're not sure which (eg 1,000 or 100.50).+data AmbiguousNumber = AmbiguousNumber DigitGrp Char DigitGrp+ deriving (Show, Eq)++-- | Description of a single digit group in a number literal.+-- "Thousands" is one well known digit grouping, but there are others.+data DigitGrp = DigitGrp {+ digitGroupLength :: !Word, -- ^ The number of digits in this group.+ -- This is Word to avoid the need to do overflow+ -- checking for the Semigroup instance of DigitGrp.+ digitGroupNumber :: !Integer -- ^ The natural number formed by this group's digits. This should always be positive.+} deriving (Eq)++-- | A custom show instance, showing digit groups as the parser saw them.+instance Show DigitGrp where+ show (DigitGrp len n) = "\"" ++ padding ++ numStr ++ "\""+ where numStr = show n+ padding = genericReplicate (toInteger len - toInteger (length numStr)) '0'++instance Sem.Semigroup DigitGrp where+ DigitGrp l1 n1 <> DigitGrp l2 n2 = DigitGrp (l1 + l2) (n1 * 10^l2 + n2)++instance Monoid DigitGrp where+ mempty = DigitGrp 0 0+ mappend = (Sem.<>)++digitgroupp :: TextParser m DigitGrp+digitgroupp = label "digits"+ $ makeGroup <$> takeWhile1P (Just "digit") isDigit+ where+ makeGroup = uncurry DigitGrp . T.foldl' step (0, 0)+ step (!l, !a) c = (l+1, a*10 + fromIntegral (digitToInt c))++--- *** comments++multilinecommentp :: TextParser m ()+multilinecommentp = startComment *> anyLine `skipManyTill` endComment+ where+ startComment = string "comment" *> trailingSpaces+ endComment = eof <|> string "end comment" *> trailingSpaces++ trailingSpaces = skipNonNewlineSpaces <* newline+ anyLine = void $ takeWhileP Nothing (/='\n') *> newline++{-# INLINABLE multilinecommentp #-}++-- | A blank or comment line in journal format: a line that's empty or+-- containing only whitespace or whose first non-whitespace character+-- is semicolon, hash, or star. See also emptyorcommentlinep2.+emptyorcommentlinep :: TextParser m ()+emptyorcommentlinep = do+ dp "emptyorcommentlinep"+ skipNonNewlineSpaces+ mc <- peekChar+ if maybe False isLineCommentStart mc then skiplinecommentp else void newline+ where+ skiplinecommentp :: TextParser m ()+ skiplinecommentp = do+ satisfy isLineCommentStart+ void $ takeWhileP Nothing (/= '\n')+ optional newline+ pure ()++{-# INLINABLE emptyorcommentlinep #-}++-- | A newer comment line parser.+-- Parses a line which is empty, all blanks, or whose first non-blank character is one of those provided.+-- A final newline is optional.+emptyorcommentlinep2 :: [Char] -> TextParser m ()+emptyorcommentlinep2 cs =+ label ("empty line or comment line beginning with "++cs) $ do+ dp "emptyorcommentlinep2"+ skipNonNewlineSpaces+ void newline <|> void commentp+ where+ commentp = do+ choice (map (some.char) cs)+ takeWhileP Nothing (/='\n') <* optional newline++-- | Is this a character that, as the first non-whitespace on a line,+-- starts a comment line ?+isLineCommentStart :: Char -> Bool+isLineCommentStart '#' = True+isLineCommentStart '*' = True+isLineCommentStart ';' = True+isLineCommentStart _ = False++-- | Is this a character that, appearing anywhere within a line,+-- starts a comment ?+isSameLineCommentStart :: Char -> Bool+isSameLineCommentStart ';' = True+isSameLineCommentStart _ = False++-- | Parse a comment following a journal item, possibly continued on multiple lines,+-- and return the comment text.+--+-- >>> rtp followingcommentp "" -- no comment+-- Right ""+-- >>> rtp followingcommentp ";" -- just a (empty) same-line comment. newline is added+-- Right "\n"+-- >>> rtp followingcommentp "; \n"+-- Right "\n"+-- >>> rtp followingcommentp ";\n ;\n" -- a same-line and a next-line comment+-- Right "\n\n"+-- >>> rtp followingcommentp "\n ;\n" -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.+-- Right "\n\n"+--+followingcommentp :: TextParser m Text+followingcommentp = fst <$> followingcommentpWith (void $ takeWhileP Nothing (/= '\n'))++{-# INLINABLE followingcommentp #-}++-- | Parse a following comment, possibly continued on multiple lines,+-- using the provided line parser to parse each line.+-- This returns the comment text, and the combined results from the line parser.+--+-- Following comments are a 1-or-more-lines comment,+-- beginning with a semicolon possibly preceded by whitespace on the current line,+-- or with an indented semicolon on the next line.+-- Additional lines also must begin with an indented semicolon.+--+-- Like Ledger, we sometimes allow data to be embedded in comments.+-- account directive comments and transaction comments can contain tags,+-- and posting comments can contain tags or bracketed posting dates.+-- This helper lets us handle these variations. +-- The line parser should consume all input up until the next newline.+-- See followingcommentp for some tests.+--+followingcommentpWith :: (Monoid a, Show a) => TextParser m a -> TextParser m (Text, a)+followingcommentpWith contentp = do+ skipNonNewlineSpaces+ -- there can be 0 or 1 sameLine (checking for its semicolon cheaply, as usually there is none)+ mc <- peekChar+ sameLine <- if mc == Just ';' then (:[]) <$> (headerp *> match' contentp) else pure []+ _ <- eolof+ -- there can be 0 or more nextLines+ nextLines <- manyWhile nextlineiscomment $+ skipNonNewlineSpaces1 *> headerp *> match' contentp <* eolof+ let+ -- if there's just a next-line comment, insert an empty same-line comment+ -- so the next-line comment doesn't get rendered as a same-line comment.+ sameLine' | null sameLine && not (null nextLines) = [("",mempty)]+ | otherwise = sameLine+ (texts, contents) = unzip $ sameLine' ++ nextLines+ strippedCommentText = T.unlines $ map T.strip texts+ commentContent = mconcat contents+ pure (strippedCommentText, commentContent)++ where+ headerp = char ';' *> skipNonNewlineSpaces+ -- does the next line begin with an indented semicolon ?+ nextlineiscomment = do+ (spaced, mnext) <- peekAfterSpaces+ pure $ spaced && mnext == Just ';'++{-# INLINABLE followingcommentpWith #-}+++-- Parse the tags from a single comment line, eg for use with followingcommentpWith.+-- XXX what part of a comment line ? leading whitespace / semicolon or not ?+commentlinetagsp :: TextParser m [Tag]+commentlinetagsp = do+ -- XXX sketchy+ tagName <- (last . T.split isSpace) <$> takeWhileP Nothing (\c -> c /= ':' && c /= '\n')+ atColon tagName <|> pure [] -- if not ':', then either '\n' or EOF++ where+ atColon :: Text -> TextParser m [Tag]+ atColon name = char ':' *> do+ if T.null name+ then commentlinetagsp+ else do+ skipNonNewlineSpaces+ val <- tagValue+ let tag = (name, val)+ (tag:) <$> commentlinetagsp++ tagValue :: TextParser m Text+ tagValue = do+ val <- T.strip <$> takeWhileP Nothing (\c -> c /= ',' && c /= '\n')+ _ <- optional $ char ','+ pure val++{-# INLINABLE commentlinetagsp #-}+++-- | Parse a transaction comment and extract its tags.+--+-- The first line of a transaction may be followed a 1-or-more-lines comment,+-- beginning with a semicolon possibly preceded by whitespace on the current line,+-- or with an indented semicolon on the next line. Additional lines also must+-- begin with an indented semicolon.+-- See also followingcommentpWith.+--+-- 2000/1/1 ; a transaction comment starting on the same line ...+-- ; extending to the next line+-- account1 $1+-- account2+--+-- Tags are name-value pairs.+--+-- >>> let getTags (_,tags) = tags+-- >>> let parseTags = fmap getTags . rtp transactioncommentp+--+-- >>> parseTags "; name1: val1, name2:all this is value2"+-- Right [("name1","val1"),("name2","all this is value2")]+--+-- A tag's name must be immediately followed by a colon, without+-- separating whitespace. The corresponding value consists of all the text+-- following the colon up until the next colon or newline, stripped of+-- leading and trailing whitespace.+--+transactioncommentp :: TextParser m (Text, [Tag])+transactioncommentp = followingcommentpWith commentlinetagsp+{-# INLINABLE transactioncommentp #-}+++-- | Parse a posting comment and extract its tags and dates.+--+-- Postings may be followed by comments, which begin with semicolons and+-- extend to the end of the line. Posting comments may span multiple+-- lines, but comment lines below the posting must be preceded by+-- leading whitespace.+--+-- 2000/1/1+-- account1 $1 ; a posting comment starting on the same line ...+-- ; extending to the next line+--+-- account2+-- ; a posting comment beginning on the next line+--+-- Tags are name-value pairs.+--+-- >>> let getTags (_,tags,_,_) = tags+-- >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing)+--+-- >>> parseTags "; name1: val1, name2:all this is value2"+-- Right [("name1","val1"),("name2","all this is value2")]+--+-- A tag's name must be immediately followed by a colon, without+-- separating whitespace. The corresponding value consists of all the text+-- following the colon up until the next colon or newline, stripped of+-- leading and trailing whitespace.+--+-- Posting dates may be expressed with "date"/"date2" tags or with+-- bracketed date syntax. Posting dates will inherit their year from the+-- transaction date if the year is not specified. We throw parse errors on+-- invalid dates.+--+-- >>> let getDates (_,_,d1,d2) = (d1, d2)+-- >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))+--+-- >>> parseDates "; date: 1/2, date2: 1999/12/31"+-- Right (Just 2000-01-02,Just 1999-12-31)+-- >>> parseDates "; [1/2=1999/12/31]"+-- Right (Just 2000-01-02,Just 1999-12-31)+--+-- Example: tags, date tags, and bracketed dates+-- >>> rtp (postingcommentp (Just 2000)) "; a:b, date:3/4, [=5/6]"+-- Right ("a:b, date:3/4, [=5/6]\n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06)+--+-- Example: extraction of dates from date tags ignores trailing text+-- >>> rtp (postingcommentp (Just 2000)) "; date:3/4=5/6"+-- Right ("date:3/4=5/6\n",[("date","3/4=5/6")],Just 2000-03-04,Nothing)+--+-- Example: date tags with empty values set no date+-- >>> rtp (postingcommentp (Just 2000)) "; date:, date2: , a:b"+-- Right ("date:, date2: , a:b\n",[("date",""),("date2",""),("a","b")],Nothing,Nothing)+--+postingcommentp+ :: Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)+postingcommentp mYear = do+ (commentText, (tags, dateTags)) <-+ followingcommentpWith (commenttagsanddatesp mYear)+ let mdate = snd <$> find ((=="date") .fst) dateTags+ mdate2 = snd <$> find ((=="date2").fst) dateTags+ pure (commentText, tags, mdate, mdate2)+{-# INLINABLE postingcommentp #-}+++commenttagsanddatesp+ :: Maybe Year -> TextParser m ([Tag], [DateTag])+commenttagsanddatesp mYear = do+ (txt, dateTags) <- match $ readUpTo ':'+ -- next char is either ':' or '\n' (or EOF)+ let tagName = last (T.split isSpace txt)+ (fmap.second) (dateTags++) (atColon tagName) <|> pure ([], dateTags) -- if not ':', then either '\n' or EOF++ where+ readUpTo :: Char -> TextParser m [DateTag]+ readUpTo end = do+ void $ takeWhileP Nothing (\c -> c /= end && c /= '\n' && c /= '[')+ -- if not '[' then ':' or '\n' or EOF+ atBracket (readUpTo end) <|> pure []++ atBracket :: TextParser m [DateTag] -> TextParser m [DateTag]+ atBracket cont = do+ -- Uses the fact that bracketed date-tags cannot contain newlines+ dateTags <- option [] $ lookAhead (bracketeddatetagsp mYear)+ _ <- char '['+ dateTags' <- cont+ pure $ dateTags ++ dateTags'++ atColon :: Text -> TextParser m ([Tag], [DateTag])+ atColon name = char ':' *> do+ skipNonNewlineSpaces+ (tags, dateTags) <- case name of+ "" -> pure ([], [])+ "date" -> dateValue name+ "date2" -> dateValue name+ _ -> tagValue name+ _ <- optional $ char ','+ bimap (tags++) (dateTags++) <$> commenttagsanddatesp mYear++ -- An empty value (allowed for compatibility with Ledger, where date: is ordinary metadata)+ -- makes an ordinary tag, setting no date.+ dateValue :: Text -> TextParser m ([Tag], [DateTag])+ dateValue name = (lookAhead (void (satisfy (\c -> c == ',' || c == '\n')) <|> eof) *> tagValue name) <|> do+ (txt, (date, dateTags)) <- match' $ do+ date <- datep' mYear+ dateTags <- readUpTo ','+ pure (date, dateTags)+ let val = T.strip txt+ pure $ ( [(name, val)]+ , (name, date) : dateTags )++ tagValue :: Text -> TextParser m ([Tag], [DateTag])+ tagValue name = do+ (txt, dateTags) <- match' $ readUpTo ','+ let val = T.strip txt+ pure $ ( [(name, val)]+ , dateTags )++{-# INLINABLE commenttagsanddatesp #-}++-- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as+-- "date" and/or "date2" tags. Anything that looks like an attempt at+-- this (a square-bracketed sequence of 0123456789/-.= containing at+-- least one digit and one date separator) is also parsed, and will+-- throw an appropriate error.+--+-- The dates are parsed in full here so that errors are reported in+-- the right position. A missing year in DATE can be inferred if a+-- default date is provided. A missing year in DATE2 will be inferred+-- from DATE.+--+-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"+-- Right [("date",2016-01-02),("date2",2016-03-04)]+--+-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"+-- Left ...not a bracketed date...+--+-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"+-- Left ...1:2:...This is not a valid date...+--+-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"+-- Left ...1:2:...This partial date can not be parsed because the current year is unknown...+--+-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"+-- Left ...1:13:...expecting month or day...+--+bracketeddatetagsp+ :: Maybe Year -> TextParser m [(TagName, Day)]+bracketeddatetagsp mYear1 = do+ -- dbgparse 0 "bracketeddatetagsp"+ try $ do+ s <- lookAhead+ $ between (char '[') (char ']')+ $ takeWhile1P Nothing isBracketedDateChar+ unless (T.any isDigit s && T.any isDateSepChar s) $+ Fail.fail "not a bracketed date"+ -- Looks sufficiently like a bracketed date to commit to parsing a date++ between (char '[') (char ']') $ do+ md1 <- optional $ datep' mYear1++ let mYear2 = fmap readYear md1 <|> mYear1+ md2 <- optional $ char '=' *> datep' mYear2++ pure $ catMaybes [("date",) <$> md1, ("date2",) <$> md2]++ where+ readYear = first3 . toGregorian+ isBracketedDateChar c = isDigit c || isDateSepChar c || c == '='++{-# INLINABLE bracketeddatetagsp #-}++-- | Get the account name aliases from options, if any.+-- A bad alias argument causes a program exit with a parse error message.+aliasesFromOpts :: InputOpts -> [AccountAlias]+aliasesFromOpts = map parseAliasOpt . aliases_+ where+ parseAliasOpt a =+ case runParser accountaliasp "--alias" (T.pack a) of+ Right alias -> alias+ Left e -> error' $ customErrorBundlePretty e -- PARTIAL:++accountaliasp :: TextParser m AccountAlias+accountaliasp = regexaliasp <|> basicaliasp++basicaliasp :: TextParser m AccountAlias+basicaliasp = do+ -- dbgparse 0 "basicaliasp"+ old <- rstrip <$> (some $ noneOf ("=" :: [Char]))+ char '='+ skipNonNewlineSpaces+ new <- rstrip <$> anySingle `manyTill` eolof -- eol in journal, eof in command lines, normally+ return $ BasicAlias (T.pack old) (T.pack new)++regexaliasp :: TextParser m AccountAlias+regexaliasp = do+ -- dbgparse 0 "regexaliasp"+ (off1, off2, re) <- between (char '/') (char '/') $ do+ off1 <- getOffset+ re <- fmap T.concat . some $+ (T.singleton <$> noneOf ("/\\\n\r" :: [Char])) -- paranoid: don't try to read past line end+ <|> string "\\/" -- allow escaping forward slashes+ <|> (liftM2 T.cons (char '\\') (T.singleton <$> anySingle)) -- Otherwise leave backslashes in+ off2 <- getOffset+ return (off1, off2, re)+ skipNonNewlineSpaces+ char '='+ skipNonNewlineSpaces+ repl <- anySingle `manyTill` eolof+ case toRegexCI re of+ Right r -> return $! RegexAlias r repl+ Left e -> customFailure $! parseErrorAtRegion off1 off2 e++--- ** tests++tests_Common = testGroup "Common" [++ testGroup "amountp" [+ testCase "basic" $ assertParseEq amountp "$47.18" (usd 47.18)+ ,testCase "ends with decimal mark" $ assertParseEq amountp "$1." (usd 1 `withPrecision` Precision 0)+ ,testCase "unit price" $ assertParseEq amountp "$10 @ €0.5"+ -- not precise enough:+ -- (usd 10 `withPrecision` 0 `at` (eur 0.5 `withPrecision` 1)) -- `withStyle` asdecimalmark=Just '.'+ nullamt{+ acommodity="$"+ ,aquantity=10 -- need to test internal precision with roundTo ? I think not+ ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}+ ,acost=Just $ UnitCost $+ nullamt{+ acommodity="€"+ ,aquantity=0.5+ ,astyle=amountstyle{asprecision=Precision 1, asdecimalmark=Just '.'}+ }+ }+ ,testCase "total price" $ assertParseEq amountp "$10 @@ €5"+ nullamt{+ acommodity="$"+ ,aquantity=10+ ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}+ ,acost=Just $ TotalCost $+ nullamt{+ acommodity="€"+ ,aquantity=5+ ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}+ }+ }+ ,testCase "unit price, parenthesised" $ assertParse amountp "$10 (@) €0.5"+ ,testCase "total price, parenthesised" $ assertParse amountp "$10 (@@) €0.5"+ ]++ ,let p = postingamountp OrdinaryAmount+ -- the parts of the result which the expression rules decide+ costParts (UnitCost a) = ("@" :: String, acommodity a, aquantity a)+ costParts (TotalCost a) = ("@@", acommodity a, aquantity a)+ eq input c q prec = assertParseEqOn p input (\a -> (acommodity a, aquantity a, asprecision $ astyle a)) (c, q, Precision prec)+ in testGroup "postingamountp" [+ testCase "a simple amount is unchanged" $ assertParseEq p "$47.18" (usd 47.18)+ ,testCase "the example in #2648" $ eq "$-50.20 + $-209.00 + $-16.54 + $-438" "$" (-713.74) 2+ ,testCase "subtraction, spaces optional" $ eq "10 EUR-2.50 EUR" "EUR" 7.5 2+ ,testCase "a sign after an operator" $ eq "$10 - -$5" "$" 15 0+ ,testCase "* and / before + and -" $ eq "$1 + $2 * 3" "$" 7 0+ ,testCase "parentheses" $ eq "($1 + $2) * 3" "$" 9 0+ ,testCase "nested parentheses" $ eq "((1.0 + 2) * (3 - 1)) / 4" "" 1.5 1+ ,testCase "a sign before parentheses" $ eq "-($1 + $2) - +($3)" "$" (-6) 0+ ,testCase "/ with a right-side symbol" $ eq "10.00 EUR / 4" "EUR" 2.5 2+ ,testCase "a right-side symbol in parentheses" $ eq "(10.00 EUR + 5 EUR) / 4" "EUR" 3.75 2+ ,testCase "* is exact, with the amount's precision" $ eq "$47.97 * 0.05" "$" 2.3985 2+ ,testCase "/ is exact, with the amount's precision" $+ assertParseEqOn p "$100.00 / 3" (\a -> (aquantity a > 33.3333333 && aquantity a < 33.3333334, asprecision $ astyle a)) (True, Precision 2)+ ,testCase "an amount on the right of *" $ eq "3 * $10.005" "$" 30.015 3+ ,testCase "the plain number's decimal places don't count" $ eq "0.5 * $10" "$" 5 0+ ,testCase "two plain numbers use the left one's precision" $ eq "5 / 2" "" 2.5 0+ ,testCase "precision of + is the larger" $ eq "$1 + $0.5" "$" 1.5 1+ ,testCase "a number takes the other side's commodity" $ do+ eq "$10 + 5.5" "$" 15.5 1+ eq "5 - $10" "$" (-5) 0+ eq "(2 + 3) * 10 EUR" "EUR" 50 0+ assertParseEqOn p "5 + 10 EUR" (ascommodityside . astyle) R+ ,testCase "a cost applies to the result" $ assertParseEqOn p "1 X + 2 X @ $3" (\a -> (aquantity a, costParts <$> acost a)) (3, Just ("@", "$", 3))+ ,testCase "different commodities" $ assertParseError p "$1 + 1 EUR" "can't add amounts with different commodities ($ and EUR)"+ ,testCase "two amounts with commodities in *" $ assertParseError p "$2 * $1" "can't multiply two amounts with commodity symbols"+ ,testCase "a number divided by an amount has its commodity and precision" $ do+ eq "9 / $3" "$" 3 0+ eq "3 / 1.50 EUR" "EUR" 2 2+ assertParseEqOn p "1 / 1.25 EUR" (ascommodityside . astyle) R+ ,testCase "two amounts with commodities in /" $ assertParseError p "$9 / $3" "can't divide two amounts with commodity symbols"+ ,testCase "division by zero" $ do+ assertParseError p "$1 / 0" "can't divide by zero"+ assertParseError p "1 / $0" "can't divide by zero"+ ,testCase "no space before / after a commodity symbol" $ do+ assertParseError p "10 EUR/4" "this / is read as part of the commodity symbol EUR/; to divide, write a space before it"+ assertParseError p "10 EUR/ 4" "this / is read as part of the commodity symbol EUR/"+ assertParseError p "10 EUR/-2" "this / is read as part of the commodity symbol EUR/"+ assertParseEqOn p "10 EUR/ + 2 EUR/" acommodity "EUR/"+ ,testCase "an unclosed parenthesis" $ assertParseError p "($1 + $2" "closing parenthesis"+ ,testCase "the default commodity applies only to a result with no commodity" $ do+ let p' = modify' (\j -> j{jparsedefaultcommodity=Just ("$", amountstyle)}) >> p+ on = assertParseEqOn p'+ on "10 EUR * 2" (\a -> (acommodity a, aquantity a)) ("EUR", 20)+ on "10 EUR + 2" (\a -> (acommodity a, aquantity a)) ("EUR", 12)+ on "10 + 2" (\a -> (acommodity a, aquantity a)) ("$", 12)+ ]++ ,let p = lift (numberp Nothing) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) in+ testCase "numberp" $ do+ assertParseEq p "0" (0, 0, Nothing, Nothing)+ assertParseEq p "1" (1, 0, Nothing, Nothing)+ assertParseEq p "1.1" (1.1, 1, Just '.', Nothing)+ assertParseEq p "1,000.1" (1000.1, 1, Just '.', Just $ DigitGroups ',' [3])+ assertParseEq p "1_000.1" (1000.1, 1, Just '.', Just $ DigitGroups '_' [3])+ assertParseEq p "1'000.1" (1000.1, 1, Just '.', Just $ DigitGroups '\'' [3])+ assertParseEq p "1.00.000,1" (100000.1, 1, Just ',', Just $ DigitGroups '.' [3,2])+ assertParseEq p "1,000,000" (1000000, 0, Nothing, Just $ DigitGroups ',' [3,3]) -- could be simplified to [3]+ assertParseEq p "1." (1, 0, Just '.', Nothing)+ assertParseEq p "1," (1, 0, Just ',', Nothing)+ assertParseEq p ".1" (0.1, 1, Just '.', Nothing)+ assertParseEq p ",1" (0.1, 1, Just ',', Nothing)+ assertParseError p "" ""+ assertParseError p "1,000.000,1" ""+ assertParseError p "1.000,000.1" ""+ assertParseError p "1,000.000.1" ""+ assertParseError p "1,,1" ""+ assertParseError p "1..1" ""+ assertParseError p ".1," ""+ assertParseError p ",1." ""+ assertParseEq p "1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" (1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555, 255, Just '.', Nothing)+ assertParseError p "1.5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" ""++ ,testCase "numberp with a suggested decimal mark" $ do+ let p c = lift (numberp $ Just amountstyle{asdecimalmark=Just c}) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)+ assertParseEq (p '.') "1.000" (1, 3, Just '.', Nothing)+ assertParseEq (p ',') "1.000" (1000, 0, Nothing, Just $ DigitGroups '.' [3])+ assertParseEq (p ',') "1.000.000" (1000000, 0, Nothing, Just $ DigitGroups '.' [3,3])+ assertParseEq (p '.') "1,000,000" (1000000, 0, Nothing, Just $ DigitGroups ',' [3,3])+ assertParseEq (p '.') "1 000 000" (1000000, 0, Nothing, Just $ DigitGroups ' ' [3,3])+ -- the suggested decimal mark is used only for disambiguation, not enforced+ assertParseEq (p '.') "1.2.34" (1234, 0, Nothing, Just $ DigitGroups '.' [2,1,1])+ assertParseEq (p ',') "1,000,000.00" (1000000, 2, Just '.', Just $ DigitGroups ',' [3,3])++ ,testCase "amountp with a decimal-mark directive" $ do+ let p kind = modify' (\j -> j{jparsedecimalmark=Just ','}) >> amountp' kind+ assertParse (p OrdinaryAmount) "1.000,5 EUR"+ assertParseError (p OrdinaryAmount) "1,000.5 EUR" "number's decimal mark is '.'"+ assertParseError (p OrdinaryAmount) ".5 EUR" "number's decimal mark is '.'"+ assertParseError (p OrdinaryAmount) "1 X @ 1,000.5 EUR" "number's decimal mark is '.'"+ assertParseError (p OrdinaryAmount) "1,000,000 EUR" "so it can appear only once"+ -- directives declaring a display style may use a different decimal mark+ assertParse (p StyleAmount) "1,000.5 EUR"++ ,testGroup "spaceandamountormissingp" [+ testCase "space and amount" $ assertParseEq spaceandamountormissingp " $47.18" (mixedAmount $ usd 47.18)+ ,testCase "empty string" $ assertParseEq spaceandamountormissingp "" missingmixedamt+ -- ,testCase "just space" $ assertParseEq spaceandamountormissingp " " missingmixedamt -- XXX should it ?+ -- ,testCase "just amount" $ assertParseError spaceandamountormissingp "$47.18" "" -- succeeds, consuming nothing+ ]++ ]++
+ Hledger/Read/CsvReader.hs view
@@ -0,0 +1,89 @@+--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-|++A reader for CSV (character-separated) data.+This also reads a rules file to help interpret the CSV data.++-}++--- ** language+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}++--- ** exports+module Hledger.Read.CsvReader (+ -- * Reader+ reader,+ -- * Tests+ tests_CsvReader,+)+where++--- ** imports+import Prelude hiding (Applicative(..))+import Control.Monad.Except (ExceptT(..), liftEither, withExceptT)+import Control.Monad.IO.Class (MonadIO)+import Data.Encoding (DynEncoding)+import Data.Text (Text)+import System.IO (Handle, IOMode(..), openFile)++import Hledger.Data+import Hledger.Utils+import Hledger.Read.Common (aliasesFromOpts, Reader(..), InputOpts(..), includeFileParser, journalFinalise)+import Hledger.Read.RulesReader (readParsedJournalFromCsv, getRulesFile, rulesEncoding, readRules)+import Control.Monad.Trans (lift)++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++--- ** reader++reader :: MonadIO m => SepFormat -> Reader m+reader sep = Reader+ {rFormat = Sep sep+ ,rExtensions = [show sep]+ ,rReadFn = parse sep+ -- When included by a journal file: the --rules option is ignored, the rules file is always FILE.rules,+ -- and the data is not finalised here; the including journal's finalisation handles that.+ -- (So if finalisation then fails on a CSV-generated entry, the "converted from this record"+ -- context is not shown, but the error still cites the CSV file and line.)+ ,rParser = \iopts -> includeFileParser $ \f ->+ fst <$> readCsvWith sep (_scanfiles iopts) Nothing f (\enc -> openFile f ReadMode >>= hGetContentsPortably enc)+ }++-- | Parse and post-process a "Journal" from a CSV(/SSV/TSV/*SV) data file, or give an error.+-- This reads the data from the provided input file handle, and reads the corresponding+-- rules file (or the one specified by --rules) to help convert it.+-- This does not check balance assertions.+parse :: SepFormat -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal+parse sep iopts f h = do+ (j1, adderrorcontext) <- readCsvWith sep (_scanfiles iopts) (mrules_file_ iopts) f (`hGetContentsPortably` h)+ -- apply any command line account aliases. Can fail with a bad replacement pattern.+ j2 <- liftEither $ journalApplyAliases (aliasesFromOpts iopts) j1+ -- if finalisation fails, show also the CSV record which generated the failing entry+ withExceptT adderrorcontext $+ journalFinalise iopts{balancingopts_=(balancingopts_ iopts){ignore_assertions_=True}} f "" j2++-- | Read the rules file for a CSV data file (the one specified, or the one named after the data file),+-- read the data with the given action (which is told the rules' encoding, if any),+-- and convert it to an unfinalised journal (see 'readParsedJournalFromCsv').+-- If the first argument is true (we are just finding the files read), the data is not read.+readCsvWith :: SepFormat -> Bool -> Maybe FilePath -> FilePath -> (Maybe DynEncoding -> IO Text)+ -> ExceptT String IO (ParsedJournal, String -> String)+readCsvWith sep scanning mrulesfile f readdata = do+ let rulesfile = getRulesFile f mrulesfile+ (rules, rulesfiles) <- readRules rulesfile+ mencoding <- rulesEncoding rulesfile rules+ csvtext <- if scanning then return "" else lift $ readdata mencoding+ readParsedJournalFromCsv rulesfile rules (f, rulesfiles) f csvtext (Just sep)++--- ** tests++tests_CsvReader = testGroup "CsvReader" [+ ]
+ Hledger/Read/InputOptions.hs view
@@ -0,0 +1,159 @@+{-|++Various options to use when reading journal files.+Similar to CliOptions.inputflags, simplifies the journal-reading functions.++-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Read.InputOptions (+-- * Types and helpers for input options+ InputOpts(..)+, HasInputOpts(..)+, definputopts+, fileOverride+, inputOptsSetJournalDir+, forecastPeriod+) where++import Control.Applicative ((<|>))+import Data.Map qualified as M+import Data.Text (Text)+import Data.Time (Day, addDays)+import System.Directory (canonicalizePath)+import System.FilePath (takeDirectory)++import Hledger.Data.Types+import Hledger.Data.Journal (journalEndDate, journalFilePath)+import Hledger.Data.Dates (nulldate, nulldatespan)+import Hledger.Data.Balancing (BalancingOpts(..), HasBalancingOpts(..), defbalancingopts)+import Hledger.Utils (dbg2, makeHledgerClassyLenses)++data InputOpts = InputOpts {+ -- files_ :: [FilePath]+ mformat_ :: Maybe StorageFormat -- ^ a file/storage format to try, unless overridden+ -- by a filename prefix. Nothing means try all.+ ,mrules_file_ :: Maybe FilePath -- ^ a conversion rules file to use (when reading CSV)+ ,aliases_ :: [String] -- ^ account name aliases to apply+ ,anon_ :: Bool -- ^ do light obfuscation of the data ? Now corresponds to --obfuscate, not the old --anon flag.+ ,new_ :: Bool -- ^ read only new transactions since this file was last read ?+ ,new_save_ :: Bool -- ^ save latest new transactions state for next time ?+ ,pivot_ :: String -- ^ use the given field's value as the account name+ ,forecast_ :: Maybe DateSpan -- ^ span in which to generate forecast transactions+ ,verbose_tags_ :: Bool -- ^ add user-visible tags when generating/modifying transactions & postings ?+ ,reportspan_ :: DateSpan -- ^ a dirty hack keeping the query dates in InputOpts. This rightfully lives in ReportSpec, but is duplicated here.+ ,auto_ :: Bool -- ^ generate extra postings according to auto posting rules ?+ ,infer_equity_ :: Bool -- ^ infer equity conversion postings from costs ?+ ,infer_costs_ :: Bool -- ^ infer costs from equity conversion postings ? distinct from BalancingOpts{infer_balancing_costs_}+ ,ignore_lots_ :: Bool -- ^ skip lot tracking and its checks, silencing lot errors ? (basic lot inference still runs, leniently, so lot entries balance)+ ,balancingopts_ :: BalancingOpts -- ^ options for transaction balancing+ ,strict_ :: Bool -- ^ do extra correctness checks ?+ ,_defer :: Bool -- ^ internal flag: postpone checks, because we are processing multiple files ?+ ,_importing :: Bool -- ^ internal flag: is this the @import@ command reading its data files ?+ -- Enables the CSV rules reader's import-specific behaviour: preferring the+ -- oldest file matched by a @source@ glob, and honouring the @archive@ rule.+ -- Set by 'importcmd'; other reads should leave it off.+ ,_dryrun :: Bool -- ^ internal flag: is this a @import --dry-run@ command ?+ -- If set, the CSV rules reader will never archive or remove a data file.+ ,_scanfiles :: Bool -- ^ internal flag: are we just finding the files read (for the files command) ?+ -- If set, files are parsed only to find the files they include or use:+ -- data is not converted or finalised (balanced, checked), source commands are not run,+ -- and an included file which is missing (or a glob matching nothing) is recorded, not an error.+ ,_forecastOnlyForDisplay :: Bool -- ^ internal flag: are forecast transactions being generated only so they can be shown on request+ -- (as hledger-ui always does), not because the user asked for them with --forecast ?+ -- If so, assert rules ignore them, so they pass or fail as they do without --forecast.+ ,_ioDay :: Day -- ^ today's date, for use with forecast transactions XXX this duplicates _rsDay, and should eventually be removed when it's not needed anymore.+ ,_oldtimeclock :: Bool -- ^ parse with the old timeclock pairing rules?+ ,_journaldir :: Maybe FilePath -- ^ The main journal file's directory. Used eg by the CSV rules reader to locate the+ -- journal's @data/@ directory. Set by the CLI entry points 'withJournal',+ -- 'withPossibleJournal', and 'journalReload'.+ -- If you do a further 'readJournalFile' / 'readJournalFiles' call after a+ -- journal has been loaded (eg as @import@ does), apply 'inputOptsSetJournalDir'+ -- to its 'InputOpts' so the CSV rules reader can find the right @data/@.+ -- Otherwise, the CSV rules reader falls back to the rules file's own directory.+ ,_fileoverrides :: M.Map FilePath Text -- ^ internal: replacement content for some files, keyed by canonical path+ -- (see 'canonicalizePath'), with \n line endings. When the reader would read+ -- one of these files (as a journal file or an included file), it reads this text+ -- instead, and the file need not exist. Used to check a change to a file before+ -- writing it (see @journalCheckChange@ in hledger's Hledger.Cli.Utils).+ } deriving (Eq, Ord, Show)++definputopts :: InputOpts+definputopts = InputOpts+ { mformat_ = Nothing+ , mrules_file_ = Nothing+ , aliases_ = []+ , anon_ = False+ , new_ = False+ , new_save_ = True+ , pivot_ = ""+ , forecast_ = Nothing+ , verbose_tags_ = False+ , reportspan_ = nulldatespan+ , auto_ = False+ , infer_equity_ = False+ , infer_costs_ = False+ , ignore_lots_ = False+ , balancingopts_ = defbalancingopts+ , strict_ = False+ , _defer = False+ , _importing = False+ , _dryrun = False+ , _scanfiles = False+ , _forecastOnlyForDisplay = False+ , _ioDay = nulldate+ , _oldtimeclock = False+ , _journaldir = Nothing+ , _fileoverrides = M.empty+ }++-- | The replacement content for this file in the input options' '_fileoverrides', if any.+-- Standard input ("-") is never overridden. Paths are compared canonically,+-- which is skipped when there are no overrides (the usual case).+fileOverride :: InputOpts -> FilePath -> IO (Maybe Text)+fileOverride InputOpts{_fileoverrides=os} f+ | M.null os || f == "-" = return Nothing+ | otherwise = (`M.lookup` os) <$> canonicalizePath f++-- | Set 'InputOpts._journaldir' from a parsed 'Journal' (using @takeDirectory . journalFilePath@).+--+-- Use this when you want to do a further @readJournalFile@ / @readJournalFiles@ call+-- after a journal has been loaded — eg the @hledger import@ command reads the user's rules+-- files in a second pass — so the CSV rules reader can find the journal's @data/@ directory+-- for @source@ lookups and @archive@ saves. Otherwise it will fall back to using the rules+-- file's own directory, which is no longer the preferred place.+--+-- Usage:+--+-- @+-- iopts' = inputOptsSetJournalDir j $ iopts { ...other tweaks... }+-- @+inputOptsSetJournalDir :: Journal -> InputOpts -> InputOpts+inputOptsSetJournalDir j iopts = iopts{_journaldir = Just (takeDirectory (journalFilePath j))}++-- | Get the Maybe the DateSpan to generate forecast options from.+-- This begins on:+-- - the start date supplied to the `--forecast` argument, if present+-- - 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 present+-- - otherwise the report end date if specified with -e/-p/date:+-- - otherwise 180 days (6 months) from today.+forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan+forecastPeriod iopts j = do+ DateSpan requestedStart requestedEnd <- forecast_ iopts+ let forecastStart = fromEFDay <$> requestedStart <|> max mjournalend (fromEFDay <$> reportStart) <|> Just (_ioDay iopts)+ forecastEnd = fromEFDay <$> requestedEnd <|> fromEFDay <$> reportEnd <|> (Just $ addDays 180 $ _ioDay iopts)+ mjournalend = dbg2 "journalEndDate" $ journalEndDate False j -- ignore secondary dates+ DateSpan reportStart reportEnd = reportspan_ iopts+ return . dbg2 "forecastspan" $ DateSpan (Exact <$> forecastStart) (Exact <$> forecastEnd)++-- ** Lenses++makeHledgerClassyLenses ''InputOpts++instance HasBalancingOpts InputOpts where+ balancingOpts = balancingopts
Hledger/Read/JournalReader.hs view
@@ -1,851 +1,2330 @@-{-|--A reader for hledger's (and c++ ledger's) journal file format.--From the ledger 2.5 manual:--@-The ledger file format is quite simple, but also very flexible. It supports-many options, though typically the user can ignore most of them. They are-summarized below. The initial character of each line determines what the-line means, and how it should be interpreted. Allowable initial characters-are:--NUMBER A line beginning with a number denotes an entry. It may be followed by any- number of lines, each beginning with whitespace, to denote the entry’s account- transactions. The format of the first line is:-- DATE[=EDATE] [*|!] [(CODE)] DESC-- If ‘*’ appears after the date (with optional effective date), it indicates the entry- is “cleared”, which can mean whatever the user wants it t omean. If ‘!’ appears- after the date, it indicates d the entry is “pending”; i.e., tentatively cleared from- the user’s point of view, but not yet actually cleared. If a ‘CODE’ appears in- parentheses, it may be used to indicate a check number, or the type of the- transaction. Following these is the payee, or a description of the transaction.- The format of each following transaction is:-- ACCOUNT AMOUNT [; NOTE]-- The ‘ACCOUNT’ may be surrounded by parentheses if it is a virtual- transactions, or square brackets if it is a virtual transactions that must- balance. The ‘AMOUNT’ can be followed by a per-unit transaction cost,- by specifying ‘ AMOUNT’, or a complete transaction cost with ‘\@ AMOUNT’.- Lastly, the ‘NOTE’ may specify an actual and/or effective date for the- transaction by using the syntax ‘[ACTUAL_DATE]’ or ‘[=EFFECTIVE_DATE]’ or- ‘[ACTUAL_DATE=EFFECtIVE_DATE]’.--= An automated entry. A value expression must appear after the equal sign.- After this initial line there should be a set of one or more transactions, just as- if it were normal entry. If the amounts of the transactions have no commodity,- they will be applied as modifiers to whichever real transaction is matched by- the value expression.- -~ A period entry. A period expression must appear after the tilde.- After this initial line there should be a set of one or more transactions, just as- if it were normal entry.--! A line beginning with an exclamation mark denotes a command directive. It- must be immediately followed by the command word. The supported commands- are:-- ‘!include’- Include the stated ledger file.- ‘!account’- The account name is given is taken to be the parent of all transac-- tions that follow, until ‘!end’ is seen.- ‘!end’ Ends an account block.- -; A line beginning with a colon indicates a comment, and is ignored.- -Y If a line begins with a capital Y, it denotes the year used for all subsequent- entries that give a date without a year. The year should appear immediately- after the Y, for example: ‘Y2004’. This is useful at the beginning of a file, to- specify the year for that file. If all entries specify a year, however, this command- has no effect.- - -P Specifies a historical price for a commodity. These are usually found in a pricing- history file (see the ‘-Q’ option). The syntax is:-- P DATE SYMBOL PRICE--N SYMBOL Indicates that pricing information is to be ignored for a given symbol, nor will- quotes ever be downloaded for that symbol. Useful with a home currency, such- as the dollar ($). It is recommended that these pricing options be set in the price- database file, which defaults to ‘~/.pricedb’. The syntax for this command is:-- N SYMBOL-- -D AMOUNT Specifies the default commodity to use, by specifying an amount in the expected- format. The entry command will use this commodity as the default when none- other can be determined. This command may be used multiple times, to set- the default flags for different commodities; whichever is seen last is used as the- default commodity. For example, to set US dollars as the default commodity,- while also setting the thousands flag and decimal flag for that commodity, use:-- D $1,000.00--C AMOUNT1 = AMOUNT2- Specifies a commodity conversion, where the first amount is given to be equiv-- alent to the second amount. The first amount should use the decimal precision- desired during reporting:-- C 1.00 Kb = 1024 bytes--i, o, b, h- These four relate to timeclock support, which permits ledger to read timelog- files. See the timeclock’s documentation for more info on the syntax of its- timelog files.-@---}--module Hledger.Read.JournalReader (- emptyLine,- journalAddFile,- journalFile,- ledgeraccountname,- ledgerdatetime,- ledgerDefaultYear,- ledgerDirective,- ledgerHistoricalPrice,- reader,- someamount,- tests_Hledger_Read_JournalReader-)-where-import Control.Monad-import Control.Monad.Error-import Data.Char (isNumber)-import Data.List-import Data.List.Split (wordsBy)-import Data.Maybe-import Data.Time.Calendar--- import Data.Time.Clock--- import Data.Time.Format-import Data.Time.LocalTime-import Safe (headDef)--- import System.Locale (defaultTimeLocale)-import Test.HUnit-import Text.ParserCombinators.Parsec hiding (parse)-import Text.Printf--import Hledger.Data-import Hledger.Read.Utils-import Hledger.Utils-import Prelude hiding (readFile)-import Hledger.Utils.UTF8 (readFile)----- let's get to it--reader :: Reader-reader = Reader format detect parse--format :: String-format = "journal"---- | Does the given file path and data provide hledger's journal file format ?-detect :: FilePath -> String -> Bool-detect f _ = fileSuffix f == format---- | Parse and post-process a "Journal" from hledger's journal file--- format, or give an error.-parse :: FilePath -> String -> ErrorT String IO Journal-parse = parseJournalWith journalFile---- | Top-level journal parser. Returns a single composite, I/O performing,--- error-raising "JournalUpdate" (and final "JournalContext") which can be--- applied to an empty journal to get the final result.-journalFile :: GenParser Char JournalContext (JournalUpdate,JournalContext)-journalFile = do- journalupdates <- many journalItem- eof- finalctx <- getState- return $ (juSequence journalupdates, finalctx)- where - -- As all journal line types can be distinguished by the first- -- character, excepting transactions versus empty (blank or- -- comment-only) lines, can use choice w/o try- journalItem = choice [ ledgerDirective- , liftM (return . addTransaction) ledgerTransaction- , liftM (return . addModifierTransaction) ledgerModifierTransaction- , liftM (return . addPeriodicTransaction) ledgerPeriodicTransaction- , liftM (return . addHistoricalPrice) ledgerHistoricalPrice- , emptyLine >> return (return id)- ] <?> "journal transaction or directive"--emptyLine :: GenParser Char JournalContext ()-emptyLine = do many spacenonewline- optional $ (char ';' <?> "comment") >> many (noneOf "\n")- newline- return ()--ledgercomment :: GenParser Char JournalContext String-ledgercomment = do- many1 $ char ';'- many spacenonewline- many (noneOf "\n")- <?> "comment"--ledgercommentline :: GenParser Char JournalContext String-ledgercommentline = do- many spacenonewline- s <- ledgercomment- optional newline- eof- return s- <?> "comment"--ledgerDirective :: GenParser Char JournalContext JournalUpdate-ledgerDirective = do- optional $ char '!'- choice' [- ledgerInclude- ,ledgerAlias- ,ledgerEndAliases- ,ledgerAccountBegin- ,ledgerAccountEnd- ,ledgerTagDirective- ,ledgerEndTagDirective- ,ledgerDefaultYear- ,ledgerDefaultCommodity- ,ledgerCommodityConversion- ,ledgerIgnoredPriceCommodity- ]- <?> "directive"--ledgerInclude :: GenParser Char JournalContext JournalUpdate-ledgerInclude = do- string "include"- many1 spacenonewline- filename <- restofline- outerState <- getState- outerPos <- getPosition- return $ do filepath <- expandPath outerPos filename- txt <- readFileOrError outerPos filepath- let inIncluded = show outerPos ++ " in included file " ++ show filename ++ ":\n"- case runParser journalFile outerState filepath txt of- Right (ju,_) -> juSequence [return $ journalAddFile (filepath,txt), ju] `catchError` (throwError . (inIncluded ++))- Left err -> throwError $ inIncluded ++ show err- where readFileOrError pos fp =- ErrorT $ liftM Right (readFile fp) `catch`- \err -> return $ Left $ printf "%s reading %s:\n%s" (show pos) fp (show err)--journalAddFile :: (FilePath,String) -> Journal -> Journal-journalAddFile f j@Journal{files=fs} = j{files=fs++[f]}--ledgerAccountBegin :: GenParser Char JournalContext JournalUpdate-ledgerAccountBegin = do- string "account"- many1 spacenonewline- parent <- ledgeraccountname- newline- pushParentAccount parent- return $ return id--ledgerAccountEnd :: GenParser Char JournalContext JournalUpdate-ledgerAccountEnd = do- string "end"- popParentAccount- return (return id)--ledgerAlias :: GenParser Char JournalContext JournalUpdate-ledgerAlias = do- string "alias"- many1 spacenonewline- orig <- many1 $ noneOf "="- char '='- alias <- restofline- addAccountAlias (accountNameWithoutPostingType $ strip orig- ,accountNameWithoutPostingType $ strip alias)- return $ return id--ledgerEndAliases :: GenParser Char JournalContext JournalUpdate-ledgerEndAliases = do- string "end aliases"- clearAccountAliases- return (return id)--ledgerTagDirective :: GenParser Char JournalContext JournalUpdate-ledgerTagDirective = do- string "tag" <?> "tag directive"- many1 spacenonewline- _ <- many1 nonspace- restofline- return $ return id--ledgerEndTagDirective :: GenParser Char JournalContext JournalUpdate-ledgerEndTagDirective = do- (string "end tag" <|> string "pop") <?> "end tag or pop directive"- restofline- return $ return id--ledgerDefaultYear :: GenParser Char JournalContext JournalUpdate-ledgerDefaultYear = do- char 'Y' <?> "default year"- many spacenonewline- y <- many1 digit- let y' = read y- failIfInvalidYear y- setYear y'- return $ return id--ledgerDefaultCommodity :: GenParser Char JournalContext JournalUpdate-ledgerDefaultCommodity = do- char 'D' <?> "default commodity"- many1 spacenonewline- a <- someamount- -- someamount always returns a MixedAmount containing one Amount, but let's be safe- let as = amounts a- when (not $ null as) $ setCommodity $ commodity $ head as- restofline- return $ return id--ledgerHistoricalPrice :: GenParser Char JournalContext HistoricalPrice-ledgerHistoricalPrice = do- char 'P' <?> "historical price"- many spacenonewline- date <- try (do {LocalTime d _ <- ledgerdatetime; return d}) <|> ledgerdate -- a time is ignored- many1 spacenonewline- symbol <- commoditysymbol- many spacenonewline- price <- someamount- restofline- return $ HistoricalPrice date symbol price--ledgerIgnoredPriceCommodity :: GenParser Char JournalContext JournalUpdate-ledgerIgnoredPriceCommodity = do- char 'N' <?> "ignored-price commodity"- many1 spacenonewline- commoditysymbol- restofline- return $ return id--ledgerCommodityConversion :: GenParser Char JournalContext JournalUpdate-ledgerCommodityConversion = do- char 'C' <?> "commodity conversion"- many1 spacenonewline- someamount- many spacenonewline- char '='- many spacenonewline- someamount- restofline- return $ return id--ledgerModifierTransaction :: GenParser Char JournalContext ModifierTransaction-ledgerModifierTransaction = do- char '=' <?> "modifier transaction"- many spacenonewline- valueexpr <- restofline- postings <- ledgerpostings- return $ ModifierTransaction valueexpr postings--ledgerPeriodicTransaction :: GenParser Char JournalContext PeriodicTransaction-ledgerPeriodicTransaction = do- char '~' <?> "periodic transaction"- many spacenonewline- periodexpr <- restofline- postings <- ledgerpostings- return $ PeriodicTransaction periodexpr postings---- | Parse a (possibly unbalanced) ledger transaction.-ledgerTransaction :: GenParser Char JournalContext Transaction-ledgerTransaction = do- date <- ledgerdate <?> "transaction"- edate <- optionMaybe (ledgereffectivedate date) <?> "effective date"- status <- ledgerstatus <?> "cleared flag"- code <- ledgercode <?> "transaction code"- (description, comment) <-- (do {many1 spacenonewline; d <- liftM rstrip (many (noneOf ";\n")); c <- ledgercomment <|> return ""; newline; return (d, c)} <|>- do {many spacenonewline; c <- ledgercomment <|> return ""; newline; return ("", c)}- ) <?> "description and/or comment"- md <- try ledgermetadata <|> return []- postings <- ledgerpostings- return $ txnTieKnot $ Transaction date edate status code description comment md postings ""---- | Parse a date in YYYY/MM/DD format. Fewer digits are allowed. The year--- may be omitted if a default year has already been set.-ledgerdate :: GenParser Char JournalContext Day-ledgerdate = do- -- hacky: try to ensure precise errors for invalid dates- -- XXX reported error position is not too good- -- pos <- getPosition- datestr <- many1 $ choice' [digit, datesepchar]- let dateparts = wordsBy (`elem` datesepchars) datestr- currentyear <- getYear- [y,m,d] <- case (dateparts,currentyear) of- ([m,d],Just y) -> return [show y,m,d]- ([_,_],Nothing) -> fail $ "partial date "++datestr++" found, but the current year is unknown"- ([y,m,d],_) -> return [y,m,d]- _ -> fail $ "bad date: " ++ datestr- let maybedate = fromGregorianValid (read y) (read m) (read d)- case maybedate of- Nothing -> fail $ "bad date: " ++ datestr- Just date -> return date- <?> "full or partial date"---- | Parse a date and time in YYYY/MM/DD HH:MM[:SS][+-ZZZZ] format. Any--- timezone will be ignored; the time is treated as local time. Fewer--- digits are allowed, except in the timezone. The year may be omitted if--- a default year has already been set.-ledgerdatetime :: GenParser Char JournalContext LocalTime-ledgerdatetime = do - day <- ledgerdate- many1 spacenonewline- h <- many1 digit- let h' = read h- guard $ h' >= 0 && h' <= 23- char ':'- m <- many1 digit- let m' = read m- guard $ m' >= 0 && m' <= 59- s <- optionMaybe $ char ':' >> many1 digit- let s' = case s of Just sstr -> read sstr- Nothing -> 0- guard $ s' >= 0 && s' <= 59- {- tz <- -}- optionMaybe $ do- plusminus <- oneOf "-+"- d1 <- digit- d2 <- digit- d3 <- digit- d4 <- digit- return $ plusminus:d1:d2:d3:d4:""- -- ltz <- liftIO $ getCurrentTimeZone- -- let tz' = maybe ltz (fromMaybe ltz . parseTime defaultTimeLocale "%z") tz- -- return $ localTimeToUTC tz' $ LocalTime day $ TimeOfDay h' m' (fromIntegral s')- return $ LocalTime day $ TimeOfDay h' m' (fromIntegral s')--ledgereffectivedate :: Day -> GenParser Char JournalContext Day-ledgereffectivedate actualdate = do- char '='- -- kludgy way to use actual date for default year- let withDefaultYear d p = do- y <- getYear- let (y',_,_) = toGregorian d in setYear y'- r <- p- when (isJust y) $ setYear $ fromJust y- return r- edate <- withDefaultYear actualdate ledgerdate- return edate--ledgerstatus :: GenParser Char JournalContext Bool-ledgerstatus = try (do { many spacenonewline; char '*' <?> "status"; return True } ) <|> return False--ledgercode :: GenParser Char JournalContext String-ledgercode = try (do { many1 spacenonewline; char '(' <?> "code"; code <- anyChar `manyTill` char ')'; return code } ) <|> return ""--ledgermetadata :: GenParser Char JournalContext [(String,String)]-ledgermetadata = many ledgermetadataline---- a comment line containing a metadata declaration, eg:--- ; name: value-ledgermetadataline :: GenParser Char JournalContext (String,String)-ledgermetadataline = do- many1 spacenonewline- many1 $ char ';'- many spacenonewline- name <- many1 $ noneOf ": \t"- char ':'- many spacenonewline- value <- many (noneOf "\n")- optional newline--- eof- return (name,value)- <?> "metadata line"---- Parse the following whitespace-beginning lines as postings, posting metadata, and/or comments.--- complicated to handle intermixed comment and metadata lines.. make me better ?-ledgerpostings :: GenParser Char JournalContext [Posting]-ledgerpostings = do- ctx <- getState- -- we'll set the correct position for sub-parses for more useful errors- pos <- getPosition- ls <- many1 $ try linebeginningwithspaces- let lsnumbered = zip ls [0..]- parses p = isRight . parseWithCtx ctx p- postinglines = filter (not . (ledgercommentline `parses`) . fst) lsnumbered- -- group any metadata lines with the posting line above- postinglinegroups :: [(String,Line)] -> [(String,Line)]- postinglinegroups [] = []- postinglinegroups ((pline,num):ls) = (unlines (pline:(map fst mdlines)), num):postinglinegroups rest- where (mdlines,rest) = span ((ledgermetadataline `parses`) . fst) ls- pstrs = postinglinegroups postinglines- parseNumberedPostingLine (str,num) = fromparse $ parseWithCtx ctx (setPosition (incSourceLine pos num) >> ledgerposting) str- when (null pstrs) $ fail "no postings"- return $ map parseNumberedPostingLine pstrs- <?> "postings"- -linebeginningwithspaces :: GenParser Char JournalContext String-linebeginningwithspaces = do- sp <- many1 spacenonewline- c <- nonspace- cs <- restofline- return $ sp ++ (c:cs) ++ "\n"--ledgerposting :: GenParser Char JournalContext Posting-ledgerposting = do- many1 spacenonewline- status <- ledgerstatus- many spacenonewline- account <- modifiedaccountname- let (ptype, account') = (accountNamePostingType account, unbracket account)- amount <- postingamount- many spacenonewline- comment <- ledgercomment <|> return ""- newline- md <- ledgermetadata- return (Posting status account' amount comment ptype md Nothing)---- Parse an account name, then apply any parent account prefix and/or account aliases currently in effect.-modifiedaccountname :: GenParser Char JournalContext AccountName-modifiedaccountname = do- a <- ledgeraccountname- prefix <- getParentAccount- let prefixed = prefix `joinAccountNames` a- aliases <- getAccountAliases- return $ accountNameApplyAliases aliases prefixed---- | Parse an account name. Account names may have single spaces inside--- them, and are terminated by two or more spaces. They should have one or--- more components of at least one character, separated by the account--- separator char.-ledgeraccountname :: GenParser Char st AccountName-ledgeraccountname = do- a <- many1 (nonspace <|> singlespace)- let a' = striptrailingspace a- when (accountNameFromComponents (accountNameComponents a') /= a')- (fail $ "accountname seems ill-formed: "++a')- return a'- where - singlespace = try (do {spacenonewline; do {notFollowedBy spacenonewline; return ' '}})- -- couldn't avoid consuming a final space sometimes, harmless- striptrailingspace s = if last s == ' ' then init s else s---- accountnamechar = notFollowedBy (oneOf "()[]") >> nonspace--- <?> "account name character (non-bracket, non-parenthesis, non-whitespace)"---- | Parse an amount, with an optional left or right currency symbol and--- optional price.-postingamount :: GenParser Char JournalContext MixedAmount-postingamount =- try (do- many1 spacenonewline- someamount <|> return missingamt- ) <|> return missingamt--someamount :: GenParser Char JournalContext MixedAmount-someamount = try leftsymbolamount <|> try rightsymbolamount <|> nosymbolamount --leftsymbolamount :: GenParser Char JournalContext MixedAmount-leftsymbolamount = do- sign <- optionMaybe $ string "-"- let applysign = if isJust sign then negate else id- sym <- commoditysymbol - sp <- many spacenonewline- (q,p,d,s,spos) <- number- pri <- priceamount- let c = Commodity {symbol=sym,side=L,spaced=not $ null sp,decimalpoint=d,precision=p,separator=s,separatorpositions=spos}- return $ applysign $ Mixed [Amount c q pri]- <?> "left-symbol amount"--rightsymbolamount :: GenParser Char JournalContext MixedAmount-rightsymbolamount = do- (q,p,d,s,spos) <- number- sp <- many spacenonewline- sym <- commoditysymbol- pri <- priceamount- let c = Commodity {symbol=sym,side=R,spaced=not $ null sp,decimalpoint=d,precision=p,separator=s,separatorpositions=spos}- return $ Mixed [Amount c q pri]- <?> "right-symbol amount"--nosymbolamount :: GenParser Char JournalContext MixedAmount-nosymbolamount = do- (q,p,d,s,spos) <- number- pri <- priceamount- defc <- getCommodity- let c = fromMaybe Commodity{symbol="",side=L,spaced=False,decimalpoint=d,precision=p,separator=s,separatorpositions=spos} defc- return $ Mixed [Amount c q pri]- <?> "no-symbol amount"--commoditysymbol :: GenParser Char JournalContext String-commoditysymbol = (quotedcommoditysymbol <|> simplecommoditysymbol) <?> "commodity symbol"--quotedcommoditysymbol :: GenParser Char JournalContext String-quotedcommoditysymbol = do- char '"'- s <- many1 $ noneOf ";\n\""- char '"'- return s--simplecommoditysymbol :: GenParser Char JournalContext String-simplecommoditysymbol = many1 (noneOf nonsimplecommoditychars)--priceamount :: GenParser Char JournalContext (Maybe Price)-priceamount =- try (do- many spacenonewline- char '@'- try (do- char '@'- many spacenonewline- a <- someamount -- XXX can parse more prices ad infinitum, shouldn't- return $ Just $ TotalPrice a)- <|> (do- many spacenonewline- a <- someamount -- XXX can parse more prices ad infinitum, shouldn't- return $ Just $ UnitPrice a))- <|> return Nothing---- gawd.. trying to parse a ledger number without error:--type Quantity = Double---- -- | Parse a ledger-style numeric quantity and also return the number of--- -- digits to the right of the decimal point and whether thousands are--- -- separated by comma.--- amountquantity :: GenParser Char JournalContext (Quantity, Int, Bool)--- amountquantity = do--- sign <- optionMaybe $ string "-"--- (intwithcommas,frac) <- numberparts--- let comma = ',' `elem` intwithcommas--- let precision = length frac--- -- read the actual value. We expect this read to never fail.--- let int = filter (/= ',') intwithcommas--- let int' = if null int then "0" else int--- let frac' = if null frac then "0" else frac--- let sign' = fromMaybe "" sign--- let quantity = read $ sign'++int'++"."++frac'--- return (quantity, precision, comma)--- <?> "commodity quantity"---- -- | parse the two strings of digits before and after a possible decimal--- -- point. The integer part may contain commas, or either part may be--- -- empty, or there may be no point.--- numberparts :: GenParser Char JournalContext (String,String)--- numberparts = numberpartsstartingwithdigit <|> numberpartsstartingwithpoint---- numberpartsstartingwithdigit :: GenParser Char JournalContext (String,String)--- numberpartsstartingwithdigit = do--- let digitorcomma = digit <|> char ','--- first <- digit--- rest <- many digitorcomma--- frac <- try (do {char '.'; many digit}) <|> return ""--- return (first:rest,frac)- --- numberpartsstartingwithpoint :: GenParser Char JournalContext (String,String)--- numberpartsstartingwithpoint = do--- char '.'--- frac <- many1 digit--- return ("",frac)---- | Parse a numeric quantity for its value and display attributes. Some--- international number formats (cf--- http://en.wikipedia.org/wiki/Decimal_separator) are accepted: either--- period or comma may be used for the decimal point, and the other of--- these may be used for separating digit groups in the integer part (eg a--- thousands separator). This returns the numeric value, the precision--- (number of digits to the right of the decimal point), the decimal point--- and separator characters (defaulting to . and ,), and the positions of--- separators (counting leftward from the decimal point, the last is--- assumed to repeat).-number :: GenParser Char JournalContext (Quantity, Int, Char, Char, [Int])-number = do- sign <- optionMaybe $ string "-"- parts <- many1 $ choice' [many1 digit, many1 $ char ',', many1 $ char '.']- let numeric = isNumber . headDef '_'- (_, puncparts) = partition numeric parts- (ok,decimalpoint',separator') =- case puncparts of- [] -> (True, Nothing, Nothing) -- no punctuation chars- [d:""] -> (True, Just d, Nothing) -- just one punctuation char, assume it's a decimal point- [_] -> (False, Nothing, Nothing) -- adjacent punctuation chars, not ok- _:_:_ -> let (s:ss, d) = (init puncparts, last puncparts) -- two or more punctuation chars- in if (any ((/=1).length) puncparts -- adjacent punctuation chars, not ok- || any (s/=) ss -- separator chars differ, not ok- || head parts == s) -- number begins with a separator char, not ok- then (False, Nothing, Nothing)- else if s == d- then (True, Nothing, Just $ head s) -- just one kind of punctuation, assume separator chars- else (True, Just $ head d, Just $ head s) -- separators and a decimal point- when (not ok) (fail $ "number seems ill-formed: "++concat parts)- let (intparts',fracparts') = span ((/= decimalpoint') . Just . head) parts- (intparts, fracpart) = (filter numeric intparts', filter numeric fracparts')- separatorpositions = reverse $ map length $ drop 1 intparts- int = concat $ "":intparts- frac = concat $ "":fracpart- precision = length frac- int' = if null int then "0" else int- frac' = if null frac then "0" else frac- sign' = fromMaybe "" sign- quantity = read $ sign'++int'++"."++frac' -- this read should never fail- (decimalpoint, separator) = case (decimalpoint', separator') of (Just d, Just s) -> (d,s)- (Just '.',Nothing) -> ('.',',')- (Just ',',Nothing) -> (',','.')- (Nothing, Just '.') -> (',','.')- (Nothing, Just ',') -> ('.',',')- _ -> ('.',',')- return (quantity,precision,decimalpoint,separator,separatorpositions)- <?> "number"--tests_Hledger_Read_JournalReader = TestList [-- "number" ~: do- let s `is` n = assertParseEqual (parseWithCtx nullctx number s) n- assertFails = assertBool "" . isLeft . parseWithCtx nullctx number - assertFails ""- "0" `is` (0, 0, '.', ',', [])- "1" `is` (1, 0, '.', ',', [])- "1.1" `is` (1.1, 1, '.', ',', [])- "1,000.1" `is` (1000.1, 1, '.', ',', [3])- "1.00.000,1" `is` (100000.1, 1, ',', '.', [3,2])- "1,000,000" `is` (1000000, 0, '.', ',', [3,3])- "1." `is` (1, 0, '.', ',', [])- "1," `is` (1, 0, ',', '.', [])- ".1" `is` (0.1, 1, '.', ',', [])- ",1" `is` (0.1, 1, ',', '.', [])- assertFails "1,000.000,1"- assertFails "1.000,000.1"- assertFails "1,000.000.1"- assertFails "1,,1"- assertFails "1..1"- assertFails ".1,"- assertFails ",1."-- ,"ledgerTransaction" ~: do- assertParseEqual (parseWithCtx nullctx ledgerTransaction entry1_str) entry1- assertBool "ledgerTransaction should not parse just a date"- $ isLeft $ parseWithCtx nullctx ledgerTransaction "2009/1/1\n"- assertBool "ledgerTransaction should require some postings"- $ isLeft $ parseWithCtx nullctx ledgerTransaction "2009/1/1 a\n"- let t = parseWithCtx nullctx ledgerTransaction "2009/1/1 a ;comment\n b 1\n"- assertBool "ledgerTransaction should not include a comment in the description"- $ either (const False) ((== "a") . tdescription) t-- ,"ledgerModifierTransaction" ~: do- assertParse (parseWithCtx nullctx ledgerModifierTransaction "= (some value expr)\n some:postings 1\n")-- ,"ledgerPeriodicTransaction" ~: do- assertParse (parseWithCtx nullctx ledgerPeriodicTransaction "~ (some period expr)\n some:postings 1\n")-- ,"ledgerDirective" ~: do- assertParse (parseWithCtx nullctx ledgerDirective "!include /some/file.x\n")- assertParse (parseWithCtx nullctx ledgerDirective "account some:account\n")- assertParse (parseWithCtx nullctx (ledgerDirective >> ledgerDirective) "!account a\nend\n")-- ,"ledgercommentline" ~: do- assertParse (parseWithCtx nullctx ledgercommentline "; some comment \n")- assertParse (parseWithCtx nullctx ledgercommentline " \t; x\n")- assertParse (parseWithCtx nullctx ledgercommentline ";x")-- ,"ledgerdate" ~: do- assertParse (parseWithCtx nullctx ledgerdate "2011/1/1")- assertParseFailure (parseWithCtx nullctx ledgerdate "1/1")- assertParse (parseWithCtx nullctx{ctxYear=Just 2011} ledgerdate "1/1")-- ,"ledgerdatetime" ~: do- let p = do {t <- ledgerdatetime; eof; return t}- bad = assertParseFailure . parseWithCtx nullctx p- good = assertParse . parseWithCtx nullctx p- bad "2011/1/1"- bad "2011/1/1 24:00:00"- bad "2011/1/1 00:60:00"- bad "2011/1/1 00:00:60"- good "2011/1/1 00:00"- good "2011/1/1 23:59:59"- good "2011/1/1 3:5:7"- -- timezone is parsed but ignored- let startofday = LocalTime (fromGregorian 2011 1 1) (TimeOfDay 0 0 (fromIntegral 0))- assertParseEqual (parseWithCtx nullctx p "2011/1/1 00:00-0800") startofday- assertParseEqual (parseWithCtx nullctx p "2011/1/1 00:00+1234") startofday-- ,"ledgerDefaultYear" ~: do- assertParse (parseWithCtx nullctx ledgerDefaultYear "Y 2010\n")- assertParse (parseWithCtx nullctx ledgerDefaultYear "Y 10001\n")-- ,"ledgerHistoricalPrice" ~:- assertParseEqual (parseWithCtx nullctx ledgerHistoricalPrice "P 2004/05/01 XYZ $55.00\n") (HistoricalPrice (parsedate "2004/05/01") "XYZ" $ Mixed [dollars 55])-- ,"ledgerIgnoredPriceCommodity" ~: do- assertParse (parseWithCtx nullctx ledgerIgnoredPriceCommodity "N $\n")-- ,"ledgerDefaultCommodity" ~: do- assertParse (parseWithCtx nullctx ledgerDefaultCommodity "D $1,000.0\n")-- ,"ledgerCommodityConversion" ~: do- assertParse (parseWithCtx nullctx ledgerCommodityConversion "C 1h = $50.00\n")-- ,"ledgerTagDirective" ~: do- assertParse (parseWithCtx nullctx ledgerTagDirective "tag foo \n")-- ,"ledgerEndTagDirective" ~: do- assertParse (parseWithCtx nullctx ledgerEndTagDirective "end tag \n")- ,"ledgerEndTagDirective" ~: do- assertParse (parseWithCtx nullctx ledgerEndTagDirective "pop \n")-- ,"ledgeraccountname" ~: do- assertBool "ledgeraccountname parses a normal accountname" (isRight $ parsewith ledgeraccountname "a:b:c")- assertBool "ledgeraccountname rejects an empty inner component" (isLeft $ parsewith ledgeraccountname "a::c")- assertBool "ledgeraccountname rejects an empty leading component" (isLeft $ parsewith ledgeraccountname ":b:c")- assertBool "ledgeraccountname rejects an empty trailing component" (isLeft $ parsewith ledgeraccountname "a:b:")-- ,"ledgerposting" ~: do- assertParseEqual (parseWithCtx nullctx ledgerposting " expenses:food:dining $10.00\n")- (Posting False "expenses:food:dining" (Mixed [dollars 10]) "" RegularPosting [] Nothing)- assertBool "ledgerposting parses a quoted commodity with numbers"- (isRight $ parseWithCtx nullctx ledgerposting " a 1 \"DE123\"\n")-- ,"someamount" ~: do- let -- | compare a parse result with a MixedAmount, showing the debug representation for clarity- assertMixedAmountParse parseresult mixedamount =- (either (const "parse error") showMixedAmountDebug parseresult) ~?= (showMixedAmountDebug mixedamount)- assertMixedAmountParse (parseWithCtx nullctx someamount "1 @ $2")- (Mixed [Amount unknown 1 (Just $ UnitPrice $ Mixed [Amount dollar{precision=0} 2 Nothing])])-- ,"postingamount" ~: do- assertParseEqual (parseWithCtx nullctx postingamount " $47.18") (Mixed [dollars 47.18])- assertParseEqual (parseWithCtx nullctx postingamount " $1.")- (Mixed [Amount Commodity {symbol="$",side=L,spaced=False,decimalpoint='.',precision=0,separator=',',separatorpositions=[]} 1 Nothing])- ,"postingamount with unit price" ~: do- assertParseEqual- (parseWithCtx nullctx postingamount " $10 @ €0.5")- (Mixed [Amount{commodity=dollar{precision=0},- quantity=10,- price=(Just $ UnitPrice $ Mixed [Amount{commodity=euro{precision=1},- quantity=0.5,- price=Nothing}])}])- ,"postingamount with total price" ~: do- assertParseEqual- (parseWithCtx nullctx postingamount " $10 @@ €5")- (Mixed [Amount{commodity=dollar{precision=0},- quantity=10,- price=(Just $ TotalPrice $ Mixed [Amount{commodity=euro{precision=0},- quantity=5,- price=Nothing}])}])-- ,"leftsymbolamount" ~: do- assertParseEqual (parseWithCtx nullctx leftsymbolamount "$1")- (Mixed [Amount Commodity {symbol="$",side=L,spaced=False,decimalpoint='.',precision=0,separator=',',separatorpositions=[]} 1 Nothing])- assertParseEqual (parseWithCtx nullctx leftsymbolamount "$-1")- (Mixed [Amount Commodity {symbol="$",side=L,spaced=False,decimalpoint='.',precision=0,separator=',',separatorpositions=[]} (-1) Nothing])- assertParseEqual (parseWithCtx nullctx leftsymbolamount "-$1")- (Mixed [Amount Commodity {symbol="$",side=L,spaced=False,decimalpoint='.',precision=0,separator=',',separatorpositions=[]} (-1) Nothing])-- ]--entry1_str = unlines- ["2007/01/28 coopportunity"- ," expenses:food:groceries $47.18"- ," assets:checking $-47.18"- ,""- ]--entry1 =- txnTieKnot $ Transaction (parsedate "2007/01/28") Nothing False "" "coopportunity" "" []- [Posting False "expenses:food:groceries" (Mixed [dollars 47.18]) "" RegularPosting [] Nothing, - Posting False "assets:checking" (Mixed [dollars (-47.18)]) "" RegularPosting [] Nothing] ""-+--- * -*- outline-regexp:"--- *"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-|++A reader for hledger's journal file format+(<http://hledger.org/hledger.html#the-journal-file>). hledger's journal+format is a compatible subset of c++ ledger's+(<http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format>), so this+reader should handle many ledger files as well. Example:++@+2012\/3\/24 gift+ expenses:gifts $10+ assets:cash+@++Journal format supports the include directive which can read files in+other formats, so the other file format readers need to be importable+and invocable here.++Some important parts of journal parsing are therefore kept in+Hledger.Read.Common, to avoid import cycles.++-}++--- ** language++{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE NoMonoLocalBinds #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiWayIf #-}++--- ** exports+module Hledger.Read.JournalReader (++ -- * Reader-finding utils+ findReader,+ splitReaderPrefix,++ -- * Reader+ reader,++ -- * Parsing utils+ parseAndFinaliseJournal,+ runJournalParser,+ rjp,+ runErroringJournalParser,+ rejp,++ -- * Parsers used elsewhere+ getParentAccount,+ journalp,+ directivep,+ defaultyeardirectivep,+ marketpricedirectivep,+ datetimep,+ datep,+ modifiedaccountnamep,+ tmpostingrulep,+ statusp,+ emptyorcommentlinep,+ followingcommentp,+ accountaliasp,+ parseAssertDirective++ -- * Tests+ ,tests_JournalReader+)+where++--- ** imports+import Control.Exception qualified as C+import Control.Monad (forM_, when, void, unless, filterM, forM, guard)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Control.Monad.Except (ExceptT(..), runExceptT)+import Control.Monad.State.Strict (evalStateT,get,modify',put)+import Control.Monad.Trans.Class (lift)+import Data.Bifunctor (first)+import Data.Char (isDigit, isSpace, toLower)+import Data.Either (isRight, lefts)+import Data.Functor ((<&>))+import Data.Map.Strict qualified as M+import Data.Text (Text)+import Data.String+import Data.List+import Data.Maybe+import Data.Text qualified as T+import Data.Time.Calendar+import Data.Time.LocalTime+import Safe+import Text.Megaparsec hiding (parse)+import Text.Megaparsec.Char+import Text.Printf+import System.Directory (canonicalizePath, doesFileExist, makeAbsolute)+import System.Environment (lookupEnv)+import System.FilePath+import System.IO.Unsafe (unsafePerformIO)+import "Glob" System.FilePath.Glob hiding (match)+-- import "filepattern" System.FilePattern.Directory++import Hledger.Data+import Hledger.Query (parseQuery, querySplitRowTerms)+import Hledger.Read.Common+import Hledger.Utils++import Hledger.Read.CsvReader qualified as CsvReader (reader)+import Hledger.Read.RulesReader qualified as RulesReader (reader)+import Hledger.Read.TimeclockReader qualified as TimeclockReader (reader)+import Hledger.Read.TimedotReader qualified as TimedotReader (reader)+import Data.Function ((&))++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings+--+--- ** parsing utilities++-- | Run a journal parser in some monad. See also: parseWithState.+runJournalParser, rjp+ :: Monad m+ => JournalParser m a -> Text -> m (Either HledgerParseErrors a)+runJournalParser p = runParserT (evalStateT p nulljournal) ""+rjp = runJournalParser++-- | Run an erroring journal parser in some monad. See also: parseWithState.+runErroringJournalParser, rejp+ :: Monad m+ => ErroringJournalParser m a+ -> Text+ -> m (Either FinalParseError (Either HledgerParseErrors a))+runErroringJournalParser p t =+ runExceptT $ runParserT (evalStateT p nulljournal) "" t+rejp = runErroringJournalParser+++--- ** reader finding utilities+-- Defined here rather than Hledger.Read so that we can use them in includedirectivep below.++-- The available journal readers, each one handling a particular data format.+readers' :: MonadIO m => [Reader m]+readers' = [+ reader+ ,TimeclockReader.reader+ ,TimedotReader.reader+ ,RulesReader.reader+ ,CsvReader.reader Csv+ ,CsvReader.reader Tsv+ ,CsvReader.reader Ssv+-- ,LedgerReader.reader+ ]++readerNames :: [String]+readerNames = map (show . rFormat) (readers'::[Reader IO])++-- | @findReader mformat mpath@+--+-- Find the reader named by @mformat@, if provided.+-- ("ssv" and "tsv" are recognised as alternate names for the csv reader,+-- which also handles those formats.)+-- Or, if a file path is provided, find the first reader that handles+-- its file extension, if any.+findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)+findReader Nothing Nothing = Nothing+findReader (Just fmt) _ = headMay [r | r <- readers', let rname = rFormat r, rname == fmt]+findReader Nothing (Just path) =+ case prefix of+ Just fmt -> headMay [r | r <- readers', rFormat r == fmt]+ Nothing -> headMay [r | r <- readers', ext `elem` rExtensions r]+ where+ (prefix,path') = splitReaderPrefix path+ ext = map toLower $ drop 1 $ takeExtension path'++-- | Separate a file path and its reader prefix, if any.+--+-- >>> splitReaderPrefix "csv:-"+-- (Just csv,"-")+splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)+splitReaderPrefix f =+ let + candidates = [(Just r, drop (length r + 1) f) | r <- readerNames ++ ["ssv","tsv"], (r++":") `isPrefixOf` f]+ (strPrefix, newF) = headDef (Nothing, f) candidates+ in case strPrefix of+ Just "csv" -> (Just (Sep Csv), newF)+ Just "tsv" -> (Just (Sep Tsv), newF)+ Just "ssv" -> (Just (Sep Ssv), newF)+ Just "journal" -> (Just Journal', newF)+ Just "timeclock" -> (Just Timeclock, newF)+ Just "timedot" -> (Just Timedot, newF)+ _ -> (Nothing, f)++-- -- | Does this file path have a reader prefix ?+-- hasReaderPrefix :: PrefixedFilePath -> Bool+-- hasReaderPrefix = isJust . fst. splitReaderPrefix++-- -- | Add a reader prefix to a file path, unless it already has one.+-- -- The argument should be a valid reader name.+-- --+-- -- >>> addReaderPrefix "csv" "a.txt"+-- -- >>> "csv:a.txt"+-- -- >>> addReaderPrefix "csv" "timedot:a.txt"+-- -- >>> "timedot:a.txt"+-- addReaderPrefix :: ReaderPrefix -> FilePath -> PrefixedFilePath+-- addReaderPrefix readername f+-- | hasReaderPrefix f = f+-- | otherwise = readername <> ":" <> f++--- ** reader++reader :: MonadIO m => Reader m+reader = Reader+ {rFormat = Journal'+ ,rExtensions = ["journal", "j", "hledger", "ledger"]+ ,rReadFn = handleReadFnToTextReadFn parse+ ,rParser = journalp -- no need to add command line aliases like journalp'+ -- when called as a subparser I think+ }++-- | Parse and post-process a "Journal" from hledger's journal file+-- format, or give an error.+parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal+parse iopts f = parseAndFinaliseJournal journalp' iopts f+ where+ journalp' = do+ modify' (\j -> j{jparseoptaliases = aliasesFromOpts iopts})+ journalp iopts++--- ** parsers+--- *** journal++-- | A journal parser. Accumulates and returns a "ParsedJournal",+-- which should be finalised/validated before use.+--+-- >>> rejp (journalp definputopts <* eof) "2015/1/1\n a 0\n"+-- Right (Right Journal (unknown) with 1 transactions, 1 accounts)+--+journalp :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal+journalp iopts = do+ many $ addJournalItemP iopts+ eof+ modify' $ \j -> j{jparsepos = Nothing, jparseamountstyles = mempty, jparsetexts = mempty} -- drop parse-time state that is only meaningful during parsing+ get++-- | A side-effecting parser; parses any kind of journal item+-- and updates the parse state accordingly.+-- Every item is also recorded in jitems, so the file can be reproduced.+addJournalItemP :: MonadIO m => InputOpts -> ErroringJournalParser m ()+addJournalItemP iopts = (<?> "transaction or directive") $ do+ -- Journal item types can be told apart by their first character. Where that+ -- is unambiguous, go straight to the right parser: trying every alternative+ -- for every item (mostly transactions and blank lines) was a large parsing cost.+ -- The fallbacks keep the error messages the same as before.+ c <- lookAhead anySingle+ if | isDigit c -> transactionitem+ | c == 'P' -> priceitem <|> anyitem+ | isSpace c || isLineCommentStart c -> blankorcommentitem <|> anyitem+ | otherwise -> anyitem+ where+ transactionitem = transactionOrFastp >>= modify' . addTransactionItem -- (fastPathEnabled disables the fast path)+ priceitem = recordItem JIDirective marketpriceOrFastp >>= modify' . addPriceDirective+ blankorcommentitem = recordItem commentOrBlankItem $ lift emptyorcommentlinep+ anyitem = choice [+ directivep iopts+ , transactionitem+ , recordItem JIDirective transactionmodifierp >>= modify' . addTransactionModifier+ , recordItem JIDirective periodictransactionp >>= modify' . addPeriodicTransaction+ , priceitem+ , blankorcommentitem+ , recordItem JICommentBlock $ lift multilinecommentp+ ]+ commentOrBlankItem txt = if T.all isSpace txt then JIBlank else JIComment txt++-- | Run a parser, also recording the text it consumed as a journal item of the given kind.+recordItem :: (Text -> JournalItem) -> JournalParser m a -> JournalParser m a+recordItem mkitem p = do+ -- This is like megaparsec's `match`, but written out; `match` was found to allocate+ -- ~20KB per item here, costing ~9% of total run time on a 100k-transaction journal.+ -- Note T.take does not copy bytes: it returns a small Text value (array pointer, offset, length)+ -- viewing the same byte array as the remaining input, which is the whole file's text, already+ -- kept in jfiles. So each jitems entry costs a few words, however long its text is,+ -- and jitems adds little memory even though it holds every directive and comment line verbatim.+ o <- getOffset+ s <- getInput+ a <- p+ o' <- getOffset+ modify' $ addJournalItem $ mkitem $ T.take (o' - o) s+ return a++--- *** directives++-- | Parse any journal directive and update the parse state accordingly,+-- and record it as a journal item (exported or not by print --export).+-- Cf http://hledger.org/hledger.html#directives,+-- http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives+directivep :: MonadIO m => InputOpts -> ErroringJournalParser m ()+directivep iopts = (do+ optional $ oneOf ['!','@']+ choice [+ includedirectivep iopts+ -- directives which print --export reproduces+ ,recordItem JIDirective $ choice [+ accountdirectivep+ ,commoditydirectivep+ ,decimalmarkdirectivep+ ,defaultyeardirectivep+ ,defaultcommoditydirectivep+ ,payeedirectivep+ ,tagdirectivep+ ,assertdirectivep (_ioDay iopts) >>= modify' . addAssertDirective+ ]+ -- directives which print --export does not reproduce:+ -- those whose effect is already applied to the parsed data,+ -- and the Ledger directives which hledger ignores.+ -- (endtagdirectivep consumes "end" before failing, so it must come after the other end directives.)+ ,recordItem JINonExportedDirective $ choice [+ aliasdirectivep+ ,endaliasesdirectivep+ ,applyaccountdirectivep+ ,applyyeardirectivep+ ,bareenddirectivep+ ,endapplyaccountdirectivep+ ,endapplyyeardirectivep+ ,applyfixeddirectivep+ ,applytagdirectivep+ ,bucketdirectivep+ ,capturedirectivep+ ,checkdirectivep+ ,commandlineflagdirectivep+ ,commodityconversiondirectivep+ ,definedirectivep+ ,endapplyfixeddirectivep+ ,endapplytagdirectivep+ ,endtagdirectivep+ ,evaldirectivep+ ,exprdirectivep+ ,ignoredpricecommoditydirectivep+ ,pythondirectivep+ ,valuedirectivep+ ]+ ]+ ) <?> "directive"++-- | Parse an include directive, and the file(s) it refers to, possibly recursively.+-- Input options are required since they may affect parsing (of timeclock files, specifically).+-- include's argument is a file path or glob pattern (see findMatchedFiles for details),+-- optionally with a file type prefix. Relative paths are relative to the current file.+includedirectivep :: MonadIO m => InputOpts -> ErroringJournalParser m ()+includedirectivep iopts = do+ -- save the position at start of include directive, for error messages+ eoff <- getOffset+ pos <- getSourcePos'+ let errorNoArg = customFailure $ parseErrorAt eoff "include needs a file path or glob pattern argument"++ -- parse the directive, and record it as a journal item (before the included files' items)+ prefixedglob <- recordItem JIInclude $ do+ string "include"+ -- notFollowedBy newline <?> "a file path or glob pattern argument"+ (do+ lift skipNonNewlineSpaces1+ prefixedglob <- rstrip . T.unpack <$> takeWhileP Nothing (`notElem` [';','\n'])+ lift followingcommentp+ return prefixedglob+ ) <|> errorNoArg++ let (mprefix,path) = splitReaderPrefix prefixedglob+ parentf <- sourcePosFilePath pos+ when (null $ dbg6 (parentf <> " include: path ") path) errorNoArg++ -- Find the file or glob-matched files (just the ones from this include directive), with some IO error checking.+ paths <- findMatchedFiles eoff parentf path+ -- Also report whether a glob pattern was used, and not just a literal file path.+ -- (paths, isglob) <- findMatchedFiles off pos glb++ -- XXX worth the trouble ? no+ -- Comprehensively exclude files already processed. Some complexities here:+ -- If this include directive uses a glob pattern, remove duplicates. + -- Ie if this glob pattern matches any files we have already processed (or the current file),+ -- due to multiple includes in sequence or in a cycle, exclude those files so they're not processed again.+ -- If this include directive uses a literal file path, don't remove duplicates.+ -- Multiple includes in sequence will cause the included file to be processed multiple times.+ -- Multiple includes forming a cycle will be detected and reported as an error in parseIncludedFile.+ -- let paths' = if isglob then filter (...) paths else paths++ -- if there was a reader prefix, apply it to all the file paths+ let prefixedpaths = case mprefix of+ Nothing -> paths+ Just fmt -> map ((show fmt++":")++) paths++ -- Parse each one, as if inlined here.+ -- Or when just finding the files read, record a missing one and carry on.+ forM_ prefixedpaths $ \p -> do+ let f = snd $ splitReaderPrefix p+ missing <- liftIO $ not <$> doesFileExist f+ if _scanfiles iopts && missing+ then modify' $ \pj -> pj{jfiles = JournalFile f T.empty (length $ jparseincludefilestack pj) : jfiles pj}+ else parseIncludedFile iopts eoff p++ where++ -- | Find the files matched by a literal path or a glob pattern.+ -- Examples: foo.j, ../foo/bar.j, timedot:/foo/2020*, *.journal, **.journal.+ --+ -- Uses the current parse context for detecting the current directory and for error messages.+ -- Expands a leading tilde to the user's home directory.+ -- Converts ** without a slash to **/*, like zsh's GLOB_STAR_SHORT, so ** also matches file name parts.+ -- Checks if any matched paths are directories and excludes those.+ -- Converts all matched paths to their canonical form.+ -- Note * and ** mostly won't implicitly match dot files or dot directories,+ -- but ** will implicitly search non-top-level dot directories (see #2498, Glob#49).++ findMatchedFiles :: (MonadIO m) => Int -> FilePath -> FilePath -> JournalParser m [FilePath]+ findMatchedFiles off parentf path = do++ -- Some notes about the Glob library that we use (related: https://github.com/Deewiant/glob/issues/49):+ -- It does not expand tilde.+ -- It does not canonicalise paths.+ -- The results are not in any particular order.+ -- The results can include directories.+ -- DIRPAT/ is equivalent to DIRPAT, except results will end with // (double slash).+ -- A . or .. path component can match the current or parent directories (including them in the results).+ -- * matches zero or more characters in a file or directory name.+ -- * at the start of a file name ignores dot-named files and directories, by default.+ -- ** (or zero or more consecutive *'s) not followed by slash is equivalent to *.+ -- A **/ component matches any number of directory parts.+ -- A **/ does not implicitly search top-level dot directories or implicitly match do files,+ -- but it does search non-top-level dot directories. Eg ** will find the c file in a/.b/c.+ -- It tends to get attributes of all files in a directory.++ -- expand a tilde at the start of the glob pattern, or throw an error+ expandedpath <- lift $ expandHomePath path & handleIOError off "failed to expand ~"++ -- get the directory of the including file+ -- need to canonicalise a symlink parentf so takeDirectory works correctly [#2503]+ cwd <- fmap takeDirectory <$> liftIO $ canonicalizePath parentf++ -- Don't allow 3 or more stars.+ when ("***" `isInfixOf` expandedpath) $+ customFailure $ parseErrorAt off $ "Invalid glob pattern: too many stars, use * or **"++ -- Make ** also match file name parts like zsh's GLOB_STAR_SHORT.+ let+ finalpath =+ -- ** without a slash is equivalent to **/*+ case regexReplace (toRegex' $ T.pack "\\*\\*([^/\\])") "**/*\\1" expandedpath of+ Right s -> s+ Left _ -> expandedpath -- ignore any error, there should be none++ -- Compile as a Pattern. Can throw an error.+ pat <- case tryCompileWith compDefault{errorRecovery=False} finalpath of+ Left e -> customFailure $ parseErrorAt off $ "Invalid glob pattern: " ++ e+ Right x -> pure x++ -- Find all paths matched by the glob pattern.+ -- If it is a literal (non-glob) path, don't use the Glob lib, because it gets attributes+ -- of all files in the directory, which confuses build systems like tup.+ paths <-+ if isLiteral pat+ then return $ if isAbsolute finalpath then [finalpath] else [cwd </> finalpath]+ else liftIO $ globDir1 pat cwd++ -- Exclude any directories or symlinks to directories, and canonicalise, and sort.+ files <- liftIO $+ filterM doesFileExist paths+ >>= mapM makeAbsolute+ <&> sort++ -- Throw an error if one of these files is among the grandparent files, forming a cycle.+ -- Though, ignore the immediate parent file for convenience. XXX inconsistent - should it ignore all cyclic includes ?+ -- Use canonical paths for cycle detection, show nominal absolute paths in error messages.+ parentj <- get+ let parentfiles = jparseincludefilestack parentj+ cparentfiles = map snd parentfiles+ cparentf = take 1 cparentfiles+ files2 <- forM files $ \f -> do+ cf <- liftIO $ canonicalizePath f+ if+ | [cf] == cparentf -> return cf -- current file - return canonicalised, will be excluded later+ | cf `elem` drop 1 cparentfiles -> customFailure $ parseErrorAt off $ "This included file forms a cycle: " ++ f+ | otherwise -> return f++ -- Throw an error if no files were matched.+ -- Or when just finding the files read, return the path or pattern itself, to be recorded as missing.+ let unmatched = [if isAbsolute finalpath then finalpath else cwd </> finalpath]+ when (null files2 && not (_scanfiles iopts)) $ customFailure $ parseErrorAt off $ "No files were matched by: " ++ path++ -- If the current file got included, ignore it (last, to avoid triggering the error above).+ let+ files3 =+ dbg6 (parentf <> " include: matched files (excluding current file)") $+ if null files2 then unmatched else filter (not.(`elem` cparentf)) files2++ return files3++ -- Parse the given included file (and any deeper includes, recursively) as if it was inlined in the current (parent) file.+ -- The offset of the start of the include directive in the parent file is provided for error messages.+ parseIncludedFile :: MonadIO m => InputOpts -> Int -> PrefixedFilePath -> ErroringJournalParser m ()+ parseIncludedFile iopts1 off prefixedpath = do+ let (_mprefix,filepath) = splitReaderPrefix prefixedpath++ -- Choose a reader based on the file path prefix or file extension,+ -- defaulting to JournalReader. Duplicating readJournal a bit here.+ let r = fromMaybe reader $ findReader Nothing (Just prefixedpath)+ parser = (rParser r) iopts1+ dbg7IO "parseIncludedFile: trying reader" (rFormat r)++ -- Read the file's content (or its replacement text from the input options), or throw an error.+ -- Readers which read their own input (CSV, rules) are given empty text instead.+ cfilepath <- liftIO $ canonicalizePath filepath+ childInput <-+ if readerReadsOwnInput r then pure ""+ else case M.lookup cfilepath (_fileoverrides iopts1) of+ Just t -> pure t+ Nothing -> lift $ readFilePortably filepath & handleIOError off "failed to read a file"+ parentj <- get+ let initChildj = newJournalWithParseStateFrom filepath cfilepath parentj++ -- Parse the file (and its own includes, if any) to a Journal+ -- with file path and source text attached. Or throw an error.+ -- Its include depth is the length of the parent's include file stack (which includes the parent).+ updatedChildj <- journalAddFile (JournalFile filepath childInput (length $ jparseincludefilestack parentj)) <$>+ parseIncludeFile parser initChildj filepath childInput++ -- Child journal was parsed successfully; now merge it into the parent journal.+ -- Debug logging is provided for troubleshooting account display order (eg).+ -- The parent journal is the second argument to journalConcat; this means+ -- its parse state is kept, and its lists are appended to child's (which+ -- ultimately produces the right list order, because parent's and child's+ -- lists are in reverse order at this stage. Cf #1909)+ let+ parentj' =+ dbgJournalAcctDeclOrder ("parseChild: child " <> childfilename <> " acct decls: ") updatedChildj+ `journalConcat`+ dbgJournalAcctDeclOrder ("parseChild: parent " <> parentfilename <> " acct decls: ") parentj++ where+ childfilename = takeFileName filepath+ parentfilename = maybe "(unknown)" takeFileName $ fmap fst $ headMay $ jparseincludefilestack parentj -- XXX more accurate than journalFilePath for some reason++ -- And update the current parse state.+ put parentj'++ where+ newJournalWithParseStateFrom :: FilePath -> FilePath -> Journal -> Journal+ newJournalWithParseStateFrom filepath cfilepath j = nulljournal{+ jparsedefaultyear = jparsedefaultyear j+ ,jparseapplyyears = jparseapplyyears j+ ,jparsedefaultcommodity = jparsedefaultcommodity j+ ,jparseparentaccounts = jparseparentaccounts j+ ,jparsedecimalmark = jparsedecimalmark j+ ,jparsealiases = jparsealiases j+ ,jparseoptaliases = jparseoptaliases j+ ,jdeclaredcommodities = jdeclaredcommodities j+ -- ,jparsetransactioncount = jparsetransactioncount j+ ,jparsetimeclockentries = jparsetimeclockentries j+ ,jparseincludefilestack = (filepath, cfilepath) : jparseincludefilestack j+ }++-- Get the absolute path of the file referenced by this parse position.+-- (Symbolic links will not be dereferenced.)+-- This probably will always succeed, since the parse file's path is probably always absolute.+sourcePosFilePath :: (MonadIO m) => SourcePos -> m FilePath+sourcePosFilePath = liftIO . makeAbsolute . sourceName++-- | Lift an IO action into the exception monad, converting any IO error+-- to a parse error message at the given offset.+handleIOError :: MonadIO m => Int -> String -> IO a -> TextParser m a+handleIOError off msg io = do+ eResult <- liftIO $ (Right <$> io) `C.catch` \(e::C.IOException) -> pure $ Left $ printf "%s:\n%s" msg (show e)+ case eResult of+ Right res -> pure res+ Left errMsg -> setOffset off >> fail errMsg++-- Parse an account directive, adding its info to the journal's+-- list of account declarations.+accountdirectivep :: JournalParser m ()+accountdirectivep = do+ off <- getOffset -- XXX figure out a more precise position later+ pos <- getSourcePos'++ string "account"+ lift skipNonNewlineSpaces1++ -- the account name, possibly modified by preceding alias or apply account directives;+ -- also kept without the parent account, as the target of any alias: tags below+ -- (which, like alias directives, are applied before the parent account is added; see accountNameApplyModifiers)+ aliasedacct <- (notFollowedBy (char '(' <|> char '[') <?> "account name without brackets") >>+ aliasedaccountnamep True+ acct <- applyParentAndOptionAliases aliasedacct++ -- maybe a comment, on this and/or following lines+ commentoff <- getOffset+ (cmt, commenttags) <- lift transactioncommentp++ -- maybe Ledger-style subdirectives: alias NAME declares an account alias, and is kept as an alias: tag;+ -- the others are ignored+ subdirectivealiases <- catMaybes <$> many (try aliassubdirectivep <|> (Nothing <$ indentedlinep))+ let tags = commenttags ++ [("alias", a) | a <- subdirectivealiases]++ -- an account type may have been set by account type code or a tag;+ -- the latter takes precedence+ let+ metype = parseAccountTypeCode <$> lookup accountTypeTagName tags++ -- alias: tags declare account aliases, like alias directives at this point+ let acctaliases = [v | (n, v) <- tags, T.toLower n == "alias"]+ when (any T.null acctaliases) $ customFailure $ parseErrorAt commentoff+ "an alias: tag on an account directive should have an account name as its value, eg alias: checking"+ mapM_ (addAccountAlias . (`BasicAlias` aliasedacct)) acctaliases++ -- update the journal+ addAccountDeclaration (acct, cmt, tags, pos)+ unless (null tags) $ addDeclaredAccountTags acct tags+ case metype of+ Nothing -> return ()+ Just (Right t) -> addDeclaredAccountType acct t+ Just (Left err) -> customFailure $ parseErrorAt off err++-- The special tag used for declaring account type. XXX change to "class" ?+accountTypeTagName = "type"++-- | Parse the value of an account declaration's type: tag (a one-letter code or long-form name).+parseAccountTypeCode :: Text -> Either String AccountType+parseAccountTypeCode s = first err $ parseAccountType True s+ where+ err _ = T.unpack $ "invalid account type code "<>s<>", should be one of " <> T.pack (accountTypeChoices True)++-- Add an account declaration to the journal, auto-numbering it.+addAccountDeclaration :: (AccountName,Text,[Tag],SourcePos) -> JournalParser m ()+addAccountDeclaration (a,cmt,tags,pos) = do+ modify' (\j ->+ let+ decls = jdeclaredaccounts j+ d = (a, nullaccountdeclarationinfo{+ adicomment = cmt+ ,aditags = tags+ ,adideclarationorder = length decls + 1 -- gets renumbered when Journals are finalised or merged+ ,adisourcepos = pos+ })+ in+ j{jdeclaredaccounts = d:decls})++-- Add a payee declaration to the journal.+addPayeeDeclaration :: (Payee,Text,[Tag]) -> JournalParser m ()+addPayeeDeclaration (p, cmt, tags) =+ modify' (\j@Journal{jdeclaredpayees} -> j{jdeclaredpayees=d:jdeclaredpayees})+ where+ d = (p+ ,nullpayeedeclarationinfo{+ pdicomment = cmt+ ,pditags = tags+ })++-- Add a tag declaration to the journal.+addTagDeclaration :: (TagName,Text) -> JournalParser m ()+addTagDeclaration (t, cmt) =+ modify' (\j@Journal{jdeclaredtags} -> j{jdeclaredtags=tagandinfo:jdeclaredtags})+ where+ tagandinfo = (t, nulltagdeclarationinfo{tdicomment=cmt})++indentedlinep :: JournalParser m String+indentedlinep = lift skipNonNewlineSpaces1 >> (rstrip <$> lift restofline)++-- | Parse a Ledger-style @alias NAME@ subdirective (an indented line) of an account directive,+-- returning the alias name.+aliassubdirectivep :: JournalParser m (Maybe AccountName)+aliassubdirectivep = do+ lift skipNonNewlineSpaces1+ string "alias"+ lift skipNonNewlineSpaces1+ Just . T.pack . rstrip <$> lift restofline++-- | Parse a one-line or multi-line commodity directive.+--+-- >>> Right _ <- rjp commoditydirectivep "commodity $1.00"+-- >>> Right _ <- rjp commoditydirectivep "commodity $\n format $1.00"+-- >>> Right _ <- rjp commoditydirectivep "commodity $\n\n" -- a commodity with no format+-- >>> Right _ <- rjp commoditydirectivep "commodity $1.00\n format $1.00" -- both, what happens ?+commoditydirectivep :: JournalParser m ()+commoditydirectivep = commoditydirectiveonelinep <|> commoditydirectivemultilinep++-- | Parse a one-line commodity directive.+--+-- >>> Right _ <- rjp commoditydirectiveonelinep "commodity $1.00"+-- >>> Right _ <- rjp commoditydirectiveonelinep "commodity $1.00 ; blah\n"+commoditydirectiveonelinep :: JournalParser m ()+commoditydirectiveonelinep = do+ (off, pos, Amount{acommodity,astyle}) <- try $ do+ string "commodity"+ pos <- getSourcePos'+ lift skipNonNewlineSpaces1+ off <- getOffset+ amt <- amountp' StyleAmount+ pure $ (off, pos, amt)+ lift skipNonNewlineSpaces+ commentoff <- getOffset+ (comment, tags) <- lift transactioncommentp+ commaliases <- commodityaliasesp commentoff acommodity tags+ let comm = Commodity{csymbol=acommodity, cformat=Just $ dbg7 "style from commodity directive" astyle, ccomment=comment, ctags=tags, caliases=[(a, pos) | a <- commaliases], csourcepos=pos}+ if isNothing $ asdecimalmark astyle+ then customFailure $ parseErrorAt off pleaseincludedecimalpoint+ else modify' (addCommodityDeclaration comm)++pleaseincludedecimalpoint :: String+pleaseincludedecimalpoint = chomp $ unlines [+ "Please include a decimal point or decimal comma in commodity directives,"+ ,"to help us parse correctly. It may be followed by zero or more decimal digits."+ ,"Examples:"+ ,"commodity $1000. ; no thousands mark, decimal period, no decimals"+ ,"commodity 1.234,00 ARS ; period at thousands, decimal comma, 2 decimals"+ ,"commodity EUR 1 000,000 ; space at thousands, decimal comma, 3 decimals"+ ,"commodity INR1,23,45,678.0 ; comma at thousands/lakhs/crores, decimal period, 1 decimal"+ ]++-- | Parse a multi-line commodity directive, containing 0 or more format subdirectives.+--+-- >>> Right _ <- rjp commoditydirectivemultilinep "commodity $ ; blah \n format $1.00 ; blah"+commoditydirectivemultilinep :: JournalParser m ()+commoditydirectivemultilinep = do+ string "commodity"+ pos <- getSourcePos'+ lift skipNonNewlineSpaces1+ sym <- lift commoditysymbolp+ commentoff <- getOffset+ (comment, tags) <- lift transactioncommentp+ commaliases <- commodityaliasesp commentoff sym tags+ -- read all subdirectives, saving format subdirectives as Lefts+ subdirectives <- many $ indented (eitherP (formatdirectivep sym) (lift restofline))+ let mfmt = lastMay $ lefts subdirectives+ let comm = Commodity{csymbol=sym, cformat=mfmt, ccomment=comment, ctags=tags, caliases=[(a, pos) | a <- commaliases], csourcepos=pos}+ modify' (addCommodityDeclaration comm)+ where+ indented = (lift skipNonNewlineSpaces1 >>)++-- | Add a commodity directive's declaration to the journal.+-- A commodity declared again adds to its earlier declaration (see 'commodityRedeclare').+addCommodityDeclaration :: Commodity -> Journal -> Journal+addCommodityDeclaration comm@Commodity{csymbol, ctags} j = j{+ jdeclaredcommodities = M.insertWith commodityRedeclare csymbol comm $ jdeclaredcommodities j+ ,jdeclaredcommoditytags = if null ctags then jdeclaredcommoditytags j+ else M.insertWith union csymbol ctags $ jdeclaredcommoditytags j+ }++-- | Parse a format (sub)directive, throwing a parse error if its+-- symbol does not match the one given.+formatdirectivep :: CommoditySymbol -> JournalParser m AmountStyle+formatdirectivep expectedsym = do+ string "format"+ lift skipNonNewlineSpaces1+ off <- getOffset+ Amount{acommodity,astyle} <- amountp' StyleAmount+ _ <- lift followingcommentp+ if acommodity==expectedsym+ then+ if isNothing $ asdecimalmark astyle+ then customFailure $ parseErrorAt off pleaseincludedecimalpoint+ else return $ dbg7 "style from format subdirective" astyle+ else customFailure $ parseErrorAt off $+ printf "commodity directive symbol \"%s\" and format directive symbol \"%s\" should be the same" expectedsym acommodity++-- | Parse the values of a commodity directive's alias: tags, if any.+-- Each value is one commodity symbol, optionally with a positive quantity:+-- the number of alias units equal to one unit of the commodity (1 if omitted).+-- These are returned as amounts, keeping the style they were written with.+-- A 1:1 alias to the commodity itself, or a repeat of an earlier alias, is ignored.+-- An alias already declared for this commodity (by an earlier commodity directive) with a different quantity is an error.+-- Errors are reported at the given offset (the start of the directive's comment).+commodityaliasesp :: Int -> CommoditySymbol -> [Tag] -> JournalParser m [Amount]+commodityaliasesp off sym tags = do+ j <- get+ commaliases <- nubOn symqty . filter ((/= (sym, 1)) . symqty) <$> mapM (aliasvalue j) [v | (n, v) <- tags, T.toLower n == "alias"]+ let aliassyms = map acommodity commaliases+ if sym `elem` aliassyms then customFailure $ errAt $ printf "%s can't be an alias of itself with a quantity other than 1" (quote sym)+ else case aliassyms \\ nub aliassyms of+ a:_ -> customFailure $ errAt $ printf "alias %s is declared more than once, with different quantities" (quote a)+ [] -> case [(a, e, epos) | a <- commaliases, (e, epos) <- earlieraliases j, acommodity e == acommodity a, aquantity e /= aquantity a] of+ (a, e, epos):_ -> customFailure $ errAt $ printf "alias %s was declared earlier for %s with a different quantity (%s), at %s"+ (quote $ acommodity a) (quote sym) (show $ aquantity e) (sourcePosFileLine epos)+ [] -> pure commaliases+ where+ earlieraliases j = maybe [] caliases $ M.lookup sym $ jdeclaredcommodities j+ errAt = parseErrorAt off+ symqty a = (acommodity a, aquantity a)+ nubOn f = nubBy (\a b -> f a == f b)+ quote t = "\"" <> T.unpack t <> "\""+ aliasvalue j v = case runParser (evalStateT aliasp j) "" v of+ Right a | not (T.null $ acommodity a) && aquantity a > 0 -> pure a+ _ -> customFailure $ errAt $ printf (unlines+ ["could not parse commodity alias %s."+ ,"Each alias: tag should contain one commodity symbol, optionally with a positive quantity,"+ ,"the number of alias units equal to one %s. Eg: alias: $, alias: 100 cents"+ ]) (quote v) (T.unpack sym)+ aliasp = do+ let spaces = lift skipNonNewlineSpaces+ spaces+ try ((\a -> nullamt{acommodity=a, aquantity=1}) <$> lift commoditysymbolp <* spaces <* eof)+ <|> (simpleamountp MultiplierAmount <* spaces <* eof)++-- More Ledger directives, ignore for now:+-- apply fixed, apply tag, bucket, A, capture, check, define, expr+-- (Ledger's assert directive is not supported; hledger's assert directive is different, see assertdirectivep.)+applyfixeddirectivep, endapplyfixeddirectivep, applytagdirectivep, endapplytagdirectivep,+ bucketdirectivep, capturedirectivep, checkdirectivep,+ definedirectivep, exprdirectivep, valuedirectivep,+ evaldirectivep, pythondirectivep, commandlineflagdirectivep+ :: JournalParser m ()+applyfixeddirectivep = do string "apply fixed" >> lift restofline >> return ()+endapplyfixeddirectivep = do string "end apply fixed" >> lift restofline >> return ()+applytagdirectivep = do string "apply tag" >> lift restofline >> return ()+endapplytagdirectivep = do string "end apply tag" >> lift restofline >> return ()++bucketdirectivep = do string "A " <|> string "bucket " >> lift restofline >> return ()+capturedirectivep = do string "capture" >> lift restofline >> return ()+checkdirectivep = do string "check" >> lift restofline >> return ()+definedirectivep = do string "define" >> lift restofline >> return ()+exprdirectivep = do string "expr" >> lift restofline >> return ()+valuedirectivep = do string "value" >> lift restofline >> return ()+evaldirectivep = do string "eval" >> lift restofline >> return ()+commandlineflagdirectivep = do string "--" >> lift restofline >> return ()+pythondirectivep = do+ string "python" >> lift restofline+ many $ indentedline <|> blankline+ return ()+ where+ indentedline = lift skipNonNewlineSpaces1 >> lift restofline+ blankline = lift skipNonNewlineSpaces >> newline >> return "" <?> "blank line"++keywordp :: String -> JournalParser m ()+keywordp = void . string . fromString++spacesp :: JournalParser m ()+spacesp = void $ lift skipNonNewlineSpaces1++-- | Backtracking parser similar to string, but allows varying amount of space between words+keywordsp :: String -> JournalParser m ()+keywordsp = try . sequence_ . intersperse spacesp . map keywordp . words++applyaccountdirectivep :: JournalParser m ()+applyaccountdirectivep = do+ keywordsp "apply account" <?> "apply account directive"+ lift skipNonNewlineSpaces1+ parent <- lift parentaccountnamep+ newline+ pushParentAccount parent++endapplyaccountdirectivep :: JournalParser m ()+endapplyaccountdirectivep = do+ off <- getOffset+ keywordsp "end apply account" <?> "end apply account directive"+ lift restofline+ j <- get+ case jparseparentaccounts j of+ [] -> customFailure $ parseErrorAt off "end apply account has no matching apply account"+ (_:rest) -> put j{jparseparentaccounts = rest}++-- | Set the default year until the matching end apply year, saving the current one.+applyyeardirectivep :: JournalParser m ()+applyyeardirectivep = do+ keywordsp "apply year" <?> "apply year directive"+ lift skipNonNewlineSpaces+ y <- lift yearp+ lift restofline+ modify' (\j -> j{jparseapplyyears = jparsedefaultyear j : jparseapplyyears j, jparsedefaultyear = Just y})++-- | Restore the default year that was in effect before the matching apply year.+endapplyyeardirectivep :: JournalParser m ()+endapplyyeardirectivep = do+ off <- getOffset+ keywordsp "end apply year" <?> "end apply year directive"+ lift restofline+ j <- get+ case jparseapplyyears j of+ [] -> customFailure $ parseErrorAt off "end apply year has no matching apply year"+ (y:ys) -> put j{jparsedefaultyear = y, jparseapplyyears = ys}++-- | Reject Ledger's bare "end" or "end apply" (which closes the innermost apply block)+-- with a clear error, since hledger requires the kind of block to be named.+bareenddirectivep :: JournalParser m ()+bareenddirectivep = do+ off <- getOffset+ try $ keywordp "end" >> optional (try $ spacesp >> keywordp "apply") >> lift skipNonNewlineSpaces >> lookAhead (void eol <|> eof)+ customFailure $ parseErrorAt off $+ "hledger needs the kind of apply block here:\n"+ ++ "end apply account, end apply fixed, end apply tag, or end apply year"++aliasdirectivep :: JournalParser m ()+aliasdirectivep = do+ string "alias"+ lift skipNonNewlineSpaces1+ alias <- lift accountaliasp+ addAccountAlias alias++endaliasesdirectivep :: JournalParser m ()+endaliasesdirectivep = do+ keywordsp "end aliases" <?> "end aliases directive"+ lift restofline+ -- forget the aliases from alias directives/tags (--alias options are kept separately; see accountNameApplyModifiers)+ modify' (\j -> j{jparsealiases = []})++tagdirectivep :: JournalParser m ()+tagdirectivep = do+ string "tag" <?> "tag directive"+ lift skipNonNewlineSpaces1+ tagname <- lift $ T.pack <$> some nonspace+ (comment, _) <- lift transactioncommentp+ skipMany indentedlinep+ addTagDeclaration (tagname,comment)+ return ()++-- end tag or end apply tag+endtagdirectivep :: JournalParser m ()+endtagdirectivep = (do+ string "end"+ lift skipNonNewlineSpaces1+ optional $ string "apply" >> lift skipNonNewlineSpaces1+ string "tag"+ lift skipNonNewlineSpaces+ eol+ return ()+ ) <?> "end tag or end apply tag directive"++payeedirectivep :: JournalParser m ()+payeedirectivep = do+ string "payee" <?> "payee directive"+ lift skipNonNewlineSpaces1+ payee <- lift $ T.strip <$> (try doublequotedtextp <|> noncommenttext1p)+ (comment, tags) <- lift transactioncommentp+ skipMany indentedlinep+ addPayeeDeclaration (payee, comment, tags)+ return ()++defaultyeardirectivep :: JournalParser m ()+defaultyeardirectivep = do+ (string "Y" <|> string "year") <?> "default year"+ lift skipNonNewlineSpaces+ y <- lift yearp+ lift restofline+ setYear y++defaultcommoditydirectivep :: JournalParser m ()+defaultcommoditydirectivep = do+ char 'D' <?> "default commodity"+ lift skipNonNewlineSpaces1+ off <- getOffset+ Amount{acommodity,astyle} <- amountp' StyleAmount+ lift restofline+ if isNothing $ asdecimalmark astyle+ then customFailure $ parseErrorAt off pleaseincludedecimalpoint+ else setDefaultCommodityAndStyle (acommodity, astyle)++marketpricedirectivep :: JournalParser m PriceDirective+marketpricedirectivep = do+ pos <- getSourcePos'+ char 'P' <?> "market price"+ lift skipNonNewlineSpaces+ date <- datep+ lift skipNonNewlineSpaces1+ -- a time of day may follow the date; it is ignored (checked cheaply first, since usually there is none)+ mc <- lift peekChar+ mtime <- if maybe False isDigit mc then lift $ optional $ try timeofdayp else pure Nothing+ when (isJust mtime) $ lift skipNonNewlineSpaces1+ symbol <- shareText =<< lift commoditysymbolp+ lift skipNonNewlineSpaces1+ price <- amountp+ lift restofline+ return $ PriceDirective pos date symbol price++ignoredpricecommoditydirectivep :: JournalParser m ()+ignoredpricecommoditydirectivep = do+ char 'N' <?> "ignored-price commodity"+ lift skipNonNewlineSpaces1+ lift commoditysymbolp+ lift restofline+ return ()++commodityconversiondirectivep :: JournalParser m ()+commodityconversiondirectivep = do+ char 'C' <?> "commodity conversion"+ lift skipNonNewlineSpaces1+ amountp+ lift skipNonNewlineSpaces+ char '='+ lift skipNonNewlineSpaces+ amountp+ lift restofline+ return ()++-- | Read a valid decimal mark from the decimal-mark directive e.g+--+-- decimal-mark ,+decimalmarkdirectivep :: JournalParser m ()+decimalmarkdirectivep = do+ string "decimal-mark" <?> "decimal mark"+ lift skipNonNewlineSpaces1+ mark <- satisfy isDecimalMark+ modify' $ \j -> j{jparsedecimalmark=Just mark}+ lift restofline+ return ()++--- *** transactions++-- | Parse a transaction modifier (auto postings) rule.+transactionmodifierp :: JournalParser m TransactionModifier+transactionmodifierp = do+ char '=' <?> "modifier transaction"+ lift skipNonNewlineSpaces+ querytxt <- lift $ T.strip <$> descriptionp+ (_comment, _tags) <- lift transactioncommentp -- TODO apply these to modified txns ?+ postingrules <- tmpostingrulesp Nothing+ return $ TransactionModifier querytxt postingrules++-- | Parse a periodic transaction rule.+--+-- This reuses periodexprp which parses period expressions on the command line.+-- This is awkward because periodexprp supports relative and partial dates,+-- which we don't really need here, and it doesn't support the notion of a+-- default year set by a Y directive, which we do need to consider here.+-- We resolve it as follows: in periodic transactions' period expressions,+-- if there is a default year Y in effect, partial/relative dates are calculated+-- relative to Y/1/1. If not, they are calculated related to today as usual.+periodictransactionp :: MonadIO m => JournalParser m PeriodicTransaction+periodictransactionp = do+ startpos <- getSourcePos'++ -- first line+ char '~' <?> "periodic transaction"+ lift $ skipNonNewlineSpaces++ -- if there's a default year in effect, use Y/1/1 as base for partial/relative dates+ today <- liftIO getCurrentDay+ mdefaultyear <- getYear+ let refdate = case mdefaultyear of+ Nothing -> today+ Just y -> fromGregorian y 1 1+ periodExcerpt <- lift $ excerpt_ $+ singlespacedtextsatisfying1p (\c -> c /= ';' && c /= '\n')+ let periodtxt = T.strip $ getExcerptText periodExcerpt++ -- first parsing with 'singlespacedtextp', then "re-parsing" with+ -- 'periodexprp' saves 'periodexprp' from having to respect the single-+ -- and double-space parsing rules+ (interval, spn) <- lift $ reparseExcerpt periodExcerpt $ do+ pexp <- periodexprp refdate+ (<|>) eof $ do+ offset1 <- getOffset+ void takeRest+ offset2 <- getOffset+ customFailure $ parseErrorAtRegion offset1 offset2 $+ "remainder of period expression cannot be parsed"+ <> "\nperhaps you need to terminate the period expression with a double space?"+ <> "\na double space is required between period expression and description/comment"+ pure pexp++ status <- lift statusp <?> "cleared status"+ code <- lift codep <?> "transaction code"+ description <- lift $ T.strip <$> descriptionp+ (comment, tags) <- lift transactioncommentp+ -- next lines; use same year determined above.+ -- Amounts calculated with * or / are rounded to their own precision (#2648).+ postings <- map (fst . postingRoundCalculatedAmounts mempty) <$> postingsp (Just $ first3 $ toGregorian refdate)++ endpos <- getSourcePos'+ let sourcepos = (startpos, endpos)++ return $ nullperiodictransaction{+ ptperiodexpr=periodtxt+ ,ptinterval=interval+ ,ptspan=spn+ ,ptsourcepos=sourcepos+ ,ptstatus=status+ ,ptcode=code+ ,ptdescription=description+ ,ptcomment=comment+ ,pttags=tags+ ,ptpostings=postings+ }++-- | Parse an assert directive:+--+-- > assert (none|some)[ PERIODEXPR][ QUERY] [; COMMENT]+--+-- A period expression follows the quantifier after one space,+-- and a query follows the quantifier or period expression after two or more spaces.+-- Relative dates in the period expression and the query are relative to the given day (today).+-- The query is parsed to check it, and kept as text.+assertdirectivep :: Monad m => Day -> JournalParser m AssertDirective+assertdirectivep today = do+ pos <- getSourcePos'+ line <- T.takeWhile (/= '\n') <$> getInput+ try (string "assert" <* lift skipNonNewlineSpaces1) <?> "assert directive"+ quantoff <- getOffset+ quantword <- lift $ takeWhileP Nothing (not . isSpace)+ quant <- case quantword of+ "none" -> pure AssertNone+ "some" -> pure AssertSome+ _ -> customFailure $ parseErrorAtRegion quantoff (quantoff + T.length quantword) $+ "assert should be followed by none or some (and the query must match no rows, or some rows)"+ mperiod <- optional $ do+ lift $ try $ singlespacep *> lookAhead (satisfy (\c -> c /= ';' && not (isSpace c)))+ periodExcerpt <- lift $ excerpt_ $ singlespacedtextsatisfying1p (\c -> c /= ';' && c /= '\n')+ lift $ reparseExcerpt periodExcerpt $ do+ pexp <- try (periodexprp today) <|> do+ offset1 <- getOffset+ void takeRest+ offset2 <- getOffset+ customFailure $ parseErrorAtRegion offset1 offset2 $+ "could not parse this as a period expression"+ <> "\none space after none/some begins a period expression;"+ <> "\nthe query must follow two or more spaces"+ (<|>) eof $ do+ offset1 <- getOffset+ void takeRest+ offset2 <- getOffset+ customFailure $ parseErrorAtRegion offset1 offset2 $+ "remainder of period expression cannot be parsed"+ <> "\nperhaps you need to terminate the period expression with a double space?"+ <> "\na double space separates the period expression from the query"+ pure (pexp, T.strip $ getExcerptText periodExcerpt)+ -- What remains is the query, after two or more spaces (or nothing).+ lift skipNonNewlineSpaces+ queryoff <- getOffset+ querytxt <- lift $ T.strip <$> noncommenttextp+ queryend <- getOffset+ let queryerr = customFailure . parseErrorAtRegion queryoff queryend+ either queryerr (const $ pure ()) $ querySplitRowTerms . fst =<< parseQuery today querytxt+ void $ lift followingcommentp+ -- Then any skip subdirectives, on indented lines.+ skips <- many skipsubdirectivep+ case (skips, mperiod) of+ ((off1, off2, _, _):_, m) | maybe True ((== NoInterval) . fst . fst) m ->+ customFailure $ parseErrorAtRegion off1 off2 $+ "skip is only allowed when the assert directive has a period expression with a report interval (like daily or monthly)"+ _ -> pure ()+ return AssertDirective{adQuantifier=quant, adPeriod=fst <$> mperiod, adPeriodText=maybe "" snd mperiod,+ adQueryText=querytxt, adSkips=[sp | (_, _, sp, _) <- skips],+ adSourceText=T.intercalate "\n" $ line : [l | (_, _, _, l) <- skips], adSourcePos=pos}+ where+ -- A skip subdirective: an indented line @skip PERIOD@, with an optional comment,+ -- where PERIOD is a period expression without a report interval.+ -- Returns the PERIOD's start and end offsets, its date span, and the line as written.+ -- Any other indented line (other than a comment line, which followingcommentp consumes) is an error.+ skipsubdirectivep = do+ lift $ try $ skipNonNewlineSpaces1 *> lookAhead (satisfy (not . isSpace))+ line' <- (T.stripStart . T.takeWhile (/= '\n')) <$> getInput+ off0 <- getOffset+ word <- lift $ takeWhileP Nothing (not . isSpace)+ off0' <- getOffset+ when (word /= "skip") $ customFailure $ parseErrorAtRegion off0 off0' $+ "an indented line after an assert directive should be a skip subdirective, like: skip 2026-05"+ lift skipNonNewlineSpaces1+ off1 <- getOffset+ periodtxt <- lift $ singlespacedtextsatisfying1p (\c -> c /= ';' && c /= '\n')+ off2 <- getOffset+ sp <- case parsePeriodExpr today periodtxt of+ Right (NoInterval, sp) -> pure sp+ Right _ -> customFailure $ parseErrorAtRegion off1 off2 "a skip period can't have a report interval"+ Left _ -> customFailure $ parseErrorAtRegion off1 off2 "could not parse this as a period (a date, or a period expression without a report interval)"+ lift skipNonNewlineSpaces+ void $ lift followingcommentp+ pure (off1, off2, sp, line')++-- | Parse one assert directive given as text, such as a check command argument,+-- naming its source in error messages with the given name.+-- Relative dates are relative to the given day (today).+parseAssertDirective :: Day -> String -> Text -> Either String AssertDirective+parseAssertDirective today srcname t =+ first customErrorBundlePretty $+ runParser (evalStateT (assertdirectivep today <* eof) nulljournal) srcname (T.stripEnd t <> "\n")++-- | Parse a (possibly unbalanced) transaction.+transactionp :: JournalParser m Transaction+transactionp = do+ -- dbgparse 0 "transactionp"+ startpos <- getSourcePos'+ date <- datep <?> "transaction"+ mc <- lift peekChar+ edate <- if mc == Just '=' then optional (lift $ secondarydatep date) <?> "secondary date" else pure Nothing+ lookAhead (lift spacenonewline <|> newline) <?> "whitespace or newline"+ status <- lift statusp <?> "cleared status"+ code <- lift codep <?> "transaction code"+ description <- lift $ T.strip <$> descriptionp+ (comment, tags) <- lift transactioncommentp+ let year = first3 $ toGregorian date+ postings <- postingsp (Just year)+ endpos <- getSourcePos'+ let sourcepos = (startpos, endpos)+ return $ txnTieKnot $ transactionRoundCalculatedAmounts $+ Transaction 0 "" sourcepos date edate status code description comment tags postings++--- *** fast path++-- The parser's fast path: cheaper parsing of the commonest kinds of transaction and market+-- price directive. Most of the time spent parsing a large journal goes to megaparsec parsers,+-- which allocate heavily for every token and for every failed attempt at optional syntax.+-- So before running the general transactionp or marketpricedirectivep, the parser first tries+-- a scanner (scanSimpleTransaction, scanSimplePrice) which reads the input Text directly.+-- If the entry has the common simple form, the scanner extracts its parts and the fast path+-- builds the same value the general parser would have built; otherwise the scanner "declines",+-- returning a short reason (as a Left) without consuming anything, and the general parser runs+-- as before. With --debug, the outcomes are counted and reported after parsing (see+-- countFastPath), showing how much of a journal takes the fast path and what keeps the rest+-- off it. On a journal of simple transactions this makes parsing about a third faster, with a+-- third of the allocation (see doc/PERFORMANCE.md).+--+-- The one rule for all of this code: the fast path must produce exactly what the general parser+-- would, or decline. So each scanner below mirrors one general parser (named in its doc comment),+-- copying that parser's rules, and declines on anything it does not fully handle, including+-- anything that would be a parse error (the general parser knows how to report those).+-- Declining is always safe, it just means the general parser does the work; so when in doubt,+-- decline. To extend the fast path to more syntax: find the general parser whose behaviour is+-- to be copied, copy it exactly (including the parse-time sharing of names and styles, see+-- shareText and shareAmountStyle), add a case to hledger/test/journal/fastpath.test, and run+-- the whole functional test suite in check mode (below) to confirm the two parsers still agree.++-- | To disable the fast path entirely, eg while investigating a parsing problem, set this to+-- False: transactions and price directives are then parsed by the general parsers only,+-- exactly as before the fast path existed. (At run time, setting HLEDGER_FASTPATH=off in the+-- environment does the same, without rebuilding; see fastPathMode.)+fastPathEnabled :: Bool+fastPathEnabled = True++-- | How the fast path is used, as set by the HLEDGER_FASTPATH environment variable (for+-- testing): unset or empty means use it; "off" means don't; "check" means use it, and also+-- parse each fast-path entry with the general parser and fail if the results differ.+-- The variable is read once, when first needed (hence unsafePerformIO and NOINLINE),+-- so that consulting this for every entry costs almost nothing.+fastPathMode :: String+fastPathMode = unsafePerformIO $ fromMaybe "" <$> lookupEnv "HLEDGER_FASTPATH"+{-# NOINLINE fastPathMode #-}++-- | Run a fast-path parser (which returns a decline reason, as a Left, when it declines),+-- falling back to the general parser when it declines, or when HLEDGER_FASTPATH says to (see+-- fastPathMode); and count the outcome (see countFastPath).+-- In check mode, after the fast path accepts an entry, the parser state and journal state are+-- rewound and the general parser is run on the same input; the two results are compared after+-- applying the given normalising function (txnUntieKnot for transactions, whose postings refer+-- back to their transaction: comparing or showing such cyclic values would not terminate).+-- If they agree, the fast path's end state is restored (so that the journal keeps its result,+-- and its parse-time sharing sets); otherwise the parse fails with a message showing both.+withFastPath :: (Eq a, Show a) => FastPathKind -> (a -> a) -> JournalParser m (Either Text a) -> JournalParser m a -> JournalParser m a+withFastPath kind norm fastp generalp+ | not fastPathEnabled = generalp+ | otherwise = case fastPathMode of+ "off" -> generalp+ "check" -> do+ st0 <- getParserState+ j0 <- get+ ex <- fastp+ countFastPath kind ex+ case ex of+ Left _ -> generalp+ Right x -> do+ st1 <- getParserState+ j1 <- get+ setParserState st0+ put j0+ x' <- generalp+ when (norm x /= norm x') $+ fail $ "fast path mismatch:\n" ++ show (norm x) ++ "\ngeneral parser:\n" ++ show (norm x')+ setParserState st1+ put j1+ return x+ -- (Without --debug, the outcome is not counted; keep that path free of the extra bind,+ -- whose continuation closures would cost about 2% of parsing.)+ _ | debugLevel > 0 -> do+ ex <- fastp+ countFastPath kind ex+ either (const generalp) pure ex+ | otherwise -> fastp >>= either (const generalp) pure++-- | The kinds of entry the fast path handles, for counting its outcomes.+data FastPathKind = FastPathTransaction | FastPathPrice++-- | Count a fast path outcome (Right: the entry was accepted; Left: it was declined, with+-- the reason) in the journal's fast path statistics, which are reported after parsing+-- (see Hledger.Read.Common.dbgFastPathStats). Called only with --debug.+countFastPath :: FastPathKind -> Either Text a -> JournalParser m ()+countFastPath kind outcome = modify' $ \j -> j{jparsefastpathstats = tally $ jparsefastpathstats j}+ where+ tally s = case (kind, outcome) of+ (FastPathTransaction, Right _) -> s{fpsTxnsFast = fpsTxnsFast s + 1}+ (FastPathPrice, Right _) -> s{fpsPricesFast = fpsPricesFast s + 1}+ (FastPathTransaction, Left r) -> s{fpsTxnsGeneral = fpsTxnsGeneral s + 1, fpsDeclines = M.insertWith (+) r 1 $ fpsDeclines s}+ (FastPathPrice, Left r) -> s{fpsPricesGeneral = fpsPricesGeneral s + 1, fpsDeclines = M.insertWith (+) r 1 $ fpsDeclines s}++-- | Parse a transaction, using the fast path when it is a simple one (see fasttransactionp).+transactionOrFastp :: JournalParser m Transaction+transactionOrFastp = withFastPath FastPathTransaction txnUntieKnot fasttransactionp transactionp++-- | Parse a market price directive, using the fast path when it is a simple one (see fastmarketpricedirectivep).+marketpriceOrFastp :: JournalParser m PriceDirective+marketpriceOrFastp = withFastPath FastPathPrice id fastmarketpricedirectivep marketpricedirectivep++-- | The scanners below run in Either Text: a Left is a decline, carrying a short reason+-- (the same wording each time, since --debug counts the declines by reason).+-- This declines with the given reason if the condition holds.+declineIf :: Bool -> Text -> Either Text ()+declineIf cond reason = when cond $ Left reason+{-# INLINE declineIf #-}++-- | Convert a Maybe-returning scanner's result to a decline with the given reason, or a success.+orDecline :: Text -> Maybe a -> Either Text a+orDecline reason = maybe (Left reason) Right+{-# INLINE orDecline #-}++-- | A following comment's text as followingcommentpWith builds it, from the same-line comment's+-- text (after the semicolon) if there was one, and any following comment lines' texts: each+-- stripped and newline-terminated, with an empty first line when there was no same-line comment+-- but there are following lines (so that the comment is not rendered as a same-line one).+commentText :: Maybe Text -> [Text] -> Text+commentText msameline nextlines = case (msameline, nextlines) of+ (Nothing, []) -> ""+ _ -> T.unlines $ map T.strip $ fromMaybe "" msameline : nextlines++-- | The tags in a transaction comment line's text (after the semicolon), as commentlinetagsp+-- parses them: a colon ends a tag name, which is the last whitespace-separated word before it+-- (if there is none, the colon is just skipped); the tag's value is the whitespace-stripped text+-- up to the next comma or the end of the line; and so on along the line.+scanTransactionTags :: Text -> [Tag]+scanTransactionTags t =+ let (before, rest) = T.break (== ':') t+ name = T.takeWhileEnd (not . isSpace) before+ in case T.stripPrefix ":" rest of+ Nothing -> []+ Just aftercolon+ | T.null name -> scanTransactionTags aftercolon+ | otherwise ->+ let (valtext, rest2) = T.break (== ',') $ T.dropWhile isNonNewlineSpace aftercolon+ in (name, T.strip valtext) : scanTransactionTags (dropComma rest2)++-- | The tags, and the posting dates from date: and date2: tags, in a posting comment line's+-- text, as commenttagsanddatesp parses them, given the transaction's year for partial dates.+-- Like scanTransactionTags, except that after a colon with no tag name, spaces and a comma are+-- skipped, and a non-empty date tag value must begin with a date, which is returned as well.+-- Returns Nothing if a date tag's value does not begin with a date scanSimpleDate handles (the+-- general parser accepts a few more forms, and reports invalid ones). The text must not contain+-- a bracketed date (callers decline those).+scanPostingTags :: Year -> Text -> Maybe ([Tag], [(TagName, Day)])+scanPostingTags year t =+ let (before, rest) = T.break (== ':') t+ name = T.takeWhileEnd (not . isSpace) before+ in case T.stripPrefix ":" rest of+ Nothing -> Just ([], [])+ Just aftercolon -> do+ let r = T.dropWhile isNonNewlineSpace aftercolon+ (valtext, rest2) = T.break (== ',') r+ val = T.strip valtext+ (tags, dates, rest3) <-+ if T.null name then Just ([], [], r)+ else if (name == "date" || name == "date2") && not (T.null val) then do+ (date, _) <- scanSimpleDate (Just year) r+ Just ([(name, val)], [(name, date)], rest2)+ else Just ([(name, val)], [], rest2)+ (moretags, moredates) <- scanPostingTags year (dropComma rest3)+ Just (tags ++ moretags, dates ++ moredates)++-- | Drop a leading comma, if any (like optional (char ',')).+dropComma :: Text -> Text+dropComma t = fromMaybe t $ T.stripPrefix "," t++-- | The parts of a simple transaction recognised by scanSimpleTransaction.+data SimpleTransaction = SimpleTransaction {+ stDate :: !Day+ ,stDate2 :: !(Maybe Day)+ ,stStatus :: !Status+ ,stCode :: !Text+ ,stDescription :: !Text+ ,stComment :: !Text+ ,stTags :: ![Tag]+ ,stPostings :: ![SimplePosting]+ }++-- | The parts of a simple posting recognised by scanSimplePosting.+data SimplePosting = SimplePosting {+ spStatus :: !Status+ ,spAccount :: !AccountName -- ^ with aliases and the parent account applied, and brackets removed+ ,spRealness :: !PostingRealness+ ,spAmount :: !(Maybe Amount)+ ,spAssertion :: !(Maybe SimpleAssertion)+ ,spComment :: !Text+ ,spTags :: ![Tag]+ ,spDate :: !(Maybe Day) -- ^ from a date: tag, if any+ ,spDate2 :: !(Maybe Day) -- ^ from a date2: tag, if any+ }++-- | The parts of a balance assertion or assignment recognised by scanSimpleAssertion.+-- Its position is relative to the transaction, since the scanners don't know where that is+-- in the file; fasttransactionp makes it absolute.+data SimpleAssertion = SimpleAssertion {+ saAmount :: !Amount+ ,saTotal :: !Bool+ ,saInclusive :: !Bool+ ,saLineOffset :: !Int -- ^ how many lines after the transaction's first line+ ,saColumn :: !Int -- ^ the column of the first = (1-based)+ }++-- | A fast path for the commonest kind of transaction: if the input begins with one, parse+-- it, consuming its lines; otherwise consume nothing and return the reason for declining, so+-- that the general transactionp can be used. This produces exactly what transactionp would,+-- but much more cheaply, by scanning the text directly instead of running megaparsec parsers+-- (which allocate heavily per token). A simple transaction has:+--+-- - a date (YYYY-MM-DD, or with / or . separators; or MM-DD, using the default year), an+-- optional secondary date, an optional * or ! status mark, an optional (code), a description,+-- and optionally a comment (same-line and/or on following indented lines), possibly with tags;+-- - zero or more postings, each an indented line with an optional status mark, an account name+-- (possibly in parens or brackets), optionally an amount, and optionally a comment (as above),+-- possibly with tags including date tags, but with no bracketed dates; optionally a balance+-- assertion or assignment (with no tab before it on the line); no lot annotation;+-- - amounts whose number is digits, with or without digit group marks, a decimal mark and decimal+-- digits (as rawnumberp accepts; but no exponent), with an optional sign, an optional+-- commodity symbol on either side, and an optional @ or @@ cost of the same form;+-- and when there is no symbol, no default commodity directive in effect;+-- - no CR characters.+--+-- Anything else declines, including anything that would be a parse error, so that the general+-- parser reports it. Numbers are interpreted by the same code as the general parser+-- (interpretRawNumber), so declared commodity styles and decimal marks work.+fasttransactionp :: JournalParser m (Either Text Transaction)+fasttransactionp = do+ j <- get+ s <- getInput+ case scanSimpleTransaction j s of+ Left reason -> return $ Left reason+ Right (stxn, consumed) -> do+ startpos <- getSourcePos'+ -- share the account names, symbols and styles with identical earlier ones, as postingp does+ ps <- mapM (internPosting startpos) $ stPostings stxn+ -- consume the scanned text; megaparsec computes source positions from the offset on demand,+ -- so updating the input and the offset is all that is needed+ updateParserState $ \st -> st{stateInput = T.drop consumed s, stateOffset = stateOffset st + consumed}+ endpos <- getSourcePos'+ -- the same value transactionp builds; the index and preceding comment are filled in+ -- later, as for any transaction+ return $ Right $ txnTieKnot $ Transaction 0 "" (startpos, endpos) (stDate stxn) (stDate2 stxn) (stStatus stxn) (stCode stxn)+ (stDescription stxn) (stComment stxn) (stTags stxn) ps+ where+ internPosting startpos sp = do+ acct' <- shareText $ spAccount sp+ mamt' <- traverse internSimpleAmount $ spAmount sp+ massertion <- traverse (internAssertion startpos) $ spAssertion sp+ return posting{pdate=spDate sp, pdate2=spDate2 sp, pstatus=spStatus sp, paccount=acct'+ ,pamount=maybe missingmixedamt mixedAmount mamt', pcomment=spComment sp, preal=spRealness sp, ptags=spTags sp+ ,pbalanceassertion=massertion}+ internAssertion (SourcePos f l _) SimpleAssertion{saAmount, saTotal, saInclusive, saLineOffset, saColumn} = do+ a <- internSimpleAmount saAmount+ let !pos = SourcePos f (mkPos $ unPos l + saLineOffset) (mkPos saColumn)+ return BalanceAssertion{baamount=a, batotal=saTotal, bainclusive=saInclusive, baposition=pos}++-- | Share a scanned amount's commodity symbol and style (and its cost amount's) with identical+-- ones parsed earlier, as simpleamountp does, so that equal values point to one heap object.+-- (The scanners are pure functions; this sharing, which updates the journal's parse state,+-- is done afterwards, here.)+internSimpleAmount :: Amount -> JournalParser m Amount+internSimpleAmount a = do+ c <- if T.null (acommodity a) then return "" else shareText (acommodity a)+ s <- shareAmountStyle (astyle a)+ mcost <- traverse internCost (acost a)+ return a{acommodity=c, astyle=s, acost=mcost}+ where+ internCost (UnitCost ca) = UnitCost <$> internSimpleAmount ca+ internCost (TotalCost ca) = TotalCost <$> internSimpleAmount ca++-- | A fast path for the commonest kind of market price directive, like fasttransactionp:+-- P, a date, an optional time of day (ignored), a commodity symbol, and a simple+-- amount (as described there), separated by spaces, then optionally other text, which is+-- ignored (as marketpricedirectivep does). Declines otherwise.+fastmarketpricedirectivep :: JournalParser m (Either Text PriceDirective)+fastmarketpricedirectivep = do+ j <- get+ s <- getInput+ case scanSimplePrice j s of+ Left reason -> return $ Left reason+ Right (date, sym, amt, consumed) -> do+ pos <- getSourcePos'+ sym' <- shareText sym+ amt' <- internSimpleAmount amt+ -- consume the scanned text, as in fasttransactionp+ updateParserState $ \st -> st{stateInput = T.drop consumed s, stateOffset = stateOffset st + consumed}+ return $ Right $ PriceDirective pos date sym' amt'++-- | Recognise a simple market price directive (see fastmarketpricedirectivep) at the start of+-- the text, returning its date, commodity symbol and price amount, and the number of characters+-- consumed (through the line's newline). Mirrors marketpricedirectivep: P, optional spaces, a+-- date, at least one space, optionally a time of day and at least one space, the commodity+-- symbol, at least one space, the amount; and then the rest of the line is ignored, whatever it+-- is (as restofline does there). Declines if a cost or lot annotation follows the amount.+scanSimplePrice :: Journal -> Text -> Either Text (Day, CommoditySymbol, Amount, Int)+scanSimplePrice j s = do+ (line, _, n) <- orDecline "CR line ending" $ scanSimpleLine s -- (the text is not empty: it begins with P)+ r0 <- orDecline "malformed price directive" $ T.stripPrefix "P" line+ (date, r1) <- orDecline "unusual date form" $ scanSimpleDate (jparsedefaultyear j) $ T.dropWhile isNonNewlineSpace r0+ declineIf (not $ startsWithSpace r1) "malformed price directive"+ -- a digit here begins a time of day, which is ignored; then at least one space+ r2 <- case T.uncons (T.dropWhile isNonNewlineSpace r1) of+ Just (c, _) | isDigit c -> do+ r <- orDecline "unusual time of day in price directive" $ scanTimeOfDay $ T.dropWhile isNonNewlineSpace r1+ declineIf (not $ startsWithSpace r) "malformed price directive"+ Right $ T.dropWhile isNonNewlineSpace r+ _ -> Right $ T.dropWhile isNonNewlineSpace r1+ (sym, r3) <- orDecline "malformed price directive" $ scanCommoditySymbol r2+ declineIf (not $ startsWithSpace r3) "malformed price directive"+ (amt, r4) <- scanSimpleAmount j $ T.dropWhile isNonNewlineSpace r3+ -- a cost or lot annotation on the price: decline; anything else is ignored+ declineIf (maybe False (\(c', _) -> c' `elem` ("@({[" :: String)) $ T.uncons $ T.dropWhile isNonNewlineSpace r4) "annotation on the price amount"+ Right (date, sym, amt, n)++-- | Recognise a simple transaction (see fasttransactionp) at the start of the text, returning+-- its parts and the number of characters consumed (through the newline of its last line).+-- The first line is scanned as transactionp parses it: a date, an optional secondary date,+-- then whitespace or the end of the line, an optional status mark, an optional code, the+-- description (whitespace-stripped), and an optional comment; then any following indented+-- comment lines continue the comment (as transactioncommentp parses them). Then, as postingsp+-- does, each following indented line is taken as a posting (with its own following comment+-- lines), until a line that is not indented, or the end of the text. Since a decline must+-- consume nothing, one posting the scanner does not handle declines the whole transaction.+scanSimpleTransaction :: Journal -> Text -> Either Text (SimpleTransaction, Int)+scanSimpleTransaction j s0 = do+ (line1, s1, n1) <- orDecline "CR line ending" $ scanSimpleLine s0 -- (the text is not empty: it begins with a digit)+ (date, r1) <- orDecline "unusual date form" $ scanSimpleDate (jparsedefaultyear j) line1+ -- an optional secondary date, as secondarydatep parses it: = and a date, partial ones+ -- taking the primary date's year+ (mdate2, r2) <- case T.uncons r1 of+ Just ('=', r) -> do+ (date2, r') <- orDecline "unusual secondary date form" $ scanSimpleDate (Just $ first3 $ toGregorian date) r+ Right (Just date2, r')+ _ -> Right (Nothing, r1)+ -- then whitespace or the end of the line, as transactionp requires (anything else is an error)+ r3 <- case T.uncons r2 of+ Nothing -> Right r2+ Just (c, _) | isNonNewlineSpace c -> Right $ T.dropWhile isNonNewlineSpace r2+ _ -> Left "unexpected text after the date"+ let (status, r4) = case T.uncons r3 of+ Just ('*', r) -> (Cleared, r)+ Just ('!', r) -> (Pending, r)+ _ -> (Unmarked, r3)+ r5 = T.dropWhile isNonNewlineSpace r4+ -- codep requires at least one space before the code's ( : after the status mark if+ -- there is one, otherwise the whitespace after the date will do+ spacedbeforecode = status == Unmarked || startsWithSpace r4+ -- an optional code in parentheses, as codep parses it+ (code, r6) <- case T.uncons r5 of+ Just ('(', r) | spacedbeforecode -> do+ let (c, r') = T.break (== ')') r+ r'' <- orDecline "unclosed transaction code" $ T.stripPrefix ")" r'+ Right (c, r'')+ _ -> Right ("", r5)+ -- the description ends at a semicolon, which begins a same-line comment; following indented+ -- comment lines continue the comment (transactioncommentp); a tag in any of it: decline+ let (desc, r7) = T.break (== ';') r6+ msameline = T.stripPrefix ";" r7+ !(commentlines, s2, n2) = scanCommentLines s1+ year = first3 $ toGregorian date -- the default year for partial dates in the postings' date tags+ (sps, n) <- scanPostings year (1 + length commentlines) s2 (n1 + n2) []+ Right (SimpleTransaction{stDate=date, stDate2=mdate2, stStatus=status, stCode=code, stDescription=T.strip desc+ ,stComment=commentText msameline commentlines+ ,stTags=concatMap scanTransactionTags $ maybeToList msameline ++ commentlines+ ,stPostings=sps}, n)+ where+ modifyacct = accountNameApplyModifiers (jparsealiases j) (concatAccountNames $ reverse $ jparseparentaccounts j) (jparseoptaliases j)+ scanPostings year !lineoffset s !n acc = case scanSimpleLine s of+ Just (line, s', k)+ | isIndented line -> do+ -- a posting line, and any following indented comment lines (its comment's continuation)+ let !(commentlines, s'', k') = scanCommentLines s'+ p <- scanSimplePosting j year lineoffset modifyacct line commentlines+ scanPostings year (lineoffset + 1 + length commentlines) s'' (n + k + k') (p : acc)+ | otherwise -> Right (reverse acc, n)+ -- the end of the text, or a line with a CR: in an indented (posting) line that declines,+ -- since the general parser would accept the posting; any other line just ends the postings+ Nothing+ | isIndented (T.takeWhile (/= '\n') s) -> Left "CR line ending"+ | otherwise -> Right (reverse acc, n)+ -- does the line begin with whitespace followed by something ? (like postingsp's nextlineisindented)+ isIndented line = case T.uncons line of+ Just (c, _) -> isNonNewlineSpace c && not (T.null $ T.dropWhile isNonNewlineSpace line)+ Nothing -> False++-- | The next line of the text (without its newline), the text after it, and the number of+-- characters consumed (including the newline, if there was one); or Nothing if the text is+-- empty, or if the line contains a CR. (The general parser treats CR as whitespace; rather than+-- mirror that in every scanner, files with CRLF line endings are left to it.)+scanSimpleLine :: Text -> Maybe (Text, Text, Int)+scanSimpleLine s+ | T.null s = Nothing+ | otherwise =+ let (line, rest) = T.break (== '\n') s+ !rest' = T.drop 1 rest+ !n = T.length line + (if T.null rest then 0 else 1)+ in if T.any (== '\r') line+ then Nothing+ else Just (line, rest', n)++-- | Consume any following comment lines (indented lines beginning with a semicolon, as+-- followingcommentpWith recognises them), returning their texts after the semicolon, the text+-- after them, and the number of characters consumed. (The next line is usually a posting,+-- so it is checked before being split off.)+scanCommentLines :: Text -> ([Text], Text, Int)+scanCommentLines = go [] 0+ where+ go acc !n s+ | startsWithSpace s, Just r <- T.stripPrefix ";" (T.dropWhile isNonNewlineSpace s)+ , Just (_, s', k) <- scanSimpleLine s+ = go (T.takeWhile (/= '\n') r : acc) (n + k) s'+ | otherwise = (reverse acc, s, n)++-- | A date as datep parses it, given the default year, and the text after it. A full date has a+-- four-digit year (datep also allows longer ones; those decline), a - / or . separator, a one-+-- or two-digit month, the same separator again, and a one- or two-digit day. A partial date has+-- just a one- or two-digit month, a separator and a one- or two-digit day, and takes the default+-- year. Declines if the date has another shape, is not a valid calendar date (datep reports an+-- error for that), or is partial when there is no default year (likewise).+scanSimpleDate :: Maybe Year -> Text -> Maybe (Day, Text)+scanSimpleDate mdefaultyear t = do+ let (n1, r1) = T.span isDigit t+ (sep, r2) <- T.uncons r1+ guard $ sep == '-' || sep == '/' || sep == '.'+ let (n2, r3) = T.span isDigit r2+ guard $ T.length n2 == 1 || T.length n2 == 2+ if T.length n1 == 4+ then do -- a full date: year, month, day+ (sep2, r4) <- T.uncons r3+ guard $ sep2 == sep+ let (n3, r5) = T.span isDigit r4+ guard $ T.length n3 == 1 || T.length n3 == 2+ date <- fromGregorianValid (readDecimal n1) (fromInteger $ readDecimal n2) (fromInteger $ readDecimal n3)+ Just (date, r5)+ else do -- a partial date: month, day, in the default year+ guard $ T.length n1 == 1 || T.length n1 == 2+ y <- mdefaultyear+ date <- fromGregorianValid y (fromInteger $ readDecimal n1) (fromInteger $ readDecimal n2)+ Just (date, r3)++-- | Skip a time of day as timeofdayp parses it (two-digit hour and minute, optionally a+-- two-digit second, optionally a +HHMM or -HHMM time zone), returning the text after it;+-- or Nothing if the text does not begin with a valid one.+scanTimeOfDay :: Text -> Maybe Text+scanTimeOfDay t0 = do+ (h, r1) <- twoDigits t0+ guard $ h <= 23+ r2 <- T.stripPrefix ":" r1+ (m, r3) <- twoDigits r2+ guard $ m <= 59+ r4 <- case T.stripPrefix ":" r3 of+ Just r -> do (sec, r') <- twoDigits r; guard (sec <= 59); Just r'+ Nothing -> Just r3+ Just $ fromMaybe r4 $ do -- an optional time zone+ (c, r5) <- T.uncons r4+ guard $ c == '+' || c == '-'+ let (ds, r6) = T.span isDigit r5+ guard $ T.length ds == 4+ Just r6+ where+ twoDigits t = let (ds, r) = T.span isDigit t in if T.length ds == 2 then Just (readDecimal ds, r) else Nothing++-- | Does the text begin with a non-newline space ?+startsWithSpace :: Text -> Bool+startsWithSpace = maybe False (isNonNewlineSpace . fst) . T.uncons++-- | A simple posting line (see fasttransactionp), scanned as postingp parses it: indentation,+-- an optional status mark, the account name, optionally an amount with cost, optionally a balance+-- assertion or assignment, and optionally a same-line comment; and given the line's position within+-- the transaction, and the texts of its following comment lines (see scanCommentLines).+-- Returns the status, the account name (with aliases and the parent account applied by the+-- given function, as modifiedaccountnamep does, and virtual posting brackets removed, as postingp does), the+-- posting type, the amount and balance assertion if any, the comment text, and the comment's tags and posting dates+-- (the transaction's year is given for partial dates in those). Declines on a bracketed date+-- in the comment (which postingcommentp would interpret), a date tag whose value is not a+-- simple date, a balance assertion it does not handle, or anything else after the amount.+scanSimplePosting :: Journal -> Year -> Int -> (AccountName -> Either RegexError AccountName) -> Text -> [Text] -> Either Text SimplePosting+scanSimplePosting j year lineoffset modifyacct line commentlines = do+ -- an optional status mark, as statusp parses it, then spaces+ let (status, body) = case T.uncons $ T.dropWhile isNonNewlineSpace line of+ Just ('*', r) -> (Cleared, T.dropWhile isNonNewlineSpace r)+ Just ('!', r) -> (Pending, T.dropWhile isNonNewlineSpace r)+ Just _ -> (Unmarked, T.dropWhile isNonNewlineSpace line)+ Nothing -> (Unmarked, "")+ let (name, r1) = scanSimpleAccountName body+ r2 = T.dropWhile isNonNewlineSpace r1+ -- a status mark and nothing else is an error (accountnamep needs at least one character)+ declineIf (T.null name) "malformed posting"+ -- an empty account name part is an error, reported by accountnamep+ declineIf (accountNameHasEmptyPart name) "account name with an empty part"+ (mamt, r3) <-+ -- no amount (a following = begins a balance assignment)+ if T.null r2 || T.isPrefixOf ";" r2 || T.isPrefixOf "=" r2+ then Right (Nothing, r2)+ else do (a, r) <- scanSimpleAmountAndCost j r2; Right (Just a, r)+ -- then an optional balance assertion or assignment+ let r4 = T.dropWhile isNonNewlineSpace r3+ (massertion, r5) <-+ if T.isPrefixOf "=" r4+ then do (a, r) <- scanSimpleAssertion j lineoffset line r4; Right (Just a, r)+ else Right (Nothing, r4)+ -- then an optional same-line comment; anything else is an error+ msameline <- case T.uncons r5 of+ Nothing -> Right Nothing+ Just (';', r) -> Right (Just r)+ _ -> Left "unexpected text after the amount"+ -- the comment's tags and posting dates, as postingcommentp parses them; a bracketed date+ -- (which it would also interpret) declines, as does a date tag with an unusual value+ let comments = maybeToList msameline ++ commentlines+ declineIf (any (T.any (== '[')) comments) "posting comment with bracketed date"+ tagsanddates <- orDecline "unusual date tag value" $ mapM (scanPostingTags year) comments+ let dates = concatMap snd tagsanddates+ -- as modifiedaccountnamep and postingp do (an alias error declines, to be reported there)+ full <- either (const $ Left "account alias error") Right $ modifyacct name+ Right SimplePosting{spStatus=status, spAccount=textUnbracket full, spRealness=accountNamePostingType full, spAmount=mamt, spAssertion=massertion+ ,spComment=commentText msameline commentlines, spTags=concatMap fst tagsanddates+ ,spDate=lookup "date" dates, spDate2=lookup "date2" dates}++-- | A balance assertion or assignment as balanceassertionp parses it, and the text after it,+-- given the posting's line offset within the transaction, the whole line, and the part of the+-- line beginning with the first =. That is =, ==, =* or ==*, optional spaces, and an amount with+-- an optional cost. Declines if a tab precedes the = on the line, rather than copy megaparsec's+-- tab stop rule for calculating its column; and on anything scanSimpleAmountAndCost declines.+scanSimpleAssertion :: Journal -> Int -> Text -> Text -> Either Text (SimpleAssertion, Text)+scanSimpleAssertion j lineoffset line t = do+ let before = T.length line - T.length t+ declineIf (T.any (== '\t') $ T.take before line) "balance assertion after a tab"+ let r1 = T.drop 1 t+ (istotal, r2) = maybe (False, r1) (True,) $ T.stripPrefix "=" r1+ (isinclusive, r3) = maybe (False, r2) (True,) $ T.stripPrefix "*" r2+ (a, r4) <- scanSimpleAmountAndCost j $ T.dropWhile isNonNewlineSpace r3+ Right (SimpleAssertion{saAmount=a, saTotal=istotal, saInclusive=isinclusive, saLineOffset=lineoffset, saColumn=before + 1}, r4)++-- | An account name as accountnamep parses it, and the text after it: one or more+-- non-whitespace parts, separated by single spaces (a single tab also separates parts, and+-- becomes a space; two or more whitespace characters end the name, as does a newline).+scanSimpleAccountName :: Text -> (Text, Text)+scanSimpleAccountName t = go [part1] r1+ where+ (part1, r1) = T.span (not . isSpace) t+ go parts r = case T.uncons r of+ Just (c1, r') | isNonNewlineSpace c1, Just (c2, _) <- T.uncons r', not (isSpace c2) ->+ let (part, r'') = T.span (not . isSpace) r' in go (part : parts) r''+ _ -> (T.unwords (reverse parts), r)++-- | An amount with an optional @ or @@ cost, as amountp' parses simple ones, and the text after+-- it. A total cost's sign follows the amount's, as in costp. Declines on a second cost, a+-- parenthesised cost, a valuation expression or a lot annotation (anything beginning with+-- @ ( { or [ after the amount or the cost).+scanSimpleAmountAndCost :: Journal -> Text -> Either Text (Amount, Text)+scanSimpleAmountAndCost j t = do+ (a, r1) <- scanSimpleAmount j t+ let r2 = T.dropWhile isNonNewlineSpace r1+ case T.uncons r2 of+ Just ('@', r3) -> do+ let (total, r4) = case T.uncons r3 of+ Just ('@', r) -> (True, r)+ _ -> (False, r3)+ (ca, r5) <- scanSimpleAmount j $ T.dropWhile isNonNewlineSpace r4+ let r6 = T.dropWhile isNonNewlineSpace r5+ -- another cost, or a lot annotation: decline+ declineIf (maybe False (\(c, _) -> c `elem` ("@({[" :: String)) $ T.uncons r6) "annotation after the cost"+ let amtsign = case signum (aquantity a) of 0 -> 1; sgn -> sgn+ cost | total = TotalCost ca{aquantity = amtsign * aquantity ca}+ | otherwise = UnitCost ca+ Right (a{acost = Just cost}, r6)+ Just (c, _) | c `elem` ("({[" :: String) -> Left "lot or valuation annotation"+ _ -> Right (a, r2)++-- | An amount without cost, as simpleamountp parses simple ones, and the text after it: an+-- optional sign, then either a commodity symbol, optional spaces, an optional second+-- sign and a number; or a number, optional spaces and an optional symbol. The number+-- is interpreted by interpretRawNumber with the same suggested style and required decimal mark+-- that simpleamountp would use, so decimal-mark and commodity directives have their usual effect,+-- and the amount's style is built as there. Declines on an exponent, and+-- on a symbol-less amount when a default commodity (D) directive is in effect (simpleamountp+-- would apply that commodity and its style).+scanSimpleAmount :: Journal -> Text -> Either Text (Amount, Text)+scanSimpleAmount j t0 = do+ let (sign1, t1) = scanSign t0+ (c, _) <- orDecline malformed $ T.uncons t1+ -- in a posting, (... is an amount expression, which postingamountp evaluates+ declineIf (c == '(') "possible amount expression"+ if c == '"' || not (isNonsimpleCommodityChar c)+ then do -- symbol on the left+ (sym, t2) <- orDecline malformed $ scanCommoditySymbol t1+ let (spaced, t3) = scanSpaces t2+ (sign2, t4) = scanSign t3+ (raw, t5) <- orDecline malformed $ scanSimpleNumber t4+ (q, p, mdec, mgrps) <- interpret (suggestedStyle sym) raw+ Right (nullamt{acommodity=sym, aquantity=sign1 (sign2 q), acost=Nothing+ ,astyle=amountstyle{ascommodityside=L, ascommodityspaced=spaced, asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}+ ,t5)+ else do+ (raw, t2) <- orDecline malformed $ scanSimpleNumber t1+ let (spaced, t3) = scanSpaces t2+ case T.uncons t3 of+ -- in a posting, 10 /2 is a division, which postingamountp evaluates+ Just (c2, _) | c2 == '/' -> Left "possible amount expression"+ | c2 == '"' || not (isNonsimpleCommodityChar c2) -> do -- symbol on the right+ (sym, t4) <- orDecline malformed $ scanCommoditySymbol t3+ (q, p, mdec, mgrps) <- interpret (suggestedStyle sym) raw+ Right (nullamt{acommodity=sym, aquantity=sign1 q, acost=Nothing+ ,astyle=amountstyle{ascommodityside=R, ascommodityspaced=spaced, asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}+ ,t4)+ _ -> do -- no symbol (and no default commodity directive, which would apply: decline)+ declineIf (isJust $ jparsedefaultcommodity j) "default commodity directive in effect"+ (q, p, mdec, mgrps) <- interpret (suggestedStyle "") raw+ Right (nullamt{acommodity="", aquantity=sign1 q, acost=Nothing+ ,astyle=amountstyle{asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}+ ,t2)+ where+ -- a number scanSimpleNumber does not handle, or text which is not an amount at all (an error, usually)+ malformed = "malformed amount, or number with an exponent"+ suggestedStyle sym = journalDecimalMarkStyle j <|> journalAmountStyleFor j sym+ interpret msuggested raw = either (const $ Left "invalid number") Right $ interpretRawNumber (jparsedecimalmark j) msuggested raw Nothing++-- | A commodity symbol as commoditysymbolp parses it, and the text after it: a double-quoted symbol+-- (returned without the quotes, and which may be empty, but can't contain a semicolon or newline),+-- or one or more simple commodity symbol characters. Or Nothing, if neither of those is here.+scanCommoditySymbol :: Text -> Maybe (CommoditySymbol, Text)+scanCommoditySymbol t = case T.uncons t of+ Just ('"', r) -> do+ let (sym, r') = T.span (\c -> c /= ';' && c /= '\n' && c /= '"') r+ (sym,) <$> T.stripPrefix "\"" r'+ _ -> case T.span (not . isNonsimpleCommodityChar) t of+ (sym, r) | T.null sym -> Nothing+ | otherwise -> Just (sym, r)++-- | An optional sign, as signp parses it (a - or +, then optional spaces), as a function to+-- apply to the quantity; and the text after it.+scanSign :: Text -> (Quantity -> Quantity, Text)+scanSign t = case T.uncons t of+ Just ('-', r) -> (negate, T.dropWhile isNonNewlineSpace r)+ Just ('+', r) -> (id, T.dropWhile isNonNewlineSpace r)+ _ -> (id, t)++-- | Skip any spaces, also saying whether there were any (like skipNonNewlineSpaces', which+-- simpleamountp uses to record whether the commodity symbol was separated from the number).+scanSpaces :: Text -> (Bool, Text)+scanSpaces t = (maybe False (isNonNewlineSpace . fst) $ T.uncons t, T.dropWhile isNonNewlineSpace t)++-- | A number, classified as rawnumberp would, and the text after it: digits, possibly in groups+-- separated by one repeated digit group mark (which can be a space), possibly with a decimal+-- mark and decimal digits, or with just a leading or trailing decimal mark. The classification+-- records the marks and digit groups seen (each group as its digit count and value, as+-- digitgroupp does); interpretRawNumber turns that into a quantity, precision and style.+-- As in rawnumberp, a number with a single mark between digits is ambiguous, since the mark+-- could be a decimal mark or a digit group mark; that is left for interpretRawNumber to decide,+-- from the suggested style (with none, a single mark is a decimal mark). Eg:+--+-- > 1234 Right (NoSeparators 1234 Nothing)+-- > .56 Right (NoSeparators mempty (Just ('.', 56)))+-- > 1234. Right (NoSeparators 1234 (Just ('.', mempty)))+-- > 1234.56 Left (AmbiguousNumber 1234 '.' 56)+-- > 1,234,567 Right (WithSeparators ',' [1,234,567] Nothing)+-- > 1,234.56 Right (WithSeparators ',' [1,234] (Just ('.', 56)))+-- > 1 234,56 Right (WithSeparators ' ' [1,234] (Just (',', 56)))+--+-- Declines when the number is followed by an exponent (which rawnumberp allows; rarely used),+-- or by another decimal mark, or by a space and a digit (errors, which rawnumberp reports).+scanSimpleNumber :: Text -> Maybe (Either AmbiguousNumber RawNumber, Text)+scanSimpleNumber t0 = do+ (raw, r) <- case T.uncons t0 of+ -- a leading decimal mark, then digits: .5+ Just (c, t1) | isDecimalMark c -> do+ (grp, r) <- digits t1+ Just (Right $ NoSeparators mempty (Just (c, grp)), r)+ _ -> do+ (grp1, r1) <- digits t0+ case T.uncons r1 of+ -- a digit group mark (which might be a decimal mark), then a digit: more digit groups+ Just (sep, r2) | isDigitSeparatorChar sep, maybe False (isDigit . fst) (T.uncons r2) -> do+ (grp2, r3) <- digits r2+ let (grps, r4) = moreGroups sep r3+ case T.uncons r4 of+ -- then a decimal mark (not the digit group mark), and maybe decimal digits+ Just (dm, r5) | isDecimalMark dm, dm /= sep ->+ let (dgrp, r6) = fromMaybe (mempty, r5) $ digits r5+ in Just (Right $ WithSeparators sep (grp1 : grp2 : grps) (Just (dm, dgrp)), r6)+ _ | null grps && isDecimalMark sep -> Just (Left $ AmbiguousNumber grp1 sep grp2, r4)+ | otherwise -> Just (Right $ WithSeparators sep (grp1 : grp2 : grps) Nothing, r4)+ -- a trailing decimal mark: 1.+ Just (dm, r2) | isDecimalMark dm -> Just (Right $ NoSeparators grp1 (Just (dm, mempty)), r2)+ _ -> Just (Right $ NoSeparators grp1 Nothing, r1)+ guard $ numberEnds r+ Just (raw, r)+ where+ digits t = let (ds, r) = T.span isDigit t in if T.null ds then Nothing else Just (digitGroup ds, r)+ moreGroups sep t = case T.uncons t of+ Just (c, t') | c == sep, Just (g, t'') <- digits t' -> let (gs, r) = moreGroups sep t'' in (g : gs, r)+ _ -> ([], t)+ digitGroup ds = DigitGrp (fromIntegral $ T.length ds) (readDecimal ds)+ -- the number must not be followed by another decimal mark, an exponent, or a digit group+ -- mark (which can be a space) and a digit; those are errors, or more complex numbers+ numberEnds r = case T.uncons r of+ Just (c, r') | isDecimalMark c -> False+ | c == 'e' || c == 'E' -> False+ | isDigitSeparatorChar c, Just (d, _) <- T.uncons r', isDigit d -> False+ _ -> True++--- *** postings++-- Parse the following whitespace-beginning lines as postings, posting+-- tags, and/or comments (inferring year, if needed, from the given date).+postingsp :: Maybe Year -> JournalParser m [Posting]+postingsp mTransactionYear = manyWhile nextlineisindented (postingp mTransactionYear) <?> "postings"+ where+ -- does the next line begin with whitespace followed by something ? (a cheap check before trying to parse a posting)+ nextlineisindented = do+ (spaced, mc) <- lift peekAfterSpaces+ pure $ spaced && maybe False (not . isNewline) mc++-- linebeginningwithspaces :: JournalParser m String+-- linebeginningwithspaces = do+-- sp <- lift skipNonNewlineSpaces1+-- c <- nonspace+-- cs <- lift restofline+-- return $ sp ++ (c:cs) ++ "\n"++postingp :: Maybe Year -> JournalParser m Posting+postingp = fmap fst . postingphelper False++-- Parse the following whitespace-beginning lines as transaction posting rules, posting+-- tags, and/or comments (inferring year, if needed, from the given date).+tmpostingrulesp :: Maybe Year -> JournalParser m [TMPostingRule]+tmpostingrulesp mTransactionYear = many (tmpostingrulep mTransactionYear) <?> "posting rules"++-- Amounts calculated with * or / are rounded to their own precision, as in periodic transactions (#2648).+tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule+tmpostingrulep = fmap (uncurry TMPostingRule . first (fst . postingRoundCalculatedAmounts mempty)) . postingphelper True++-- Parse a Posting, and return a flag with whether a multiplier has been detected.+-- The multiplier is used in TMPostingRules.+postingphelper :: Bool -> Maybe Year -> JournalParser m (Posting, Bool)+postingphelper isPostingRule mTransactionYear = do+ -- lift $ dbgparse 0 "postingp"+ -- backtrack if this is not a posting line; but once an account name begins,+ -- its errors (eg an empty part) are reported+ status <- try $ do+ lift skipNonNewlineSpaces1+ status <- lift statusp+ lift skipNonNewlineSpaces+ _ <- lookAhead $ satisfy (not . isSpace)+ return status+ account <- modifiedaccountnamep True+ let preal = accountNamePostingType account+ account' <- shareText $ textUnbracket account+ lift skipNonNewlineSpaces+ mult <- if isPostingRule then multiplierp else pure False+ -- an auto posting rule's *AMT multiplier can't be an expression; other posting amounts can (#2648)+ amt <- optional $ if mult then amountp' MultiplierAmount else postingamountp OrdinaryAmount+ lift skipNonNewlineSpaces+ mc <- lift peekChar+ massertion <- if mc == Just '=' then optional balanceassertionp else pure Nothing+ lift skipNonNewlineSpaces+ (comment,tags,mdate,mdate2) <- lift $ postingcommentp mTransactionYear+ let p = posting+ { pdate=mdate+ , pdate2=mdate2+ , pstatus=status+ , paccount=account'+ , pamount=maybe missingmixedamt mixedAmount amt+ , pcomment=comment+ , preal=preal+ , ptags=tags+ , pbalanceassertion=massertion+ }+ -- Build the posting now (its fields are strict, so this also evaluates the+ -- amount), rather than leaving a thunk holding the parser's intermediate+ -- values until finalisation, which inflates peak memory use on large journals.+ p `seq` return (p, mult)+ where+ multiplierp = option False $ True <$ char '*'++--- ** tests++tests_JournalReader = testGroup "JournalReader" [++ let p = lift accountnamep :: JournalParser IO AccountName in+ testGroup "accountnamep" [+ testCase "basic" $ assertParse p "a:b:c"+ ,testCase "single space is part of the account name" $ assertParseEq p "a b:c" "a b:c"+ ,testCase "empty inner component" $ assertParseError p "a::c" "has an empty part"+ ,testCase "empty leading component" $ assertParseError p ":b:c" "has an empty part"+ ,testCase "empty trailing component" $ assertParseError p "a:b:" "has an empty part"+ ]++ -- "Parse a date in YYYY/MM/DD format.+ -- Hyphen (-) and period (.) are also allowed as separators.+ -- The year may be omitted if a default year has been set.+ -- Leading zeroes may be omitted."+ ,testGroup "datep" [+ testCase "YYYY/MM/DD" $ assertParseEq datep "2018/01/01" (fromGregorian 2018 1 1)+ ,testCase "YYYY-MM-DD" $ assertParse datep "2018-01-01"+ ,testCase "YYYY.MM.DD" $ assertParse datep "2018.01.01"+ ,testCase "yearless date with no default year" $ assertParseError datep "1/1" "current year is unknown"+ ,testCase "yearless date with default year" $ do+ let s = "1/1"+ ep <- parseWithState nulljournal{jparsedefaultyear=Just 2018} datep s+ either (assertFailure . ("parse error at "++) . customErrorBundlePretty) (const $ return ()) ep+ ,testCase "no leading zero" $ assertParse datep "2018/1/1"+ ]+ ,testCase "datetimep" $ do+ let+ good = assertParse datetimep+ bad t = assertParseError datetimep t ""+ good "2011/1/1 00:00"+ good "2011/1/1 23:59:59"+ bad "2011/1/1"+ bad "2011/1/1 24:00:00"+ bad "2011/1/1 00:60:00"+ bad "2011/1/1 00:00:60"+ bad "2011/1/1 3:5:7"+ -- timezone is parsed but ignored+ let t = LocalTime (fromGregorian 2018 1 1) (TimeOfDay 0 0 0)+ assertParseEq datetimep "2018/1/1 00:00-0800" t+ assertParseEq datetimep "2018/1/1 00:00+1234" t++ ,testGroup "periodictransactionp" [++ testCase "more period text in comment after one space" $ assertParseEq periodictransactionp+ "~ monthly from 2018/6 ;In 2019 we will change this\n"+ nullperiodictransaction {+ ptperiodexpr = "monthly from 2018/6"+ ,ptinterval = Months 1+ ,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing+ ,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))+ ,ptdescription = ""+ ,ptcomment = "In 2019 we will change this\n"+ }++ ,testCase "more period text in description after two spaces" $ assertParseEq periodictransactionp+ "~ monthly from 2018/6 In 2019 we will change this\n"+ nullperiodictransaction {+ ptperiodexpr = "monthly from 2018/6"+ ,ptinterval = Months 1+ ,ptspan = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing+ ,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))+ ,ptdescription = "In 2019 we will change this"+ ,ptcomment = ""+ }++ ,testCase "Next year in description" $ assertParseEq periodictransactionp+ "~ monthly Next year blah blah\n"+ nullperiodictransaction {+ ptperiodexpr = "monthly"+ ,ptinterval = Months 1+ ,ptspan = DateSpan Nothing Nothing+ ,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))+ ,ptdescription = "Next year blah blah"+ ,ptcomment = ""+ }++ ,testCase "Just date, no description" $ assertParseEq periodictransactionp+ "~ 2019-01-04\n"+ nullperiodictransaction {+ ptperiodexpr = "2019-01-04"+ ,ptinterval = NoInterval+ ,ptspan = DateSpan (Just $ Exact $ fromGregorian 2019 1 4) (Just $ Exact $ fromGregorian 2019 1 5)+ ,ptsourcepos = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))+ ,ptdescription = ""+ ,ptcomment = ""+ }++ ,testCase "Just date, no description + empty transaction comment" $ assertParse periodictransactionp+ "~ 2019-01-04\n ;\n a 1\n b\n"++ ]++ ,testGroup "postingp" [+ testCase "basic" $ assertParseEq (postingp Nothing)+ " expenses:food:dining $10.00 ; a: a a \n ; b: b b \n"+ posting{+ paccount="expenses:food:dining",+ pamount=mixedAmount (usd 10),+ pcomment="a: a a\nb: b b\n",+ ptags=[("a","a a"), ("b","b b")]+ }++ ,testCase "posting dates" $ assertParseEq (postingp Nothing)+ " a 1. ; date:2012/11/28, date2=2012/11/29,b:b\n"+ nullposting{+ paccount="a"+ ,pamount=mixedAmount (num 1)+ ,pcomment="date:2012/11/28, date2=2012/11/29,b:b\n"+ ,ptags=[("date", "2012/11/28"), ("date2=2012/11/29,b", "b")] -- TODO tag name parsed too greedily+ ,pdate=Just $ fromGregorian 2012 11 28+ ,pdate2=Nothing -- Just $ fromGregorian 2012 11 29+ }++ ,testCase "posting dates bracket syntax" $ assertParseEq (postingp Nothing)+ " a 1. ; [2012/11/28=2012/11/29]\n"+ nullposting{+ paccount="a"+ ,pamount=mixedAmount (num 1)+ ,pcomment="[2012/11/28=2012/11/29]\n"+ ,ptags=[]+ ,pdate= Just $ fromGregorian 2012 11 28+ ,pdate2=Just $ fromGregorian 2012 11 29+ }++ ,testCase "quoted commodity symbol with digits" $ assertParse (postingp Nothing) " a 1 \"DE123\"\n"++ ,testCase "only lot price" $ assertParse (postingp Nothing) " a 1A {1B}\n"+ ,testCase "fixed lot price" $ assertParse (postingp Nothing) " a 1A {=1B}\n"+ ,testCase "total lot price" $ assertParse (postingp Nothing) " a 1A {{1B}}\n"+ ,testCase "fixed total lot price, and spaces" $ assertParse (postingp Nothing) " a 1A {{ = 1B }}\n"+ ,testCase "lot price before transaction price" $ assertParse (postingp Nothing) " a 1A {1B} @ 1B\n"+ ,testCase "lot price after transaction price" $ assertParse (postingp Nothing) " a 1A @ 1B {1B}\n"+ ,testCase "lot price after balance assertion not allowed" $ assertParseError (postingp Nothing) " a 1A @ 1B = 1A {1B}\n" "unexpected '{'"+ ,testCase "only lot date" $ assertParse (postingp Nothing) " a 1A [2000-01-01]\n"+ ,testCase "transaction price, lot price, lot date" $ assertParse (postingp Nothing) " a 1A @ 1B {1B} [2000-01-01]\n"+ ,testCase "lot date, lot price, transaction price" $ assertParse (postingp Nothing) " a 1A [2000-01-01] {1B} @ 1B\n"++ ,testCase "balance assertion over entire contents of account" $ assertParse (postingp Nothing) " a $1 == $1\n"+ ]++ ,testGroup "transactionmodifierp" [++ testCase "basic" $ assertParseEq transactionmodifierp+ "= (some value expr)\n some:postings 1.\n"+ nulltransactionmodifier {+ tmquerytxt = "(some value expr)"+ ,tmpostingrules = [TMPostingRule nullposting{paccount="some:postings", pamount=mixedAmount (num 1)} False]+ }+ ]++ ,testGroup "transactionp" [++ testCase "just a date" $ assertParseEq transactionp "2015/1/1\n" nulltransaction{tdate=fromGregorian 2015 1 1}++ ,testCase "more complex" $ assertParseEq transactionp+ (T.unlines [+ "2012/05/14=2012/05/15 (code) desc ; tcomment1",+ " ; tcomment2",+ " ; ttag1: val1",+ " * a $1.00 ; pcomment1",+ " ; pcomment2",+ " ; ptag1: val1",+ " ; ptag2: val2"+ ])+ nulltransaction{+ tsourcepos=(SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 8) (mkPos 1)), -- 8 because there are 7 lines+ tprecedingcomment="",+ tdate=fromGregorian 2012 5 14,+ tdate2=Just $ fromGregorian 2012 5 15,+ tstatus=Unmarked,+ tcode="code",+ tdescription="desc",+ tcomment="tcomment1\ntcomment2\nttag1: val1\n",+ ttags=[("ttag1","val1")],+ tpostings=[+ nullposting{+ pdate=Nothing,+ pstatus=Cleared,+ paccount="a",+ pamount=mixedAmount (usd 1),+ pcomment="pcomment1\npcomment2\nptag1: val1\nptag2: val2\n",+ preal=RealPosting,+ ptags=[("ptag1","val1"),("ptag2","val2")],+ ptransaction=Nothing+ }+ ]+ }++ ,testCase "parses a well-formed transaction" $+ assertBool "" $ isRight $ rjp transactionp $ T.unlines+ ["2007/01/28 coopportunity"+ ," expenses:food:groceries $47.18"+ ," assets:checking $-47.18"+ ,""+ ]++ ,testCase "does not parse a following comment as part of the description" $+ assertParseEqOn transactionp "2009/1/1 a ;comment\n b 1\n" tdescription "a"++ ,testCase "parses a following whitespace line" $+ assertBool "" $ isRight $ rjp transactionp $ T.unlines+ ["2012/1/1"+ ," a 1"+ ," b"+ ," "+ ]++ ,testCase "parses an empty transaction comment following whitespace line" $+ assertBool "" $ isRight $ rjp transactionp $ T.unlines+ ["2012/1/1"+ ," ;"+ ," a 1"+ ," b"+ ," "+ ]++ ,testCase "comments everywhere, two postings parsed" $+ assertParseEqOn transactionp+ (T.unlines+ ["2009/1/1 x ; transaction comment"+ ," a 1 ; posting 1 comment"+ ," ; posting 1 comment 2"+ ," b"+ ," ; posting 2 comment"+ ])+ (length . tpostings)+ 2++ ]++ ,let amts = map (\p -> (map (\a -> (aquantity a, asprecision $ astyle a)) $ amountsRaw $ pamount p, postingHasTag roundedPostingTagName p))+ in testGroup "amount expressions are rounded" [+ testCase "to the entry's precision, after all postings are read" $+ assertParseEqOn transactionp (T.unlines ["2026-01-01", " a $100/3", " b $10 * 0.15", " c $-100.00"]) (amts . tpostings)+ [([(33.33, Precision 2)], True), ([(1.5, Precision 2)], False), ([(-100, Precision 2)], False)]+ ,testCase "with banker's rounding" $+ assertParseEqOn transactionp (T.unlines ["2026-01-01", " a $0.25 / 2", " b $0.35 / 2", " c $-0.30"]) (amts . tpostings)+ [([(0.12, Precision 2)], True), ([(0.18, Precision 2)], True), ([(-0.3, Precision 2)], False)]+ ,testCase "not counting cost amounts" $+ assertParseEqOn transactionp (T.unlines ["2026-01-01", " a 10 X / 3 @ $1.2345", " b $-4"]) (amts . tpostings)+ [([(3, Precision 0)], True), ([(-4, Precision 0)], False)]+ ,testCase "to their own precision in periodic transactions" $+ assertParseEqOn periodictransactionp (T.unlines ["~ monthly", " a $100/3", " b $-100.00"]) (amts . ptpostings)+ [([(33, Precision 0)], False), ([(-100, Precision 2)], False)]+ ,testCase "to their own precision in auto posting rules" $+ assertParseEqOn transactionmodifierp (T.unlines ["= a", " (b) $100/3", " (c) $-100.00"]) (amts . map tmprPosting . tmpostingrules)+ [([(33, Precision 0)], False), ([(-100, Precision 2)], False)]+ ]++ -- directives++ ,let p = assertdirectivep (fromGregorian 2026 11 8)+ summary ad = (adQuantifier ad, fmap fst (adPeriod ad), adQueryText ad)+ in testGroup "assertdirectivep" [+ testCase "no period, comment" $ assertParseEqOn p "assert none expenses:petty amt:>+500 ; a comment\n" summary+ (AssertNone, Nothing, "expenses:petty amt:>+500")+ ,testCase "no period, empty query" $ assertParseEqOn p "assert some\n" summary+ (AssertSome, Nothing, "")+ ,testCase "no period, empty query, comment" $ assertParseEqOn p "assert some ; a comment\n" summary+ (AssertSome, Nothing, "")+ ,testCase "no period, balance: term" $ assertParseEqOn p "assert none type:A balance:<0\n" summary+ (AssertNone, Nothing, "type:A balance:<0")+ ,testCase "no period, double space inside the query" $ assertParseEqOn p "assert none desc:'a b'\n" summary+ (AssertNone, Nothing, "desc:'a b'")+ ,testCase "period with interval" $ assertParseEqOn p "assert none daily type:A balance:<0\n" summary+ (AssertNone, Just (Days 1), "type:A balance:<0")+ ,testCase "period with span only" $ assertParseEqOn p "assert some in 2025 income:salary\n" summary+ (AssertSome, Just NoInterval, "income:salary")+ ,testCase "period, empty query" $ assertParseEqOn p "assert some monthly\n" summary+ (AssertSome, Just (Months 1), "")+ ,testCase "period, empty query, comment" $ assertParseEqOn p "assert some monthly ; a comment\n" summary+ (AssertSome, Just (Months 1), "")+ ,testCase "a query starting with the word balance" $ assertParseEqOn p "assert none balance\n" summary+ (AssertNone, Nothing, "balance")+ ,testCase "bad quantifier" $ assertParseError p "assert never expenses\n" "should be followed by none or some"+ ,testCase "period expression not parseable" $ assertParseError p "assert none dialy expenses\n" "as a period expression"+ ,testCase "query needs two spaces" $ assertParseError p "assert some desc:'opening balances'\n" "as a period expression"+ ,testCase "period expression needs a double space" $ assertParseError p "assert none daily type:A\n" "terminate the period expression with a double space"+ ,testCase "bad query" $ assertParseError p "assert none amt:>x\n" ""+ ,testCase "row terms inside or" $ assertParseError p "assert none monthly expr:'a or change:>0'\n" "can only be combined"+ ]++ ,testGroup "directivep" [+ testCase "supports !" $ do+ assertParseE (directivep definputopts) "!account a\n"+ assertParseE (directivep definputopts) "!D 1.0\n"+ ]++ ,testGroup "accountdirectivep" [+ testCase "with-comment" $ assertParse accountdirectivep "account a:b ; a comment\n"+ ,testCase "does-not-support-!" $ assertParseError accountdirectivep "!account a:b\n" ""+ ,testCase "account-type-code" $ assertParse accountdirectivep "account a:b ; type:A\n"+ ,testCase "account-type-tag" $ assertParseStateOn accountdirectivep "account a:b ; type:asset\n"+ jdeclaredaccounts+ [("a:b", AccountDeclarationInfo{adicomment = "type:asset\n"+ ,aditags = [("type","asset")]+ ,adideclarationorder = 1+ ,adisourcepos = nullsourcepos+ })+ ]+ ]++ ,testCase "commodityconversiondirectivep" $ do+ assertParse commodityconversiondirectivep "C 1h = $50.00\n"++ ,testCase "defaultcommoditydirectivep" $ do+ assertParse defaultcommoditydirectivep "D $1,000.0\n"+ assertParseError defaultcommoditydirectivep "D $1000\n" "Please include a decimal point or decimal comma"++ ,testGroup "defaultyeardirectivep" [+ testCase "1000" $ assertParse defaultyeardirectivep "Y 1000" -- XXX no \n like the others+ -- ,testCase "999" $ assertParseError defaultyeardirectivep "Y 999" "bad year number"+ ,testCase "12345" $ assertParse defaultyeardirectivep "Y 12345"+ ]++ ,testCase "ignoredpricecommoditydirectivep" $ do+ assertParse ignoredpricecommoditydirectivep "N $\n"++ ,testGroup "includedirectivep" [+ testCase "include" $ assertParseErrorE (includedirectivep definputopts) "include nosuchfile\n" "No files were matched by: nosuchfile"+ ,testCase "glob" $ assertParseErrorE (includedirectivep definputopts) "include nosuchfile*\n" "No files were matched by: nosuchfile*"+ ]++ ,testCase "marketpricedirectivep" $ assertParseEq marketpricedirectivep+ "P 2017/01/30 BTC $922.83\n"+ PriceDirective{+ pdsourcepos = nullsourcepos,+ pddate = fromGregorian 2017 1 30,+ pdcommodity = "BTC",+ pdamount = usd 922.83+ }++ ,testGroup "payeedirectivep" [+ testCase "simple" $ assertParse payeedirectivep "payee foo\n"+ ,testCase "with-comment" $ assertParse payeedirectivep "payee foo ; comment\n"+ ,testCase "double-quoted" $ assertParse payeedirectivep "payee \"a b\"\n"+ ,testCase "empty " $ assertParse payeedirectivep "payee \"\"\n"+ ]++ ,testCase "tagdirectivep" $ do+ assertParse tagdirectivep "tag foo \n"++ ,testCase "endtagdirectivep" $ do+ assertParse endtagdirectivep "end tag \n"+ assertParse endtagdirectivep "end apply tag \n"++ ,testGroup "journalp" [+ testCase "empty file" $ assertParseEqE (journalp definputopts) "" nulljournal+ ]++ -- these are defined here rather than in Common so they can use journalp+ ,testCase "parseAndFinaliseJournal" $ do+ ej <- runExceptT $ parseAndFinaliseJournal (journalp definputopts) definputopts "" "2019-1-1\n"+ let Right j = ej+ assertEqual "" [""] $ journalFilePaths j++ ]
+ Hledger/Read/LatestDates.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}+{-|++The @.latest@ mechanism: a per-input-file record of the latest transaction+date(s) seen on the previous read, used by @hledger import@ (and any reader+called with @new_=True@) to filter out already-seen transactions.++For an input file @F@, the latest dates are kept in a @.latest.F@ hidden file+in @F@'s directory. They are written after a successful import and read on the+next one. The CSV rules reader's @archive@ rule also consults these to decide+whether a fresh archive is warranted.++These helpers live in their own module so both the high-level reader+('Hledger.Read') and the low-level CSV rules reader ('Hledger.Read.RulesReader')+can use them without a module-graph cycle.++-}++module Hledger.Read.LatestDates (+ LatestDates,+ LatestDatesForFile(..),+ latestDates,+ latestDatesFileFor,+ previousLatestDates,+ saveLatestDates,+ saveLatestDatesForFiles,+ journalFilterSinceLatestDates,+) where++import Control.Monad (forM, when)+import Data.List (group, sort, sortBy)+import Data.Maybe (catMaybes)+import Data.Ord (comparing)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Time (Day)+import Safe (headDef)+import System.Directory (doesFileExist)+import System.FilePath (splitFileName, (</>), (<.>))+import Text.Printf (printf)++import Hledger.Data.Dates (parsedate, showDate)+import Hledger.Data.Types (Journal(..), Transaction(..))+import Hledger.Utils (error', readFileStrictly)++-- | One or more dates of the same kind, eg the latest transaction date(s) read from a file.+type LatestDates = [Day]++-- | The path of an input file, and its current 'LatestDates'.+data LatestDatesForFile = LatestDatesForFile FilePath LatestDates+ deriving Show++-- | Get all instances of the latest date in an unsorted list of dates.+-- Ie, if the latest date appears once, return it in a one-element list,+-- if it appears three times (anywhere), return three of it.+latestDates :: [Day] -> LatestDates+latestDates = {-# HLINT ignore "Avoid reverse" #-}+ headDef [] . take 1 . group . reverse . sort++-- | Where to save latest transaction dates for the given file path: @.latest.FILE@+-- in @FILE@'s directory.+latestDatesFileFor :: FilePath -> FilePath+latestDatesFileFor f = dir </> ".latest" <.> fname+ where+ (dir, fname) = splitFileName f++-- | Save the given latest date(s) seen in the given data FILE,+-- in a hidden file named @.latest.FILE@, creating it if needed.+-- Unless no latest dates are provided, in which case do nothing.+saveLatestDates :: LatestDates -> FilePath -> IO ()+saveLatestDates dates f = when (not $ null dates) $+ T.writeFile (latestDatesFileFor f) $ T.unlines $ map showDate dates++-- | Save each file's latest dates.+saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()+saveLatestDatesForFiles = mapM_ (\(LatestDatesForFile f ds) -> saveLatestDates ds f)++-- | What were the latest transaction dates seen the last time this+-- journal file was read ? If there were multiple transactions on the+-- latest date, that number of dates is returned, otherwise just one.+-- Or none if no transactions were read, or if latest dates info is not+-- available for this file.+previousLatestDates :: FilePath -> IO LatestDates+previousLatestDates f = do+ let latestfile = latestDatesFileFor f+ exists <- doesFileExist latestfile+ t <- if exists then readFileStrictly latestfile else return T.empty+ let nls = zip [1::Int ..] $ T.lines t+ fmap catMaybes $ forM nls $ \(n,l) -> do+ let s = T.unpack $ T.strip l+ case (s, parsedate s) of+ ("", _) -> return Nothing+ (_, Nothing) -> error' (printf "%s:%d: invalid date: \"%s\"" latestfile n s)+ (_, Just d) -> return $ Just d++-- | Given zero or more latest dates (all the same, representing the+-- latest previously seen transaction date, and how many transactions+-- were seen on that date), remove transactions with earlier dates+-- from the journal, and the same number of transactions on the+-- latest date, if any, leaving only transactions that we can assume+-- are newer. Also returns the new latest dates of the new journal.+journalFilterSinceLatestDates :: LatestDates -> Journal -> (Journal, LatestDates)+journalFilterSinceLatestDates [] j = (j, latestDates $ map tdate $ jtxns j)+journalFilterSinceLatestDates ds@(d:_) j = (j', ds')+ where+ samedateorlaterts = filter ((>= d).tdate) $ jtxns j+ (samedatets, laterts) = span ((== d).tdate) $ sortBy (comparing tdate) samedateorlaterts+ newsamedatets = drop (length ds) samedatets+ j' = j{jtxns=newsamedatets++laterts}+ ds' = latestDates $ map tdate $ samedatets++laterts
+ Hledger/Read/RulesReader.hs view
@@ -0,0 +1,2717 @@+--- * module+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-|++A reader for a CSV rules file. +This reads the actual data from a file specified by a `source` rule+or from a similarly-named file in the same directory.++Most of the code for reading rules files and csv files is in this module.+-}+-- Lots of haddocks in this file are for non-exported types.+-- Here's a command that will render them:+-- stack haddock hledger-lib --fast --no-haddock-deps --haddock-arguments='--ignore-all-exports' --open++--- ** language+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}++--- ** exports+module Hledger.Read.RulesReader (+ -- * Reader+ reader,+ -- * Misc.+ dataFileFor,+ rulesFileFor,+ getRulesFile,+ readRules,+ rulesEncoding,+ readJournalFromCsv,+ readParsedJournalFromCsv,+ parseBalanceAssertionType,+ -- * Tests+ tests_RulesReader,+)+where++--- ** imports+import Prelude hiding (Applicative(..))+import Control.Applicative (Applicative(..))+import Control.Concurrent (forkIO)+import Control.DeepSeq (deepseq)+import Control.Exception.Safe (catchAny, tryIO)+import Control.Monad (guard, unless, void, when)+import Control.Monad.Except (ExceptT(..), liftEither, throwError, withExceptT)+import Control.Monad.Fail qualified as Fail+import Control.Monad.IO.Class (MonadIO, liftIO)+import Control.Monad.State.Strict (StateT, get, gets, modify', evalStateT)+import Control.Monad.Trans.Class (lift)+import Data.Char (toLower, toUpper, isAsciiLower, isDigit, isSpace, isAlphaNum, ord)+import Data.Bifunctor (first)+import Data.ByteString qualified as B+import Data.ByteString.Lazy qualified as BL+import Data.Csv qualified as Cassava+import Data.Csv.Parser.Megaparsec qualified as CassavaMegaparsec+import Data.Encoding (encodingFromStringExplicit, DynEncoding)+import Data.Either (fromRight)+import Data.Functor ((<&>))+import Data.Graph (SCC(..), stronglyConnComp)+import Data.List (elemIndex, find, nub, sort, sortOn, isInfixOf, isPrefixOf)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List.Extra (groupOn)+import Data.List.NonEmpty qualified as NE+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)+import Data.Set qualified as S+import Data.MemoUgly (memo)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Data.Text.IO qualified as T+import Data.Time ( Day, TimeZone, UTCTime, LocalTime, ZonedTime(ZonedTime),+ defaultTimeLocale, getCurrentTimeZone, localDay, parseTimeM, utcToLocalTime, localTimeToUTC, zonedTimeToUTC, utctDay)+import Safe (atMay, headDef, headMay, lastDef, lastMay, readDef, readMay)+import System.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getHomeDirectory, getModificationTime, listDirectory, removeFile)+import System.Exit (ExitCode(..))+import System.FilePath (isAbsolute, normalise, splitDirectories, stripExtension, takeBaseName, takeDirectory, takeExtension, takeFileName, (<.>), (</>))+import System.IO (Handle, hClose, hPutStrLn, stderr, hGetContents')+import System.Process (CreateProcess(..), StdStream(CreatePipe), shell, waitForProcess, withCreateProcess)+import Data.Foldable (asum, toList)+import Text.Megaparsec hiding (match, parse)+import Text.Megaparsec qualified as P (match)+import Text.Megaparsec.Char (char, newline, string, digitChar)+import Text.Printf (printf)++import Hledger.Data+import Hledger.Utils+import Hledger.Read.Common (aliasesFromOpts, Reader(..), InputOpts(..), AmountParseKind(..), amountp, amountp', postingamountp, statusp, includeFileParser, journalFinalise, accountnamep, transactioncommentp, postingcommentp )+import Hledger.Write.Csv++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++--- ** reader+_READER__________________________________________ = undefined -- VSCode outline separator+++reader :: MonadIO m => Reader m+reader = Reader+ {rFormat = Rules+ ,rExtensions = ["rules"]+ ,rReadFn = parse+ -- When included by a journal file, the data is read as usual but not finalised;+ -- the including journal's finalisation handles that.+ ,rParser = \iopts -> includeFileParser $ \f -> readRulesFileWith iopts f (const pure)+ }++getDownloadDir = do+ home <- getHomeDirectory+ return $ home </> "Downloads" -- XXX++-- | Read, parse and post-process a "Journal" from the given rules file, or give an error.+-- See 'readRulesFileWith' for details. This ignores the provided input file handle.+parse :: InputOpts -> FilePath -> Handle -> ExceptT String IO Journal+parse iopts rulesfile h = do+ lift $ hClose h -- We don't need it (XXX why ?)+ readRulesFileWith iopts rulesfile $ \adderrorcontext j -> do+ -- apply any command line account aliases. Can fail with a bad replacement pattern.+ j' <- liftEither $ journalApplyAliases (aliasesFromOpts iopts) j+ -- if finalisation fails, show also the CSV record which generated the failing entry+ withExceptT adderrorcontext $+ journalFinalise iopts{balancingopts_=(balancingopts_ iopts){ignore_assertions_=True}} rulesfile "" j'++-- | Read the given rules file and the data it specifies, convert the data to an unfinalised journal,+-- post-process that with the given action (which also receives the error context adder described+-- in 'readJournalFromCsv', useful for annotating finalisation errors), and then archive the data if appropriate.+-- This is the core of the rules reader; it is also used when a rules file is included by a journal file.+-- It provides some extra features like data cleaning/generating commands and data archiving.+--+-- Unlike CsvReader, this ignores the --rules option.+-- Instead, it reads a data file (or data-generating command) specified by the @source@ rule,+-- or if there is no @source@ rule, it raises an error.+--+-- The source rule's path is resolved as follows:+--+-- * @~/foo.csv@ or @/abs/foo.csv@ - used as-is (home is expanded).+-- * @./foo.csv@ or @../foo.csv@ - anchored relative to the rules file's directory (no fallback).+-- * bare filename (@foo.csv@) or other relative path (@sub/foo.csv@) - looked for in+-- the journal's data directory first, otherwise in @~/Downloads@.+--+-- The data directory is the same one used by the @archive@ rule and the @get@ command.+-- By default it is @data/@ next to the main input file.+-- When the input file's directory is unknown, eg when reading from stdin, the data directory is @data/@ next to the rules file.+--+-- The directory comes from 'InputOpts._journaldir', set by the CLI entry points+-- ('withJournal', 'withPossibleJournal', 'journalReload'). Library callers doing a+-- secondary read after a journal has been loaded (the pattern used by the @import@+-- command) should apply 'inputOptsSetJournalDir' to their iopts.+--+-- The source rule can specify a glob pattern: @source foo*.csv@.+-- If the glob pattern matches multiple files, the newest (last modified) file is used (with one exception, described below).+--+-- The source rule can specify a data-cleaning command, after a @|@ separator: @source foo*.csv | sed -e 's/USD/$/g'@.+-- This command is executed by the user's default shell, receives the data file's content on stdin,+-- and should output CSV data suitable for the conversion rules.+-- A # character can be used to comment out the data-cleaning command: @source foo*.csv # | ...@.+--+-- Or the source rule can specify just a data-generating command, with no file pattern: @source | foo-csv.sh@.+-- In this case the command receives no input; it should output CSV data suitable for the conversion rules.+--+-- If the archive rule is present:+-- 1. After successfully reading the data file or data command and converting to a journal, while doing a non-dry-run import:+-- the data will be archived in an @archive/@ subdirectory of the data directory (see above), auto-creating it if needed.+-- (The subdirectory keeps archived files out of sight of the source rule's glob, which might otherwise re-match them.)+-- The archive file name will be based on the rules file and the data file's modification date and extension+-- (or when the source is a data-generating command: the current date and the ".csv" extension).+-- 2. import will prefer the oldest file matched by a glob pattern (not the newest).+--+-- Balance assertions are not checked when the rules file is read directly;+-- when it is included by a journal file, they are checked along with the rest of the journal.+--+readRulesFileWith :: InputOpts -> FilePath -> ((String -> String) -> ParsedJournal -> ExceptT String IO Journal) -> ExceptT String IO Journal+readRulesFileWith iopts rulesfile postprocess = do++ -- The rules reader does a lot; we must be organised.++ -- 1. gather contextual info+ -- gives: import flag, dryrun flag, rulesdir++ let+ import_ = _importing iopts+ dryrun = _dryrun iopts+ yn b = if b then "yes" else "no"+ dbg2MsgIO $ "importing? " <> yn import_+ when import_ $ dbg2MsgIO $ "dry run? " <> yn dryrun++ -- 2. parse the source and archive rules+ -- needs: rules file+ -- gives: file pattern, data cleaning/generating command, archive flag++ -- XXX higher-than usual logging priority for file reading (normally 6 or 7), to bypass excessive noise from elsewhere+ (rules, rulesfiles) <- readRules $ dbg1 "reading rules file" rulesfile+ let+ msourcearg = getDirective "source" rules+ -- Nothing -> error' $ rulesfile ++ " source rule must specify a file pattern or a command"+ -- A # anywhere starts a same-line comment, stripped from the whole source value.+ -- Surrounding whitespace is then removed from the whole source argument and from each part of it.+ stripcomment = T.takeWhile (/= '#')+ stripspaces = T.strip+ mpatandcmd = T.breakOn "|" . stripspaces . stripcomment <$> msourcearg+ mpat = -- a non-empty file pattern, or nothing+ case T.unpack . stripspaces . fst <$> mpatandcmd of+ Just s | not $ null s -> Just s+ _ -> Nothing+ mcmd = dbg2 "data command" $ -- a non-empty command, or nothing+ mpatandcmd >>= \sc ->+ let c = T.unpack . stripspaces . T.drop 1 . snd $ sc+ in if null c then Nothing else Just c++ archive = isJust (getDirective "archive" rules)++ -- 3. find the file to be read, if any+ -- needs: file pattern, data command, import flag, archive flag, data dir, downloads dir+ -- gives: data file, data file description++ -- The data/ directory lives next to the main journal file.+ -- This is the same directory used by the get command and by the archive rule below.+ let+ journaldir = fromMaybe (takeDirectory $ dbg2 "rulesfile" rulesfile) $ dbg2 "input file directory" $ _journaldir iopts+ datadir = dbg2 "data directory" $ journaldir </> dataDirName+ datacmddesc = if isJust mpat then "data cleaning command" else "data generating command"++ (mdatafile, datafiledesc) <- dbg2 "data file found ?" <$>+ case (journaldir `seq` datadir `seq` dbg2 "file pattern" mpat, dbg2 datacmddesc mcmd) of+ (Nothing, Nothing) -> error' $ "to make " ++ rulesfile ++ " readable,\n please add a 'source' rule with a non-empty file pattern or command"+ (Nothing, Just _) -> return (Nothing, "")+ (Just pat, _) -> do+ dldir <- liftIO getDownloadDir+ -- Source-rule path resolution (platform-independent):+ -- ./foo or ../foo -> anchored relative to the rules file's directory (no fallback)+ -- /abs or ~/foo -> used as-is (no fallback)+ -- bare or sub/foo -> looked for under the data directory, then ~/Downloads+ let firstSeg = headDef "" $ splitDirectories pat+ anchoredToRulesDir = firstSeg `elem` [".", ".."]+ -- ~ isn't a real path concept; only special as a leading literal segment.+ isAbsoluteOrTilde = isAbsolute pat || firstSeg == "~"+ plainRelative = not anchoredToRulesDir && not isAbsoluteOrTilde+ primarydir = if anchoredToRulesDir then takeDirectory rulesfile else datadir+ primarydesc | anchoredToRulesDir = "relative to rules directory"+ | otherwise = "in data directory"+ fs <- liftIO $ do+ primaryfs <- expandGlob primarydir pat >>= sortByModTime+ dbg2IO ("matched files "<>primarydesc<>", oldest first") primaryfs+ if not (null primaryfs) || not plainRelative+ then return primaryfs+ else do+ dlfs <- expandGlob dldir pat >>= sortByModTime+ dbg2IO ("matched files in "<>dldir<>", oldest first") dlfs+ return dlfs+ return $+ if import_ && archive+ then (headMay fs, " oldest file")+ else (lastMay fs, " newest file")++ -- 4. log which file we are reading/importing/cleaning/generating+ -- needs: data file, data file description, import flag++ case (mdatafile, datafiledesc) of+ (Just f, desc) -> dbg1IO ("trying to " ++ (if import_ then "import" else "read") ++ desc) f+ (Nothing, _) -> return ()++ -- 5. read raw, cleaned or generated data+ -- needs: file pattern, data file, optional data file encoding, data command+ -- gives: clean data (possibly empty)++ mexistingdatafile <- maybe (return Nothing) (\f -> liftIO $ do+ exists <- doesFileExist f+ return $ if exists then Just f else Nothing+ ) $ mdatafile+ let+ -- Show a source command on stderr, saying which rules file it's from.+ logCommand c = hPutStrLn stderr $ takeFileName rulesfile <> ": running source command: " <> c+ cleandata <- dbg1With (\t -> "read "++(show $ length $ T.lines t)++" lines") <$>+ -- when just finding the files read, don't read the data or run any command+ if _scanfiles iopts then return "" else+ case (mpat, mexistingdatafile, mcmd) of++ -- file pattern, but no file found+ (Just _, Nothing, _) -> -- trace "file pattern, but no file found" $+ return ""++ -- file found, and maybe a data cleaning command+ (_, Just f, mc) -> do -- trace "file found" $+ mencoding <- rulesEncoding rulesfile rules+ liftIO $ do+ raw <- openFileOrStdin f >>= hGetContentsPortably mencoding+ maybe (return raw) (\c -> logCommand c >> runCommandAsFilter rulesfile c raw) mc++ -- no file pattern, but a data generating command+ -- (run even in a dry run import, which needs the data to preview it;+ -- hledger can't tell whether the command is safe to repeat)+ (Nothing, _, Just cmd) ->+ liftIO $+ (logCommand cmd >> runCommand rulesfile cmd)+ -- if it fails, warn and carry on+ `catchAny` (\e -> warn (show e) $ return "")++ -- neither a file pattern nor a data generating command+ (Nothing, _, Nothing) -> -- trace "no file pattern or data generating command" $+ error' $ rulesfile ++ " source rule must specify a file pattern or a command"++ -- 6. convert the clean data to a (possibly empty) journal, and post-process it+ -- needs: clean data, rules, data file if any, rules files+ -- gives: journal++ j <- do+ -- Note the other files this journal's data came from - the included rules files,+ -- and the data file if any - for the files command, and to detect changes when reloading.+ let auxfiles = (rulesfile, filter (/= rulesfile) rulesfiles <> maybe [] (pure . normalise) mexistingdatafile)+ (j1, adderrorcontext) <- readParsedJournalFromCsv rulesfile rules auxfiles (fromMaybe "(cmd)" mdatafile) cleandata Nothing+ postprocess adderrorcontext j1++ -- 7. if non-empty, successfully read and converted, and we're doing a non-dry-run+ -- archiving import: archive the data, then consume the source file.+ -- needs: import/archive/dryrun flags, data dir, rules file, data file if any, clean data+ when (not (T.null cleandata) && import_ && archive && not dryrun) $ liftIO $ do+ let archivedir = datadir </> "archive"+ -- Archive a copy of the data, unless the most recent archive already holds exactly+ -- this data. That happens when re-running a data-generating command that produces+ -- the same output, or processing a duplicate of an already-archived file; archiving+ -- it again would just accumulate identical copies.+ mprevarchive <- latestArchive archivedir rulesfile >>= maybe (return Nothing) (fmap Just . T.readFile)+ when (mprevarchive /= Just cleandata) $+ saveToArchive archivedir rulesfile mdatafile cleandata+ -- Now that the data is safely archived (or was already), remove the original source+ -- data file if any. This only runs if the archiving above did not raise an error,+ -- and lets a later run advance to the next (newer) glob-matched file.+ maybe (return ()) removeFile mdatafile++ return j++-- | For the given rules file, run the given shell command, in the rules file's directory.+-- The command gets an empty stdin, so it can't wait for input or consume hledger's stdin,+-- which would cause confusion and/or hangs in some situations.+-- If the command fails, raise an error and show its error output;+-- otherwise return its output, and show any error output as a warning.+runCommand :: FilePath -> String -> IO Text+runCommand rulesfile cmd = do+ let process = (shell cmd) { cwd = Just $ takeDirectory rulesfile, std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }+ withCreateProcess process $ \mhin mhout mherr phandle -> do+ case (mhin, mhout, mherr) of+ (Just hin, Just hout, Just herr) -> do+ hClose hin+ out <- T.hGetContents hout+ err <- hGetContents' herr+ exitCode <- waitForProcess phandle+ case exitCode of+ ExitSuccess -> do+ unless (null err) $ warnIO err+ return out+ ExitFailure code ->+ error' $ "in " ++ rulesfile ++ ": command \"" ++ cmd ++ "\" failed with exit code " ++ show code+ ++ (if null err then "" else ":\n" ++ err)+ _ -> error' $ "in " ++ rulesfile ++ ": failed to create pipes for command execution"++-- | For the given rules file, run the given shell command, in the rules file's directory, passing the given text as input.+-- Return the output, or if the command fails, raise an informative error.+runCommandAsFilter :: FilePath -> String -> Text -> IO Text+runCommandAsFilter rulesfile cmd input = do+ let process = (shell cmd) { cwd = Just $ takeDirectory rulesfile, std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }+ withCreateProcess process $ \mhin mhout mherr phandle -> do+ case (mhin, mhout, mherr) of+ (Just hin, Just hout, Just herr) -> do+ forkIO $ T.hPutStr hin input >> hClose hin+ out <- T.hGetContents hout+ err <- hGetContents' herr+ exitCode <- waitForProcess phandle+ case exitCode of+ ExitSuccess -> return out+ ExitFailure code ->+ error' $ "in " ++ rulesfile ++ ": command \"" ++ cmd ++ "\" failed with exit code " ++ show code+ ++ (if null err then "" else ":\n" ++ err)+ _ -> error' $ "in " ++ rulesfile ++ ": failed to create pipes for command execution"++type DirPath = FilePath++-- | Save some successfully imported data+-- (more precisely: data that was successfully read and maybe cleaned, or that was generated, during an import)+-- to the given archive directory, autocreating that if needed, and show informational output on stderr.+-- The arguments are:+-- the archive directory,+-- the rules file (for naming),+-- the data file name, if any,+-- the data that was read, cleaned, or generated.+-- The archive file name will be RULESFILEBASENAME.DATAFILEMODDATEORCURRENTDATE.DATAFILEEXTORCSV.+-- Note for a data generating command, where there's no data file, we use the current date+-- and a .csv file extension (meaning "character-separated values" in this case).+-- This does not remove the source data file; the caller does that once archiving has succeeded.+saveToArchive :: DirPath -> FilePath -> Maybe FilePath -> Text -> IO ()+saveToArchive archivedir rulesfile mdatafile cleandata = do+ createDirectoryIfMissing True archivedir+ (_, cleanname) <- archiveFileName rulesfile mdatafile+ let cleanarchive = archivedir </> cleanname+ hPutStrLn stderr $ "archiving " <> cleanarchive+ T.writeFile cleanarchive cleandata++-- | In the given archive directory, if it exists, find the most recently modified+-- data file archived there for the given rules file, if any.+--+-- We don't know which extension the archived data files use, but they are named beginning+-- with the rules file's base name followed by a dot (see 'archiveFileName'), which is normally+-- good enough. Any ".orig." originals are ignored, so this returns a cleaned/generated copy.+latestArchive :: DirPath -> FilePath -> IO (Maybe FilePath)+latestArchive archivedir rulesfile = do+ exists <- doesDirectoryExist archivedir+ if not exists then return Nothing+ else do+ let prefix = takeBaseName rulesfile <> "."+ fs <- listDirectory archivedir+ let archives = [archivedir </> f | f <- fs, prefix `isPrefixOf` f, not (".orig." `isInfixOf` f)]+ lastMay <$> sortByModTime archives++-- | Figure out the file names to use when archiving, for the given rules file and the given data file if any.+-- The second name is for the final (possibly cleaned) data; the first name has ".orig" added,+-- and is used if both original and cleaned data are being archived. They will be like this:+-- ("RULESFILEBASENAME.orig.DATAFILEMODDATE.DATAFILEEXT", "RULESFILEBASENAME.DATAFILEMODDATE.DATAFILEEXT")+archiveFileName :: FilePath -> Maybe FilePath -> IO (String, String)+archiveFileName rulesfile mdatafile = do+ let base = takeBaseName rulesfile+ case mdatafile of+ Just datafile -> do+ moddate <- (show . utctDay) <$> getModificationTime datafile+ let ext = takeExtension datafile+ return (+ base <.> "orig" <.> moddate <.> ext+ ,base <.> moddate <.> ext+ )+ Nothing -> do+ let ext = "csv"+ curdate <- show <$> getCurrentDay+ return (+ base <.> "orig" <.> curdate <.> ext+ ,base <.> curdate <.> ext+ )++--- ** reading rules files+--- *** rules utilities+_RULES_READING__________________________________________ = undefined++-- | Given a rules file path, what would be the corresponding data file ?+-- (Remove a .rules extension.)+dataFileFor :: FilePath -> Maybe FilePath+dataFileFor = stripExtension "rules"++-- | Given a csv file path, what would be the corresponding rules file ?+-- (Add a .rules extension.)+rulesFileFor :: FilePath -> FilePath+rulesFileFor = (++ ".rules")++-- | Return the given rules file path, or if none is given,+-- the default rules file for the given csv file;+-- or if the csv file is "-", raise an error.+getRulesFile :: FilePath -> Maybe FilePath -> FilePath+getRulesFile csvfile mrulesfile =+ case mrulesfile of+ Nothing | csvfile == "-" ->+ error' "please use --rules when reading CSV from stdin" -- PARTIAL+ -- XXX is this bad ? everything else here uses ExceptT+ Nothing -> rulesFileFor csvfile+ Just f -> f++-- | An exception-throwing IO action that reads and validates+-- the specified CSV rules file (which may include other rules files).+-- Also returns the paths of all the rules files read, so that changes+-- to any of them can be detected later (see jauxfiles).+readRules :: FilePath -> ExceptT String IO (CsvRules, [FilePath])+readRules f = do+ liftIO $ dbg6IO "using conversion rules file" f+ (txt, sourcelines) <- expandIncludes (takeDirectory f) f =<< liftIO (readFilePortably f)+ rules <- liftEither $ parseAndValidateCsvRules f sourcelines txt+ return (rules, nub $ f : map fst sourcelines)++-- | Read the encoding specified by the @encoding@ rule, if any.+-- Or throw an error if an unrecognised encoding is specified.+rulesEncoding :: FilePath -> CsvRules -> ExceptT String IO (Maybe DynEncoding)+rulesEncoding rulesfile rules = do+ case T.unpack <$> getDirective "encoding" rules of+ Nothing -> return Nothing+ Just encstr -> case encodingFromStringExplicit $ dbg4 "encoding name" encstr of+ Nothing -> throwError $ rulesfile <> ": Invalid encoding: " <> encstr+ Just enc -> return . Just $ dbg4 "encoding" enc++-- | Inline all files referenced by include directives in this hledger CSV rules text, recursively.+-- Included file paths may be relative to the directory of the provided file path.+-- Unlike with journal files, this is done as a pre-parse step to simplify the CSV rules parser.+-- So that errors can still be reported at the right place, this also returns+-- each expanded line's source: the file it came from and its line number there.+-- Raises an error if an included file can not be read, or forms an include cycle.+expandIncludes :: FilePath -> FilePath -> Text -> ExceptT String IO (Text, [(FilePath, Int)])+expandIncludes dir file content = do+ cfile <- liftIO $ canonicalizePath file+ first T.unlines . unzip <$> expandLines [cfile] dir file content+ where+ -- The first argument is the canonical paths of this file and its ancestors, for cycle detection.+ expandLines :: [FilePath] -> FilePath -> FilePath -> Text -> ExceptT String IO [(Text, (FilePath, Int))]+ expandLines ancestors dir1 file1 content1 = concat <$> mapM expandLine (zip [1..] $ T.lines content1)+ where+ expandLine (lnum, line) =+ case line of+ (T.stripPrefix "include " -> Just f) -> do+ let f' = dir1 </> T.unpack (T.strip f)+ err = throwError . includeErrorMsg file1 lnum line+ cf' <- liftIO $ canonicalizePath f'+ when (cf' `elem` ancestors) $ err $ "This included file forms a cycle: " ++ f'+ etxt <- liftIO $ tryIO $ readFilePortably f'+ case etxt of+ Left e -> err $ "Could not read this included file:\n" ++ show e+ Right txt -> expandLines (cf':ancestors) (takeDirectory f') f' txt+ _ -> return [(line, (file1, lnum))]++-- | Format an error message about a problematic include directive:+-- the directive's file path, line number and line excerpt, megaparsec-style,+-- followed by the given message.+includeErrorMsg :: FilePath -> Int -> Text -> String -> String+includeErrorMsg file lnum line msg = unlines+ [ file ++ ":" ++ show lnum ++ ":1:"+ , pad ++ " |"+ , lnumstr ++ " | " ++ T.unpack line+ , pad ++ " | ^"+ , msg+ ]+ where+ lnumstr = show lnum+ pad = replicate (length lnumstr) ' '++-- defaultRulesText :: FilePath -> Text+-- defaultRulesText _csvfile = T.pack $ unlines+-- ["# hledger csv conversion rules" -- for " ++ csvFileFor (takeFileName csvfile)+-- ,"# cf http://hledger.org/hledger.html#csv"+-- ,""+-- ,"account1 assets:bank:checking"+-- ,""+-- ,"fields date, description, amount1"+-- ,""+-- ,"#skip 1"+-- ,"#newest-first"+-- ,""+-- ,"#date-format %-d/%-m/%Y"+-- ,"#date-format %-m/%-d/%Y"+-- ,"#date-format %Y-%h-%d"+-- ,""+-- ,"#currency $"+-- ,""+-- ,"if ITUNES"+-- ," account2 expenses:entertainment"+-- ,""+-- ,"if (TO|FROM) SAVINGS"+-- ," account2 assets:bank:savings\n"+-- ]++-- | An error-throwing IO action that parses this text as CSV conversion rules+-- and runs some extra validation checks. The file path is used in error messages.+-- The lines' sources, as returned by expandIncludes, are used to report+-- errors in included files at the right file and line number.+parseAndValidateCsvRules :: FilePath -> [(FilePath, Int)] -> T.Text -> Either String CsvRules+parseAndValidateCsvRules rulesfile sourcelines s =+ case parseCsvRules rulesfile s of+ Left err -> Left $ errorBundlePretty $ fixErrorSourcePosition sourcelines s $ finalizeCustomErrorBundle err+ Right rules -> first ((rulesfile <> ":\n") <>) $ validateCsvRules $ translateRulePositions sourcelines rules++-- | Translate the rules' recorded source positions, which are line numbers+-- in the include-expanded rules text (see expandIncludes), to positions in+-- the original rules files, using the line sources returned by expandIncludes.+translateRulePositions :: [(FilePath, Int)] -> CsvRules -> CsvRules+translateRulePositions sourcelines rules =+ rules{ rassignments = map translate $ rassignments rules+ , rconditionalblocks = cbs+ , rblocksassigning = mkBlocksAssigning cbs+ }+ where+ cbs = [cb{cbAssignments = map translate $ cbAssignments cb, cbPos = translatePos $ cbPos cb} | cb <- rconditionalblocks rules]+ translate a = a{faPos = translatePos $ faPos a}+ translatePos p = p >>= \(_,l) -> atMay sourcelines (l-1)++-- | Adjust this parse error bundle's position state, using the line sources+-- returned by expandIncludes, so that the (first) error is reported at the+-- right file and line number even when it is in text that was inlined from+-- an included rules file. The bundle should already have been adjusted by+-- finalizeCustomErrorBundle, and the given text should be the expanded rules+-- text that was parsed.+fixErrorSourcePosition :: [(FilePath, Int)] -> T.Text -> HledgerParseErrors -> HledgerParseErrors+fixErrorSourcePosition sourcelines s bundle =+ case msource of+ Nothing -> bundle+ Just (sourcefile, sourceline) ->+ bundle{bundlePosState = (bundlePosState bundle)+ { pstateInput = T.drop linestartoffset s+ , pstateOffset = linestartoffset+ , pstateSourcePos = SourcePos sourcefile (mkPos sourceline) (mkPos 1)+ , pstateLinePrefix = ""+ }}+ where+ erroroffset = errorOffset $ NE.head $ bundleErrors bundle+ textbeforeerror = T.take erroroffset s+ expandedlinenum = T.count "\n" textbeforeerror + 1+ linestartoffset = T.length textbeforeerror - T.length (T.takeWhileEnd (/= '\n') textbeforeerror)+ msource = case atMay sourcelines (expandedlinenum - 1) of+ Just source -> Just source+ -- at end of input, just after the last line: report the line after the last line's source+ Nothing -> (\(file, lnum) -> (file, lnum + 1)) <$> lastMay sourcelines++instance ShowErrorComponent String where+ showErrorComponent = id++-- | Parse this text as CSV conversion rules. The file path is for error messages.+parseCsvRules :: FilePath -> T.Text -> Either (ParseErrorBundle T.Text HledgerParseErrorData) CsvRules+-- parseCsvRules rulesfile s = runParser csvrulesfile nullrules{baseAccount=takeBaseName rulesfile} rulesfile s+parseCsvRules = runParser (evalStateT rulesp defrules)++-- | Return the validated rules, or an error.+validateCsvRules :: CsvRules -> Either String CsvRules+validateCsvRules rules = do+ unless (isAssigned "date") $ Left "Please specify (at top level) the date field. Eg: date %1"+ Right rules+ where+ isAssigned f = isJust $ hledgerField rules [] f++--- *** rules types+_RULES_TYPES__________________________________________ = undefined++-- | A set of data definitions and account-matching patterns sufficient to+-- convert a particular CSV data file into meaningful journal transactions.+data CsvRules' a = CsvRules' {+ rdirectives :: [(DirectiveName,Text)],+ -- ^ top-level rules, as (keyword, value) pairs+ rcsvfieldindexes :: [(CsvFieldName, CsvFieldIndex)],+ -- ^ csv field names and their column number, if declared by a fields list+ rassignments :: [FieldAssignment],+ -- ^ top-level assignments to hledger fields+ rconditionalblocks :: [ConditionalBlock],+ -- ^ conditional blocks (AKA "if rules"), which containing additional assignments/rules to apply to matched csv records+ rblocksassigning :: a -- (String -> [ConditionalBlock])+ -- ^ all conditional blocks which can potentially assign field with a given name (memoized)+}++-- | Type used by parsers. Directives, assignments and conditional blocks+-- are in the reverse order compared to what is in the file and rblocksassigning is non-functional,+-- could not be used for processing CSV records yet+type CsvRulesParsed = CsvRules' ()++-- | Type used after parsing is done. Directives, assignments and conditional blocks+-- are in the same order as they were in the input file and rblocksassigning is functional.+-- Ready to be used for CSV record processing+type CsvRules = CsvRules' (Text -> [ConditionalBlock]) -- XXX simplify++instance Eq CsvRules where+ r1 == r2 = (rdirectives r1, rcsvfieldindexes r1, rassignments r1) ==+ (rdirectives r2, rcsvfieldindexes r2, rassignments r2)++-- Custom Show instance used for debug output: omit the rblocksassigning field, which isn't showable.+instance Show CsvRules where+ show r = "CsvRules { rdirectives = " ++ show (rdirectives r) +++ ", rcsvfieldindexes = " ++ show (rcsvfieldindexes r) +++ ", rassignments = " ++ show (rassignments r) +++ ", rconditionalblocks = " ++ show (rconditionalblocks r) +++ " }"++type CsvRulesParser a = StateT CsvRulesParsed SimpleTextParser a++-- | The keyword of a CSV rule - "fields", "skip", "if", etc.+type DirectiveName = Text++-- | CSV field name.+type CsvFieldName = Text++-- | 1-based CSV column number.+type CsvFieldIndex = Int++-- | Percent symbol followed by a CSV field name or column number. Eg: %date, %1.+type CsvFieldReference = Text++-- | One of the standard hledger fields or pseudo-fields that can be assigned to.+-- Eg date, account1, amount, amount1-in, date-format.+type HledgerFieldName = Text++-- | A text value to be assigned to a hledger field, possibly+-- containing csv field references to be interpolated.+type FieldTemplate = Text++-- | An assignment to a hledger field: the field name, the value template,+-- and the rules file position where it was written, useful in error messages.+-- The position is not part of a rule's identity: it is ignored when comparing.+data FieldAssignment = FieldAssignment {+ faName :: HledgerFieldName+ ,faTemplate :: FieldTemplate+ ,faPos :: Maybe (FilePath, Int) -- ^ rules file and line number, if known+ } deriving (Show)++instance Eq FieldAssignment where+ a == b = (faName a, faTemplate a) == (faName b, faTemplate b)++-- | Make a field assignment with unknown source position (used in tests).+fa :: HledgerFieldName -> FieldTemplate -> FieldAssignment+fa n t = FieldAssignment n t Nothing++-- | A reference to a regular expression match group. Eg \1.+type MatchGroupReference = Text++-- | A %{...} expression in a field assignment's value, eg %{upper(%desc)}.+data TemplateExpr =+ TECall Text [TemplateExpr] -- ^ a built-in function call+ | TEField CsvFieldReference -- ^ a csv field reference, eg %desc+ | TEHledgerField HledgerFieldName -- ^ a hledger field reference, eg comment+ | TEMatch MatchGroupReference -- ^ a match group reference, eg \1+ | TEString Text -- ^ a double-quoted string+ | TENumber Int -- ^ an integer+ deriving (Show)++-- | A built-in function usable in template expressions.+data TemplateFunction = TemplateFunction {+ tfName :: Text+ ,tfArity :: (Int, Maybe Int) -- ^ minimum and (if limited) maximum number of arguments+ ,tfCheck :: [TemplateExpr] -> Maybe String -- ^ further checks on the arguments as written, returning an error message+ ,tfApply :: [Text] -> Text -- ^ the implementation, applied to the evaluated arguments+ }++-- | A strptime date parsing pattern, as supported by Data.Time.Format.+type DateFormat = Text++-- | A representation of a matcher's prefix, which indicates how it should be+-- interpreted or combined with other matchers.+data MatcherPrefix =+ Or -- ^ no prefix+ | And -- ^ &&+ | Not -- ^ !+ | AndNot -- ^ && !+ deriving (Show, Eq)++dbgShowMatcherPrefix Or = ""+dbgShowMatcherPrefix And = "&&"+dbgShowMatcherPrefix Not = "&&"+dbgShowMatcherPrefix AndNot = "&& !"++-- | A single test for matching a CSV record, in one way or another.+data Matcher =+ RecordMatcher MatcherPrefix Regexp -- ^ match if this regexp matches the overall CSV record+ | FieldMatcher MatcherPrefix CsvFieldReference Regexp -- ^ match if this regexp matches the referenced CSV field's value+ deriving (Show, Eq)++matcherPrefix :: Matcher -> MatcherPrefix+matcherPrefix (RecordMatcher prefix _) = prefix+matcherPrefix (FieldMatcher prefix _ _) = prefix++matcherSetPrefix :: MatcherPrefix -> Matcher -> Matcher+matcherSetPrefix p (RecordMatcher _ r) = RecordMatcher p r+matcherSetPrefix p (FieldMatcher _ f r) = FieldMatcher p f r++dbgShowMatcher (RecordMatcher Or r) = show $ reString r+dbgShowMatcher (RecordMatcher p r) = unwords [dbgShowMatcherPrefix p, show $ reString r]+dbgShowMatcher (FieldMatcher Or f r) = unwords [T.unpack f, show $ reString r]+dbgShowMatcher (FieldMatcher p f r) = unwords [dbgShowMatcherPrefix p, T.unpack f, show $ reString r]++-- | A conditional block: a set of CSV record matchers, and a sequence+-- of rules which will be enabled only if one or more of the matchers+-- succeeds.+--+-- Four types of rule are allowed inside conditional blocks: field+-- assignments, skip, end, merge. (A skip, end or merge rule is stored+-- as if it was a field assignment, and executed in+-- applyConditionalSkips/applyMergeRules. XXX)+data ConditionalBlock = CB {+ cbMatchers :: [Matcher]+ ,cbAssignments :: [FieldAssignment]+ ,cbPos :: Maybe (FilePath, Int) -- ^ rules file and line number of the if (or ifs table row), if known+ } deriving (Show)++instance Eq ConditionalBlock where+ a == b = (cbMatchers a, cbAssignments a) == (cbMatchers b, cbAssignments b)++dbgShowConditionalBlock :: ConditionalBlock -> String+dbgShowConditionalBlock cb =+ maybe "" (\(f,l) -> f ++ ":" ++ show l ++ ": ") (cbPos cb)+ ++ unwords (map dbgShowMatcher $ cbMatchers cb)++defrules :: CsvRulesParsed+defrules = CsvRules' {+ rdirectives=[],+ rcsvfieldindexes=[],+ rassignments=[],+ rconditionalblocks=[],+ rblocksassigning = ()+ }++-- | Create CsvRules from the content parsed out of the rules file+mkrules :: CsvRulesParsed -> CsvRules+mkrules rules =+ let conditionalblocks = reverse $ rconditionalblocks rules+ in+ CsvRules' {+ rdirectives=reverse $ rdirectives rules,+ rcsvfieldindexes=rcsvfieldindexes rules,+ rassignments=reverse $ rassignments rules,+ rconditionalblocks=conditionalblocks,+ rblocksassigning = mkBlocksAssigning conditionalblocks+ }++-- | Make the (possibly memoized) function looking up the conditional blocks+-- which can potentially assign a given field.+mkBlocksAssigning :: [ConditionalBlock] -> (Text -> [ConditionalBlock])+mkBlocksAssigning conditionalblocks =+ maybeMemo (\f -> filter (any ((==f).faName) . cbAssignments) conditionalblocks)+ where maybeMemo = if length conditionalblocks >= 15 then memo else id++--- *** rules parsers+_RULES_PARSING__________________________________________ = undefined++{-+Grammar for the CSV conversion rules, more or less:++RULES: RULE*++RULE: ( SOURCE | ARCHIVE | FIELD-LIST | FIELD-ASSIGNMENT | CONDITIONAL-BLOCK | SKIP | TIMEZONE | NEWEST-FIRST | INTRA-DAY-REVERSED | DATE-FORMAT | DECIMAL-MARK | COMMENT | BLANK ) NEWLINE++SOURCE: source SPACE FILEPATH++ARCHIVE: archive++FIELD-LIST: fields SPACE FIELD-NAME ( SPACE? , SPACE? FIELD-NAME )*++FIELD-NAME: QUOTED-FIELD-NAME | BARE-FIELD-NAME++QUOTED-FIELD-NAME: " (any CHAR except double-quote)+ "++BARE-FIELD-NAME: (any CHAR except space, tab, #, ;)+++FIELD-ASSIGNMENT: JOURNAL-FIELD ASSIGNMENT-SEPARATOR FIELD-VALUE++JOURNAL-FIELD: date | date2 | status | code | description | comment | account1 | account2 | amount | JOURNAL-PSEUDO-FIELD++JOURNAL-PSEUDO-FIELD: amount-in | amount-out | currency++ASSIGNMENT-SEPARATOR: SPACE | ( : SPACE? )++FIELD-VALUE: VALUE (possibly containing CSV-FIELD-REFERENCEs and REGEX-MATCHGROUP-REFERENCEs)++CSV-FIELD-REFERENCE: % CSV-FIELD++REGEX-MATCHGROUP-REFERENCE: \ DIGIT+++CSV-FIELD: ( FIELD-NAME | FIELD-NUMBER ) (corresponding to a CSV field)++FIELD-NUMBER: DIGIT+++CONDITIONAL-BLOCK: if ( FIELD-MATCHER NEWLINE )+ INDENTED-BLOCK++FIELD-MATCHER: ( CSV-FIELD-NAME SPACE? )? ( MATCHOP SPACE? )? PATTERNS++MATCHOP: ~++PATTERNS: ( NEWLINE REGEXP )* REGEXP++INDENTED-BLOCK: ( SPACE ( FIELD-ASSIGNMENT | COMMENT ) NEWLINE )+++REGEXP: ( NONSPACE CHAR* ) SPACE?++VALUE: SPACE? ( CHAR* ) SPACE?++COMMENT: SPACE? COMMENT-CHAR VALUE++COMMENT-CHAR: # | ;++NONSPACE: any CHAR not a SPACE-CHAR++BLANK: SPACE?++SPACE: SPACE-CHAR+++SPACE-CHAR: space | tab++CHAR: any character except newline++DIGIT: 0-9++-}++addDirective :: (DirectiveName, Text) -> CsvRulesParsed -> CsvRulesParsed+addDirective d r = r{rdirectives=d:rdirectives r}++addAssignment :: FieldAssignment -> CsvRulesParsed -> CsvRulesParsed+addAssignment a r = r{rassignments=a:rassignments r}++setIndexesAndAssignmentsFromList :: Maybe (FilePath, Int) -> [CsvFieldName] -> CsvRulesParsed -> CsvRulesParsed+setIndexesAndAssignmentsFromList pos fs = addAssignmentsFromList fs . setCsvFieldIndexesFromList fs+ where+ setCsvFieldIndexesFromList :: [CsvFieldName] -> CsvRulesParsed -> CsvRulesParsed+ setCsvFieldIndexesFromList fs' r = r{rcsvfieldindexes=zip fs' [1..]}++ addAssignmentsFromList :: [CsvFieldName] -> CsvRulesParsed -> CsvRulesParsed+ addAssignmentsFromList fs' r = foldl' maybeAddAssignment r journalfieldnames+ where+ maybeAddAssignment rules f = (maybe id addAssignmentFromIndex $ elemIndex f fs') rules+ where+ addAssignmentFromIndex i = addAssignment $ FieldAssignment f (T.pack $ '%':show (i+1)) pos++addConditionalBlock :: ConditionalBlock -> CsvRulesParsed -> CsvRulesParsed+addConditionalBlock b r = r{rconditionalblocks=b:rconditionalblocks r}++addConditionalBlocks :: [ConditionalBlock] -> CsvRulesParsed -> CsvRulesParsed+addConditionalBlocks bs r = r{rconditionalblocks=bs++rconditionalblocks r}++rulesp :: CsvRulesParser CsvRules+rulesp = do+ input <- getInput+ _ <- many $ choice+ [blankorcommentlinep <?> "blank or comment line"+ ,(directivep >>= modify' . addDirective) <?> "directive"+ ,(do pos <- getRulesPos+ fieldnamelistp >>= modify' . setIndexesAndAssignmentsFromList pos) <?> "field name list"+ ,(fieldassignmentp >>= modify' . addAssignment) <?> "field assignment"+ -- conditionalblockp backtracks because it shares "if" prefix with conditionaltablep.+ ,try (conditionalblockp >>= modify' . addConditionalBlock) <?> "if rule"+ -- 'reverse' is there to ensure that conditions are added in the order they listed in the file+ ,(conditionaltablep >>= modify' . addConditionalBlocks . reverse) <?> "ifs table"+ ]+ eof+ rules <- mkrules <$> get+ checkFieldReferenceLoops input rules+ return rules++-- | Check that the hledger field references in %{...} expressions don't form a loop,+-- where a field's value would depend on itself through other fields.+-- (A field's own name refers to its previous value, which is fine.)+-- All assignments are considered, whether or not they could apply to the same CSV record.+-- A loop is reported at the last-written assignment involved in it.+-- This takes the rules text, from which the rules were parsed, to calculate the error position.+checkFieldReferenceLoops :: Text -> CsvRules -> CsvRulesParser ()+checkFieldReferenceLoops input rules =+ case [loop | CyclicSCC loop <- stronglyConnComp graph] of+ [] -> return ()+ loop:_ -> customFailure $ parseErrorAt (lineOffset $ maybe 1 snd $ faPos =<< lastassignment) $+ "these hledger fields' values depend on each other in a loop: " <> T.unpack (T.intercalate ", " $ sort loop)+ where+ lastassignment = lastMay $ sortOn (fmap snd . faPos)+ [a | a <- assignments, faName a `elem` loop, any (`elem` loop) (otherRefs a)]+ where+ assignments = rassignments rules ++ concatMap cbAssignments (rconditionalblocks rules)+ otherRefs a = filter (/= faName a) $ templateHledgerFieldRefs $ faTemplate a+ graph = [ (f, f, nub $ concatMap otherRefs as)+ | as@(a:_) <- groupOn faName $ sortOn faName assignments, let f = faName a ]+ -- the offset of the first non-space character on this line of the input+ lineOffset l = sum (map ((+1) . T.length) before) + maybe 0 (T.length . T.takeWhile isSpace) (headMay rest)+ where (before, rest) = splitAt (l-1) $ T.lines input++blankorcommentlinep :: CsvRulesParser ()+blankorcommentlinep = lift (dbgparse 8 "trying blankorcommentlinep") >> choiceInState [blanklinep, commentlinep]++blanklinep :: CsvRulesParser ()+blanklinep = lift skipNonNewlineSpaces >> newline >> return () <?> "blank line"++commentlinep :: CsvRulesParser ()+commentlinep = lift skipNonNewlineSpaces >> commentcharp >> lift restofline >> return () <?> "comment line"++commentcharp :: CsvRulesParser Char+commentcharp = oneOf (";#" :: [Char])++directivep :: CsvRulesParser (DirectiveName, Text)+directivep = (do+ lift $ dbgparse 8 "trying directive"+ doff <- getOffset+ d <- choiceInState $ map (lift . string) directives+ (voff, v) <- (((char ':' >> lift (many spacenonewline)) <|> lift (some spacenonewline)) >> ((,) <$> getOffset <*> directivevalp))+ <|> (optional (char ':') >> lift skipNonNewlineSpaces >> lift eolof >> return (0, ""))+ checkDirectiveValue voff d v+ checkSingleSource doff d+ return (d, v)+ ) <?> "directive"++-- | Check the value of directives which take a specific kind of value, when parsing,+-- so that a bad value is reported with its position in the rules file.+-- (The same checks are made where the values are used, for rules built without parsing.)+-- Surrounding whitespace is ignored here, so as not to reject old rules files+-- which loaded before (eg with a trailing space after an unused balance-type).+checkDirectiveValue :: Int -> DirectiveName -> Text -> CsvRulesParser ()+checkDirectiveValue off d v0 = let v = T.strip v0 in case d of+ _ | T.null v -> return () -- (an empty value is checked, if needed, where it's used)+ "decimal-mark" | not (isValidDecimalMark v) ->+ bad $ "decimal-mark's argument should be \".\" or \",\" (not \"" <> v <> "\")"+ "skip" | isNothing (readMay (T.unpack v) :: Maybe Int) ->+ bad $ "skip's argument should be a number of lines, or nothing (not \"" <> v <> "\")"+ "balance-type" | isNothing (parseBalanceAssertionType $ T.unpack v) ->+ bad $ "balance-type \"" <> v <> "\" is invalid. Use =, ==, =* or ==*."+ _ -> return ()+ where+ bad = customFailure . parseErrorAt off . T.unpack+ isValidDecimalMark t = case T.uncons t of+ Just (c, rest) -> T.null rest && isDecimalMark c+ Nothing -> False++-- | Report an error if this is a second source rule (#2862).+-- Only one source rule is used, so others would be silently ignored.+checkSingleSource :: Int -> DirectiveName -> CsvRulesParser ()+checkSingleSource off d = do+ seen <- gets $ elem "source" . map fst . rdirectives+ when (d == "source" && seen) $ customFailure $ parseErrorAt off $ unlines+ ["only one source rule is allowed, but this is another one."+ ,"To read several data files, use one rules file for each"+ ,"(they can share common rules with include)."]++directives :: [Text]+directives =+ ["source"+ ,"archive"+ ,"encoding"+ ,"date-format"+ ,"decimal-mark"+ ,"separator"+ -- ,"default-account"+ -- ,"default-currency"+ ,"skip"+ ,"timezone"+ ,"newest-first"+ ,"intra-day-reversed"+ , "balance-type"+ ]++directivevalp :: CsvRulesParser Text+directivevalp = T.pack <$> anySingle `manyTill` lift eolof++fieldnamelistp :: CsvRulesParser [CsvFieldName]+fieldnamelistp = (do+ lift $ dbgparse 8 "trying fieldnamelist"+ string "fields"+ optional $ char ':'+ lift skipNonNewlineSpaces1+ let separator = lift skipNonNewlineSpaces >> char ',' >> lift skipNonNewlineSpaces+ f <- fromMaybe "" <$> optional fieldnamep+ fs <- some $ (separator >> fromMaybe "" <$> optional fieldnamep)+ lift restofline+ return . map T.toLower $ f:fs+ ) <?> "field name list"++fieldnamep :: CsvRulesParser Text+fieldnamep = quotedfieldnamep <|> barefieldnamep++quotedfieldnamep :: CsvRulesParser Text+quotedfieldnamep =+ char '"' *> takeWhile1P Nothing (`notElem` ("\"\n:;#~" :: [Char])) <* char '"'++barefieldnamep :: CsvRulesParser Text+barefieldnamep = takeWhile1P Nothing (`notElem` (" \t\n,;#~" :: [Char]))++-- | Get the current source position as a rules file position: the file path+-- and line number. When parsing rules with included files, this is a position+-- in the expanded text; it should be translated to the original file and line+-- with translateRulePositions after parsing.+getRulesPos :: CsvRulesParser (Maybe (FilePath, Int))+getRulesPos = do+ SourcePos f l _ <- lift getSourcePos+ return $ Just (f, unPos l)++fieldassignmentp :: CsvRulesParser FieldAssignment+fieldassignmentp = do+ lift $ dbgparse 8 "trying fieldassignmentp"+ pos <- getRulesPos+ f <- journalfieldnamep+ v <- choiceInState [ assignmentseparatorp >> fieldvalp+ , lift eolof >> return ""+ ]+ return $ FieldAssignment f v pos+ <?> "field assignment"++journalfieldnamep :: CsvRulesParser Text+journalfieldnamep = do+ lift (dbgparse 8 "trying journalfieldnamep")+ choiceInState $ map (lift . string) journalfieldnames++maxpostings = 99++-- Transaction fields and pseudo fields for CSV conversion.+-- Names must precede any other name they contain, for the parser+-- (amount-in before amount; date2 before date). TODO: fix+journalfieldnames =+ concat [[ "account" <> i+ ,"amount" <> i <> "-in"+ ,"amount" <> i <> "-out"+ ,"amount" <> i+ ,"balance" <> i+ ,"comment" <> i+ ,"currency" <> i+ ] | x <- [maxpostings, (maxpostings-1)..1], let i = T.pack $ show x]+ +++ ["amount-in"+ ,"amount-out"+ ,"amount"+ ,"balance"+ ,"code"+ ,"comment"+ ,"currency"+ ,"date2"+ ,"date"+ ,"description"+ ,"status"+ ,"skip" -- skip, end and merge are not really fields, but we list them here to allow conditional rules that skip or merge records+ ,"end"+ ,"merge"+ ]++assignmentseparatorp :: CsvRulesParser ()+assignmentseparatorp = do+ lift $ dbgparse 8 "trying assignmentseparatorp"+ _ <- choiceInState [ lift skipNonNewlineSpaces >> char ':' >> lift skipNonNewlineSpaces+ , lift skipNonNewlineSpaces1+ ]+ return ()++fieldvalp :: CsvRulesParser Text+fieldvalp = do+ lift $ dbgparse 8 "trying fieldvalp"+ T.concat <$> lift (templatepartp (/= '\n')) `manyTill` lift eolof++-- | Parse part of a field assignment's value, returning it as written:+-- a %{...} expression (which is checked here, so that errors are reported+-- with their position in the rules file), or other text whose characters+-- satisfy the predicate.+templatepartp :: (Char -> Bool) -> TextParser m Text+templatepartp ok =+ takeWhile1P Nothing (\c -> ok c && c /= '%')+ <|> fst <$> P.match templateexprp+ <|> T.singleton <$> satisfy ok++-- | Parse a %{...} expression. Unknown functions, wrong numbers of+-- arguments, and other invalid arguments are reported as parse errors.+templateexprp :: TextParser m TemplateExpr+templateexprp = string "%{" *> region asFancy (sp *> termp <* sp <* char '}')+ where+ -- Make syntax errors "fancy", so that an enclosing try followed by+ -- an alternative doesn't replace them with the alternative's error+ -- (megaparsec 9.8+ prefers the error at the alternative's start).+ asFancy e@TrivialError{} = FancyError (errorOffset e) $ S.singleton $ ErrorFail $+ T.unpack $ T.stripEnd $ T.pack $ parseErrorTextPretty e+ asFancy e = e+ sp = skipNonNewlineSpaces+ termp = choice+ [namedp+ ,TEField <$> templatefieldrefp+ ,TEMatch <$> templatematchrefp+ ,TEString <$> stringp+ ,TENumber <$> numberp+ ] <?> "function call, hledger field name, CSV field reference, match group reference, double-quoted string or number"+ -- a function call, or a bare name, which refers to a hledger field+ namedp = do+ off <- getOffset+ name <- T.cons <$> satisfy isAsciiLower <*> takeWhileP Nothing (\c -> isAsciiLower c || isDigit c || c == '_')+ margs <- optional $ try (sp *> char '(') *> sp *> (termp <* sp) `sepBy` (char ',' *> sp) <* char ')'+ let check = either (customFailure . parseErrorAt off) return+ case margs of+ Just args -> check (checkTemplateCall name args) >> return (TECall name args)+ Nothing -> check (checkHledgerFieldReference name) >> return (TEHledgerField name)+ -- \" and \\ are escapes; other backslashes are kept, so "\1" can be a replace backreference+ stringp = char '"' *> (T.concat <$> many strpartp) <* char '"' <?> "double-quoted string"+ strpartp = takeWhile1P Nothing (`notElem` ['"', '\\', '\n'])+ <|> (char '\\' *> option "\\" (T.singleton <$> oneOf ['"', '\\']))+ numberp = do+ sign <- option "" (string "-")+ digits <- takeWhile1P (Just "digit") isDigit+ maybe (fail "invalid number") return $ readMay $ T.unpack $ sign <> digits++-- | Check a template function call's name and arguments.+checkTemplateCall :: Text -> [TemplateExpr] -> Either String ()+checkTemplateCall name args = case lookupTemplateFunction name of+ Nothing -> Left $ "unknown function \"" <> T.unpack name <> "\" (known functions: "+ <> T.unpack (T.intercalate ", " $ map tfName templateFunctions) <> ")"+ Just TemplateFunction{tfArity=(lo,mhi), tfCheck}+ | n < lo || maybe False (n >) mhi ->+ Left $ printf "%s takes %s, but was given %d" name (arity lo mhi) n+ | otherwise -> maybe (Right ()) Left $ tfCheck args+ where+ n = length args+ arity :: Int -> Maybe Int -> String+ arity lo (Just hi) | lo == hi = plural lo+ | otherwise = printf "%d to %d arguments" lo hi+ arity lo Nothing = printf "%d or more arguments" lo+ plural 1 = "1 argument"+ plural k = printf "%d arguments" k++-- | Check that a bare name in a %{...} expression is a hledger field which can be referenced.+-- skip, end and merge are actions, not values, and are kept free for use as keywords later;+-- they get the unknown field error. amount-in/amount-out are not supported.+checkHledgerFieldReference :: Text -> Either String ()+checkHledgerFieldReference name+ | isJust $ lookupTemplateFunction name =+ Left $ printf "%s is a function; it should be followed by parentheses, eg %s(...)" name name+ | name `elem` journalfieldnames, name `notElem` ["skip", "end", "merge"] = Right ()+ | otherwise = Left $ printf+ "unknown hledger field \"%s\". To refer to a CSV field, write %%%s. The hledger fields are: %s"+ name name ("date, date2, status, code, description, comment, amount, balance, currency, and commentN, accountN, amountN, balanceN, currencyN (N = 1-99)" :: String)++lookupTemplateFunction :: Text -> Maybe TemplateFunction+lookupTemplateFunction name = find ((== name) . tfName) templateFunctions++-- | The built-in functions available in %{...} expressions.+-- All arguments and results are text.+templateFunctions :: [TemplateFunction]+templateFunctions =+ [TemplateFunction "upper" (1, Just 1) noCheck (T.toUpper . arg1)+ ,TemplateFunction "lower" (1, Just 1) noCheck (T.toLower . arg1)+ ,TemplateFunction "capitalize" (1, Just 1) noCheck (capitalize . arg1)+ ,TemplateFunction "capitalise" (1, Just 1) noCheck (capitalize . arg1)+ ,TemplateFunction "trim" (1, Just 1) noCheck (T.strip . arg1)+ ,TemplateFunction "negate" (1, Just 1) noCheck (signedPart (simplifySign . negateStr) . arg1)+ ,TemplateFunction "abs" (1, Just 1) noCheck (signedPart (absStr . simplifySign) . arg1)+ ,TemplateFunction "concat" (1, Nothing) noCheck T.concat+ ,TemplateFunction "join" (2, Nothing) noCheck joinFn+ ,TemplateFunction "default" (1, Nothing) noCheck (headDef "" . filter nonBlank)+ ,TemplateFunction "replace" (3, Just 3) checkReplace replaceFn+ ,TemplateFunction "substr" (2, Just 3) checkSubstr substrFn+ ]+ where+ noCheck = const Nothing+ arg1 = headDef ""+ nonBlank = not . T.null . T.strip+ -- join(SEPARATOR, TEXT, ...): the texts which are not empty or all whitespace, separated by SEPARATOR+ joinFn (sep:ts) = T.intercalate sep $ filter nonBlank ts+ joinFn [] = ""+ -- upper-case the first letter of each whitespace-separated word, and lower-case the rest+ capitalize = snd . T.mapAccumL (\atstart c -> (isSpace c, if atstart then toUpper c else toLower c)) True+ absStr t = fromMaybe t $ T.stripPrefix "-" t+ -- Apply a sign-changing function to an amount text, or to the part+ -- after a commodity symbol written before the sign (eg the -5 in $-5).+ signedPart f t = case T.break (\c -> isDigit c || isSign c) t of+ (sym, rest) | not (T.null sym), Just (c, _) <- T.uncons rest, isSign c -> sym <> f rest+ _ -> f t+ where isSign c = c `elem` ['-', '+', '(']++ -- replace(TEXT, "REGEX", REPLACEMENT): replace all case-insensitive matches of REGEX,+ -- REPLACEMENT may use \N to insert REGEX's match groups.+ checkReplace [_, TEString r, repl] = case toRegexCI r of+ Left e -> Just e+ Right _ | TEString t <- repl, maxBackref t > regexGroupCount r ->+ Just $ "replace's replacement refers to match group \\" <> show (maxBackref t)+ <> ", but the regular expression has only " <> show (regexGroupCount r) <> " group(s)"+ _ -> Nothing+ checkReplace _ = Just "replace's second argument (the regular expression) should be a double-quoted string"+ replaceFn (s:r:repl:_) = either (const s) T.pack $ do+ re <- toRegexCI r+ regexReplaceUnmemo re (T.unpack repl) (T.unpack s)+ replaceFn as = arg1 as++ -- substr(TEXT, START, LENGTH): LENGTH characters (or all) from position START,+ -- where 1 is the first character and -1 the last (as in SQLite and Oracle).+ checkSubstr (_:TENumber start:rest) | start /= 0, all isLength rest = Nothing+ where isLength (TENumber n) = n >= 0+ isLength _ = False+ checkSubstr _ = Just "substr's position should be a number other than 0 (1 is the first character, -1 the last), and its length a number, at least 0"+ substrFn (s:start:rest) =+ let i = readDef 1 (T.unpack start)+ s' = if i < 0 then T.takeEnd (negate i) s else T.drop (i - 1) s+ in case rest of+ len:_ -> T.take (readDef (T.length s') (T.unpack len)) s'+ [] -> s'+ substrFn as = arg1 as++ -- the highest \N backreference in a replacement pattern+ maxBackref = go . T.unpack+ where+ go ('\\':cs) | (ds@(_:_), rest) <- span isDigit cs = max (readDef 0 ds) (go rest)+ go (_:cs) = go cs+ go [] = 0++ -- the number of parenthesised groups in a regular expression+ -- (approximately: open parentheses not escaped or in a bracket expression)+ regexGroupCount :: Text -> Int+ regexGroupCount = go . T.unpack+ where+ go ('\\':_:cs) = go cs+ go ('[':cs) = go (skipBracket cs)+ go ('(':cs) = 1 + go cs+ go (_:cs) = go cs+ go [] = 0+ -- a ] at the start of a bracket expression (after any ^) is a literal+ skipBracket cs = let cs' = fromMaybe cs (T.unpack <$> T.stripPrefix "^" (T.pack cs))+ in drop 1 $ dropWhile (/= ']') $ drop 1 cs'++-- A conditional block: one or more matchers, one per line, followed by one or more indented rules.+conditionalblockp :: CsvRulesParser ConditionalBlock+conditionalblockp = do+ lift $ dbgparse 8 "trying conditionalblockp"+ -- "if\nMATCHER" or "if \nMATCHER" or "if MATCHER"+ start <- getOffset+ pos <- getRulesPos+ onifline <- string "if" >>( (newline >> return False)+ <|> (lift skipNonNewlineSpaces1 >> isNothing <$> optional newline))+ -- one or more matchers, one per line; with comment lines possibly interspersed.+ -- A matcher on the same line as "if" may begin with a comment character;+ -- on later lines, such lines are comments.+ let matcherlinep = try $ skipMany (try commentlinep) >> matcherp+ moff <- getOffset+ ms <- if onifline+ then (:) <$> matcherp <*> many matcherlinep+ else many matcherlinep+ when (null ms) $+ customFailure $ parseErrorAt moff $+ "start of if rule found, but no matchers afterward\n"+ ++ "(matchers should be on the same line as \"if\", or on the following lines.\n"+ ++ "Note: a line beginning with a comment character (# or ;) is a comment;\n"+ ++ "to match a leading comment character, escape it, eg \\#)"+ -- one or more indented assignments; with blank lines and comment lines+ -- (indented or not) possibly interspersed+ as <- catMaybes <$>+ many (choice+ [ blankorcommentlinep >> return Nothing+ , lift skipNonNewlineSpaces1 >>+ choice [ lift eolof >> return Nothing+ , fmap Just fieldassignmentp+ ]+ ])+ when (null as) $+ customFailure $ parseErrorAt start $ "start of if rule found, but no assignment rules afterward\n(assignment rules in an if rule should be indented)"+ return $ CB{cbMatchers=ms, cbAssignments=as, cbPos=pos}+ <?> "if rule"++-- An ifs table (AKA if table, conditional table): "ifs" (or "if") followed by separator, followed by some field names,+-- followed by many lines, each of which is either:+-- a comment line (possibly indented), or+-- one matcher, followed by field assignments (as many as there were fields in the header).+-- A blank line (possibly containing spaces) or end of file ends the table.+conditionaltablep :: CsvRulesParser [ConditionalBlock]+conditionaltablep = do+ lift $ dbgparse 8 "trying conditionaltablep"+ start <- getOffset+ string "if"+ -- "ifs" (preferred) allows spaces before the first delimiter;+ -- plain "if" does not, since a space there would start an if block+ ifs <- isJust <$> optional (char 's')+ when ifs $ lift skipNonNewlineSpaces+ sep <- lift (satisfy (\c -> not (isAlphaNum c || isSpace c)) <?> "delimiter (a punctuation character)")+ -- spaces are allowed around the field names+ fields <-(lift skipNonNewlineSpaces *> journalfieldnamep <* lift skipNonNewlineSpaces) `sepBy1` (char sep)+ newline+ body <- catMaybes <$> (flip manyTill (try blanklinep <|> lift eof) $+ choice [ try commentlinep >> return Nothing+ , fmap Just $ bodylinep sep fields+ ])+ when (null body) $+ customFailure $ parseErrorAt start $ "start of ifs table found, but no table rows afterward"+ return $ flip map body $ \(ms,vs,pos) ->+ -- values have surrounding whitespace removed, so they can be aligned; blank values don't assign+ CB{cbMatchers=ms, cbAssignments=[FieldAssignment f v pos | (f, v) <- zip fields (map T.strip vs), not $ T.null v], cbPos=pos}+ <?> "ifs table"+ where+ bodylinep :: Char -> [Text] -> CsvRulesParser ([Matcher],[FieldTemplate],Maybe (FilePath,Int))+ bodylinep sep fields = do+ off <- getOffset+ pos <- getRulesPos+ ms <- matcherp' (lookAhead . void . char $ sep) `manyTill` char sep+ -- separators inside %{...} expressions don't separate values+ vs <- lift $ (T.concat <$> many (templatepartp (\c -> c /= sep && c /= '\n'))) `sepBy` char sep <* eolof+ if (length vs /= length fields)+ then customFailure $ parseErrorAt off $ ((printf "line of ifs table should have %s, but this one has %d" (values $ length fields) (length vs)) :: String)+ else return (ms,vs,pos)+ where+ values :: Int -> String+ values 1 = "1 value"+ values n = show n <> " values"+++-- A single matcher, on one line.+-- This tries to parse first as a field matcher, then if that fails, as a whole-record matcher;+-- the goal was to not break legacy whole-record patterns that happened to look a bit like a field matcher+-- (eg, beginning with %, possibly preceded by & or !), or at least not to raise an error.+matcherp' :: CsvRulesParser () -> CsvRulesParser Matcher+matcherp' end = try (fieldmatcherp end) <|> recordmatcherp end++matcherp :: CsvRulesParser Matcher+matcherp = matcherp' (lift eolof)++-- A single whole-record matcher.+-- A pattern on the whole line, not beginning with a csv field reference.+recordmatcherp :: CsvRulesParser () -> CsvRulesParser Matcher+recordmatcherp end = do+ lift $ dbgparse 8 "trying recordmatcherp"+ -- pos <- currentPos+ -- _ <- optional (matchoperatorp >> lift skipNonNewlineSpaces >> optional newline)+ p <- matcherprefixp+ r <- regexp end+ return $ RecordMatcher p r+ -- when (null ps) $+ -- Fail.fail "start of record matcher found, but no patterns afterward\n(patterns should not be indented)"+ <?> "record matcher"++-- | A single matcher for a specific field. A csv field reference+-- (like %date or %1), and a pattern on the rest of the line,+-- optionally space-separated. Eg:+-- %description chez jacques+fieldmatcherp :: CsvRulesParser () -> CsvRulesParser Matcher+fieldmatcherp end = do+ lift $ dbgparse 8 "trying fieldmatcher"+ -- An optional fieldname (default: "all")+ -- f <- fromMaybe "all" `fmap` (optional $ do+ -- f' <- fieldnamep+ -- lift skipNonNewlineSpaces+ -- return f')+ p <- matcherprefixp+ f <- csvfieldreferencep <* lift skipNonNewlineSpaces+ -- optional operator.. just ~ (case insensitive infix regex) for now+ -- _op <- fromMaybe "~" <$> optional matchoperatorp+ lift skipNonNewlineSpaces+ r <- regexp end+ return $ FieldMatcher p f r+ <?> "field matcher"++matcherprefixp :: CsvRulesParser MatcherPrefix+matcherprefixp = do+ lift $ dbgparse 8 "trying matcherprefixp"+ (do+ char '&' >> optional (char '&') >> lift skipNonNewlineSpaces+ fromMaybe And <$> optional (char '!' >> lift skipNonNewlineSpaces >> return AndNot))+ <|> (char '!' >> lift skipNonNewlineSpaces >> return Not)+ <|> return Or++csvfieldreferencep :: CsvRulesParser CsvFieldReference+csvfieldreferencep = do+ lift $ dbgparse 8 "trying csvfieldreferencep"+ char '%'+ T.cons '%' . textQuoteIfNeeded <$> fieldnamep+ -- XXX this parses any generic field name, which may not actually be a valid CSV field name [#2289]++-- A single regular expression+regexp :: CsvRulesParser () -> CsvRulesParser Regexp+regexp end = do+ lift $ dbgparse 8 "trying regexp"+ -- notFollowedBy matchoperatorp+ c <- lift nonspace+ cs <- anySingle `manyTill` (double_ampersand <|> end)+ case toRegexCI . T.strip . T.pack $ c:cs of+ Left x -> Fail.fail $ "CSV parser: " ++ x+ Right x -> return x+ where+ double_ampersand = lookAhead . void $ string "&&"++-- -- A match operator, indicating the type of match to perform.+-- -- Currently just ~ meaning case insensitive infix regex match.+-- matchoperatorp :: CsvRulesParser String+-- matchoperatorp = fmap T.unpack $ choiceInState $ map string+-- ["~"+-- -- ,"!~"+-- -- ,"="+-- -- ,"!="+-- ]++_RULES_LOOKUP__________________________________________ = undefined++-- | Look up the value of a top-level directive.+-- If it is declared more than once, the last declaration wins,+-- like most other rules (but see getDirectiveFirstWins).+getDirective :: DirectiveName -> CsvRules -> Maybe FieldTemplate+getDirective directivename = lookup directivename . reverse . rdirectives++-- | Like getDirective, but if the directive is declared more than once,+-- the first declaration wins. Used for the skip directive.+getDirectiveFirstWins :: DirectiveName -> CsvRules -> Maybe FieldTemplate+getDirectiveFirstWins directivename = lookup directivename . rdirectives++-- | Look up the value (template) of a csv rule by rule keyword.+csvRule :: CsvRules -> DirectiveName -> Maybe FieldTemplate+csvRule rules = (`getDirective` rules)++-- | Look up the assignment (name, value template, rules file position)+-- which is effective for a hledger field, considering field list/field+-- assignment rules, the current record, and conditional rules.+hledgerFieldAssignment :: CsvRules -> CsvRecordGroup -> HledgerFieldName -> Maybe FieldAssignment+hledgerFieldAssignment rules record f = fst <$> lastMay (hledgerFieldAssignments rules record f)++-- | Look up the value template assigned to a hledger field by field+-- list/field assignment rules, taking into account the current record and+-- conditional rules.+hledgerField :: CsvRules -> CsvRecordGroup -> HledgerFieldName -> Maybe FieldTemplate+hledgerField rules record f = faTemplate <$> hledgerFieldAssignment rules record f++-- | Look up the final value assigned to a hledger field, with csv field+-- references, regular expression match group references and %{...} expressions interpolated.+--+-- In an assignment's %{...} expressions, the name of the field being assigned+-- gives the value from its previous assignment, and another hledger field's name+-- gives that field's final value. Both give "" if the field has no assignment.+hledgerFieldValue :: CsvRules -> CsvRecordGroup -> HledgerFieldName -> Maybe Text+hledgerFieldValue rules record = fieldValue S.empty+ where+ -- The value of field f. seen holds the fields whose values are being computed,+ -- so that a reference loop (which checkFieldReferenceLoops rejects) can't hang.+ fieldValue seen f = valueFrom $ reverse $ hledgerFieldAssignments rules record f+ where+ seen' = S.insert f seen+ -- the value from the first of these assignments, which are latest first+ valueFrom [] = Nothing+ valueFrom ((a, arules) : earlier) = Just $ renderTemplate arules record lookupField (faTemplate a)+ where+ previous = fromMaybe "" $ valueFrom earlier+ lookupField g+ | g == f = previous+ | g `S.member` seen' = ""+ | otherwise = fromMaybe "" $ fieldValue seen' g++maybeNegate :: MatcherPrefix -> Bool -> Bool+maybeNegate Not origbool = not origbool+maybeNegate _ origbool = origbool++-- | Given the conversion rules, a CSV record and a hledger field name, find all the+-- assignments to that field which apply to this record, in the order they take effect:+-- top-level ones, then those in matched if blocks, in rules file order.+-- The last one is the effective one.+-- Each is paired with the rules for rendering it: for an assignment in an if block,+-- rules with just that block, so that its match group references use that block's matchers.+--+-- Note conditional blocks' patterns are matched against an approximation of the+-- CSV record: all the field values, without enclosing quotes, comma-separated.+--+hledgerFieldAssignments :: CsvRules -> CsvRecordGroup -> HledgerFieldName -> [(FieldAssignment, CsvRules)]+hledgerFieldAssignments rules record f =+ [(a, rules) | a <- rassignments rules, faName a == f]+ ++ [(a, rules{rconditionalblocks = [cb]}) -- XXX handle rblocksassigning+ | cb <- dbg' $ filter (isBlockActive rules record) $ rblocksassigning rules f+ , a <- cbAssignments cb+ , faName a == f]+ where+ dbg' [] = []+ dbg' ms = dbg2Msg (+ " for the " ++ T.unpack f ++ " field, these if rules matched:"+ ++ concatMap (("\n " ++) . dbgShowConditionalBlock) ms+ ) ms++-- does this conditional block match the current csv record ?+isBlockActive :: CsvRules -> CsvRecordGroup -> ConditionalBlock -> Bool+isBlockActive rules record CB{..} = any (all matcherMatches) $ groupedMatchers cbMatchers+ where+ -- Does this individual matcher match the current csv record ?+ -- A matcher's target can be a specific CSV field, or the "whole record".+ --+ -- In the former case, note that the field reference must be either numeric or+ -- a csv field name declared by a `fields` rule; anything else will emit a warning to stderr+ -- (to reduce confusion when a hledger field name doesn't work; not an error, to avoid breaking legacy rules; see #2289).+ --+ -- In the latter case, the matched value will be a synthetic CSV record.+ -- Note this will not necessarily be the same as the original CSV record:+ -- the field separator will be comma, and quotes enclosing field values,+ -- and any whitespace outside those quotes, will be removed.+ -- (This means that a field containing a comma will now look like two fields.)+ --+ matcherMatches :: Matcher -> Bool+ matcherMatches = \case+ RecordMatcher prefix pat -> maybeNegate prefix $ match pat $ recordAsApproximateText record+ FieldMatcher prefix csvfieldref pat -> maybeNegate prefix $ match pat $+ fromMaybe "" $ replaceCsvFieldReference rules record csvfieldref+ -- (warn msg "") where msg = "if "<>T.unpack csvfieldref<>": this should be a name declared with 'fields', or %NUM"+ -- #2289: we'd like to warn the user when an unknown CSV field is being referenced,+ -- but it's useful to ignore it for easier reuse of rules files.+ where match p v = regexMatchText (dbg7 "regex" p) (dbg7 "value" v)++ -- | Group matchers into associative pairs based on prefix, e.g.:+ -- A+ -- & B+ -- C+ -- D+ -- & E+ -- => [[A, B], [C], [D, E]]+ -- & ! M (and not M) are converted to ! M (not M) within the and groups.+ groupedMatchers :: [Matcher] -> [[Matcher]]+ groupedMatchers [] = []+ groupedMatchers (m:ms) = (m:ands) : groupedMatchers rest+ where+ (andandnots, rest) = span (\a -> matcherPrefix a `elem` [And, AndNot]) ms+ ands = [matcherSetPrefix p a | a <- andandnots, let p = if matcherPrefix a == AndNot then Not else And]++-- | Convert a CSV record group to text, for whole-record matching.+-- This will be only an approximation of the original record(s);+-- values will always be comma-separated (across all records in the group),+-- and any enclosing quotes and whitespace outside those quotes will be removed.+recordAsApproximateText :: CsvRecordGroup -> Text+recordAsApproximateText = T.intercalate "," . concat++-- | A way to get the values of hledger fields referenced in %{...} expressions.+type HledgerFieldLookup = HledgerFieldName -> Text++-- | A part of a field assignment's template.+data TemplatePart =+ TPText Text -- ^ literal text+ | TPMatch MatchGroupReference -- ^ eg \1+ | TPExpr TemplateExpr -- ^ eg %{upper(%desc)}+ | TPField CsvFieldReference -- ^ eg %desc++-- | Render a field assignment's template, possibly interpolating referenced+-- CSV field values, match groups, or %{...} expressions.+-- Outer whitespace is removed from interpolated values.+renderTemplate :: CsvRules -> CsvRecordGroup -> HledgerFieldLookup -> FieldTemplate -> Text+renderTemplate rules record lookupfield t = maybe t (mconcat . map render) $ templateParts t+ where+ render (TPText s) = s+ render (TPMatch m) = replaceRegexGroupReference rules record m+ render (TPExpr e) = evalTemplateExpr rules record lookupfield e+ render (TPField r) = fromMaybe "" $ replaceCsvFieldReference rules record r++-- | The hledger fields referenced by a field assignment's template.+templateHledgerFieldRefs :: FieldTemplate -> [HledgerFieldName]+templateHledgerFieldRefs t = [f | TPExpr e <- fromMaybe [] $ templateParts t, f <- exprRefs e]+ where+ exprRefs (TECall _ args) = concatMap exprRefs args+ exprRefs (TEHledgerField f) = [f]+ exprRefs _ = []++-- | Parse a field assignment's template into parts.+templateParts :: FieldTemplate -> Maybe [TemplatePart]+templateParts = parseMaybe $ many+ ( TPText <$> literaltextp+ <|> TPMatch <$> templatematchrefp+ <|> TPExpr <$> templateexprp+ <|> TPField <$> templatefieldrefp+ )+ where+ literaltextp :: SimpleTextParser Text+ literaltextp = some (nonBackslashOrPercent <|> nonRefBackslash <|> nonRefPercent) <&> T.pack+ where+ nonBackslashOrPercent = noneOf ['\\', '%'] <?> "character other than backslash or percent"+ nonRefBackslash = try (char '\\' <* notFollowedBy digitChar) <?> "backslash that does not begin a match group reference"+ nonRefPercent = try (char '%' <* notFollowedBy (satisfy (\c -> isFieldNameChar c || c == '(' || c == '{'))) <?> "percent that does not begin a field reference or expression"++-- | Parse a match group reference in a template, eg \1.+templatematchrefp :: TextParser m MatchGroupReference+templatematchrefp = liftA2 T.cons (char '\\') (takeWhile1P (Just "matchref") isDigit)++-- | Parse a csv field reference in a template, eg %date, %1, %(date).+templatefieldrefp :: TextParser m CsvFieldReference+templatefieldrefp = try parenFieldrefp <|> bareFieldrefp+ where+ bareFieldrefp = liftA2 T.cons (char '%') (takeWhile1P (Just "reference") isFieldNameChar)+ parenFieldrefp = do+ _ <- string "%("+ name <- takeWhile1P (Just "reference") isFieldNameChar+ _ <- char ')'+ return $ "%(" <> name <> ")"++isFieldNameChar :: Char -> Bool+isFieldNameChar c = isAlphaNum c || c == '_' || c == '-'++-- | Evaluate a %{...} expression for this CSV record. The result has outer whitespace removed.+evalTemplateExpr :: CsvRules -> CsvRecordGroup -> HledgerFieldLookup -> TemplateExpr -> Text+evalTemplateExpr rules record lookupfield = T.strip . eval+ where+ eval (TECall name args) = maybe "" (\f -> tfApply f $ map eval args) $ lookupTemplateFunction name+ eval (TEField r) = fromMaybe "" $ replaceCsvFieldReference rules record r+ eval (TEHledgerField f) = T.strip $ lookupfield f+ eval (TEMatch m) = replaceRegexGroupReference rules record m+ eval (TEString s) = s+ eval (TENumber n) = T.pack $ show n++-- | Replace something that looks like a Regex match group reference with the+-- resulting match group value after applying the Regex.+replaceRegexGroupReference :: CsvRules -> CsvRecordGroup -> MatchGroupReference -> Text+replaceRegexGroupReference rules record s = case T.uncons s of+ Just ('\\', group) -> fromMaybe "" $ regexMatchValue rules record group+ _ -> s++regexMatchValue :: CsvRules -> CsvRecordGroup -> Text -> Maybe Text+regexMatchValue rules record sgroup = let+ matchgroups = concatMap (getMatchGroups rules record)+ $ concatMap cbMatchers+ $ filter (isBlockActive rules record)+ $ rconditionalblocks rules+ -- XXX adjusted to not use memoized field as caller might be sending a subset of rules with just one CB (hacky)+ group = (read (T.unpack sgroup) :: Int) - 1 -- adjust to 0-indexing+ in atMay matchgroups group++getMatchGroups :: CsvRules -> CsvRecordGroup -> Matcher -> [Text]+getMatchGroups _ record (RecordMatcher _ regex) =+ regexMatchTextGroups regex $ recordAsApproximateText record -- groups might be wrong+getMatchGroups rules record (FieldMatcher _ fieldref regex) =+ regexMatchTextGroups regex $ fromMaybe "" $ replaceCsvFieldReference rules record fieldref++-- | Replace something that looks like a reference to a csv field ("%date", "%1",+-- or "%(date)") with that field's value. If it doesn't look like a field reference,+-- or if we can't find a csv field with that name, return nothing.+replaceCsvFieldReference :: CsvRules -> CsvRecordGroup -> CsvFieldReference -> Maybe Text+replaceCsvFieldReference rules record s = case T.uncons s of+ Just ('%', rest)+ | Just ('(', rest') <- T.uncons rest+ , Just (fieldname, _) <- T.unsnoc rest' -- strip trailing ')'+ -> csvFieldValue rules record fieldname+ | otherwise+ -> csvFieldValue rules record rest+ _ -> Nothing++-- | Get the (whitespace-stripped) value of a CSV field from a group of one+-- or more merged CSV records. The field is identified by its name or column+-- number ("date" or "1"), referring to the group's first record; or with a+-- _ROWNUM suffix ("date_2" or "1_2", where ROWNUM is 2 or greater), referring+-- to a later record in the group. An explicitly declared field name always+-- takes precedence over the _ROWNUM interpretation.+csvFieldValue :: CsvRules -> CsvRecordGroup -> CsvFieldName -> Maybe Text+csvFieldValue rules rows fieldname =+ case fieldindex fieldname of+ Just i -> valueat 1 i+ Nothing -> do+ (base, rownum) <- splitRowSuffix fieldname+ i <- fieldindex base+ valueat rownum i+ where+ -- the column number of a field referenced by number or declared name, if any+ fieldindex f+ | T.all isDigit f = readMay $ T.unpack f+ | otherwise = lookup (T.toLower f) $ rcsvfieldindexes rules+ valueat rownum i = do+ row <- atMay rows (rownum-1)+ T.strip <$> atMay row (i-1)++-- | Split a csv field reference of the form NAME_ROWNUM into its parts,+-- if it looks like one; the row number must be 2 or greater.+-- Eg "date_2" -> ("date", 2).+splitRowSuffix :: CsvFieldName -> Maybe (CsvFieldName, Int)+splitRowSuffix f = do+ let (base', digits) = T.breakOnEnd "_" f+ base <- T.stripSuffix "_" base'+ guard $ not (T.null base) && not (T.null digits) && T.all isDigit digits+ rownum <- readMay $ T.unpack digits+ guard $ rownum >= 2+ return (base, rownum)++_CSV_READING__________________________________________ = undefined++-- | Like 'readJournalFromCsv', but returns an unfinalised journal ready for 'journalFinalise':+-- its lists are reversed, as that expects (readJournalFromCsv produces them in normal order,+-- unlike JournalReader's parser; XXX inefficient), and the given data file and its auxiliary files+-- (rules files, and for a rules file, the data file it read, if any) are noted in jauxfiles,+-- so that the files command can show them and changes to them can be detected when reloading.+readParsedJournalFromCsv :: FilePath -> CsvRules -> (FilePath, [FilePath]) -> FilePath -> Text -> Maybe SepFormat+ -> ExceptT String IO (ParsedJournal, String -> String)+readParsedJournalFromCsv rulesfile rules auxfiles csvfile csvtext sep = do+ (j, adderrorcontext) <- readJournalFromCsv rulesfile rules csvfile csvtext sep+ return ((journalReverse j){jauxfiles = [auxfiles]}, adderrorcontext)++-- | Read a Journal from the given CSV data (and filename, used for error+-- messages), or return an error. Proceed as follows:+--+-- 1. Conversion rules are provided, or they are parsed from the specified+-- rules file, or from the default rules file for the CSV data file.+-- If rules parsing fails, or the required rules file does not exist, throw an error.+--+-- 2. Parse the CSV data using the rules, or throw an error.+--+-- 3. Convert the CSV records to hledger transactions using the rules.+--+-- 4. Return the transactions as a Journal, along with an error context adder:+-- a function which, given a later error message (eg from journal+-- finalisation) mentioning a position in this CSV file, appends the+-- corresponding CSV record's field values to it.+--+readJournalFromCsv :: FilePath -> CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO (Journal, String -> String)+readJournalFromCsv rulesfile rules csvfile csvtext sep = do+ -- for now, correctness is the priority here, efficiency not so much++ dbg6IO "csv rules" rules++ -- convert the csv data to lines, numbered with their position in the file,+ -- then remove all empty/blank lines+ let csvlines1 = dbg9 "csvlines1" $ filter (not . T.null . T.strip . snd) $ zip [1..] $ dbg9 "csvlines0" $ T.lines csvtext++ -- if there is a top-level skip rule, skip the specified number of non-empty lines+ skiplines <- case getDirectiveFirstWins "skip" rules of+ Nothing -> return 0+ Just "" -> return 1+ Just s -> maybe (throwError $ rulesfile <> ": could not parse skip value: " ++ T.unpack s) return . readMay $ T.unpack s+ let csvlines2 = dbg9 "csvlines2" $ drop skiplines csvlines1++ -- convert back to text and parse as csv records+ let+ csvtext1 = T.unlines $ map snd csvlines2+ -- The separator in the rules file takes precedence over the extension or prefix+ separator = case getDirective "separator" rules >>= parseSeparator of+ Just c -> c+ _ | ext == "ssv" -> ';'+ _ | ext == "tsv" -> '\t'+ _ -> + case sep of+ Just Csv -> ','+ Just Ssv -> ';'+ Just Tsv -> '\t'+ Nothing -> ','+ where+ ext = map toLower $ drop 1 $ takeExtension csvfile+ -- parsec seemed to fail if you pass it "-" here -- TODO: try again with megaparsec+ parsecfilename = if csvfile == "-" then "(stdin)" else csvfile+ dbg6IO "using separator" separator+ -- parse csv records+ csvrecords0 <- dbg7 "parseCsv" <$> parseCsv separator parsecfilename csvtext1+ -- pair each record with the range of file lines it came from+ let csvrecords1 = dbg9 "locateCsvRecords" $ locateCsvRecords (map fst csvlines2) csvrecords0+ -- remove any records skipped by conditional skip or end rules,+ -- then group the records joined by merge rules+ csvrecords2 <- liftEither $ first ((rulesfile <> ": ") <>) $+ applyConditionalSkips rules csvrecords1 >>= applyMergeRules rules+ -- and check the remaining records for any obvious problems+ csvrecords <- liftEither $ dbg7 "validateCsv" <$> validateCsv rulesfile parsecfilename csvrecords2+ dbg6IO "first 3 csv records" $ take 3 csvrecords++ -- transactionFromCsvRecord below will replace characters which journal format can't+ -- represent: semicolons in descriptions (#2413), right parentheses in codes.+ -- Warn once per file for each; count the affected records here.+ let warnfixed fieldname badchar replacement =+ let n = length $ filter (maybe False (T.any (==badchar)) . flip (hledgerFieldValue rules) fieldname . snd) csvrecords+ in when (n > 0) $ warnIO $+ csvfile <> ": replaced '" <> [badchar] <> "' with '" <> replacement <> "' in " <>+ show n <> " " <> T.unpack fieldname <> "(s), since journal format can't represent it"+ warnfixed "description" ';' ".,"+ warnfixed "code" ')' "]"++ -- warn if any if block containing a merge rule matches on a later row's+ -- field (%FIELD_N): those fields are still empty when merge rules are+ -- applied, so such a matcher can never trigger a merge+ let mergeblockrowrefs =+ [ ref | b <- rconditionalblocks rules+ , any ((=="merge").faName) $ cbAssignments b+ , FieldMatcher _ ref _ <- cbMatchers b+ , isJust $ splitRowSuffix $ T.dropAround (`elem` ("%()"::String)) ref ]+ unless (null mergeblockrowrefs) $ warnIO $+ rulesfile <> ": an if block containing a merge rule matches on a later row's field ("+ <> T.unpack (T.intercalate ", " mergeblockrowrefs)+ <> "); this can not trigger a merge, since these fields are empty until after merging"++ -- XXX identify header lines some day ?+ -- let (headerlines, datalines) = identifyHeaderLines csvrecords'+ -- mfieldnames = lastMay headerlines++ tzout <- liftIO getCurrentTimeZone+ mtzin <- case getDirective "timezone" rules of+ Nothing -> return Nothing+ Just s ->+ maybe (throwError $ rulesfile <> ": could not parse time zone: " ++ T.unpack s) (return.Just) $+ parseTimeM False defaultTimeLocale "%Z" $ T.unpack s+ let+ -- convert CSV records to transactions, saving the CSV line numbers for error positions+ txns = dbg7 "csv txns" $+ [ transactionFromCsvRecord timesarezoned mtzin tzout rulesfile (mkpos l1, mkpos $ l2+1) rules r+ | ((l1,l2), r) <- csvrecords ]+ where+ -- like journal entries, a record's position ends at the start of the line after its last line+ mkpos l = SourcePos parsecfilename (mkPos l) (mkPos 1)+ timesarezoned =+ case csvRule rules "date-format" of+ Just f | any (`T.isInfixOf` f) ["%Z","%z","%EZ","%Ez"] -> True+ _ -> False++ -- Do our best to ensure transactions will be ordered chronologically,+ -- from oldest to newest. This is done in several steps:+ -- 1. Intra-day order: if there's an "intra-day-reversed" rule,+ -- assume each day's CSV records were ordered in reverse of the overall date order,+ -- so reverse each day's txns.+ intradayreversed = dbg6 "intra-day-reversed" $ isJust $ getDirective "intra-day-reversed" rules+ txns1 = dbg7 "txns1" $+ (if intradayreversed then concatMap reverse . groupOn tdate else id) txns+ -- 2. Overall date order: now if there's a "newest-first" rule,+ -- or if there's multiple dates and the first is more recent than the last,+ -- assume CSV records were ordered newest dates first,+ -- so reverse all txns.+ newestfirst = dbg6 "newest-first" $ isJust $ getDirective "newest-first" rules+ mdatalooksnewestfirst = dbg6 "mdatalooksnewestfirst" $+ case nub $ map tdate txns of+ ds@(d:_) -> Just $ d > last ds+ [] -> Nothing+ txns2 = dbg7 "txns2" $+ (if newestfirst || mdatalooksnewestfirst == Just True then reverse else id) txns1+ -- 3. Disordered dates: in case the CSV records were ordered by chaos,+ -- do a final sort by date. If it was only a few records out of order,+ -- this will hopefully refine any good ordering done by steps 1 and 2.+ txns3 = dbg7 "date-sorted csv txns" $ sortOn tdate txns2++ -- The error context adder returned along with the journal:+ -- if the given error message (eg from journal finalisation) mentions+ -- a position in this CSV data file, append the rules file and the+ -- corresponding record's field values to it, to help troubleshoot the conversion rules.+ adderrorcontext errmsg = maybe errmsg addrecord mgroup+ where+ addrecord g = errmsg <> "\nthis entry was converted with rules file " <> rulesfile <> ", from:\n" <> T.unpack (showRecordFields rules g)+ -- the record group whose line range contains the error's line.+ -- (Error positions can't point outside the group's range:+ -- they are clamped to the entry's source lines, see Errors.hs.)+ mgroup = do+ n <- mlineno+ headMay [g | ((l1,l2),g) <- csvrecords, l1 <= n, n <= l2]+ mlineno =+ case T.breakOn (T.pack $ parsecfilename <> ":") (T.pack errmsg) of+ (_, rest) | not $ T.null rest ->+ readMay $ T.unpack $ T.takeWhile isDigit $ T.drop (length parsecfilename + 1) rest+ _ -> Nothing++ return (nulljournal{jtxns=txns3}, adderrorcontext)++-- | Parse special separator names TAB and SPACE, or return the first+-- character. Return Nothing on empty string+parseSeparator :: Text -> Maybe Char+parseSeparator = specials . T.toLower+ where specials "space" = Just ' '+ specials "tab" = Just '\t'+ specials xs = fst <$> T.uncons xs++-- Call parseCassava on a file or stdin, converting the result to ExceptT.+parseCsv :: Char -> FilePath -> Text -> ExceptT String IO [CsvRecord]+parseCsv separator filePath csvtext = ExceptT $+ case filePath of+ "-" -> parseCassava separator "(stdin)" <$> T.getContents+ _ -> return $ if T.null csvtext then Right mempty else parseCassava separator filePath csvtext++-- Parse text into CSV records, using Cassava and the given field separator.+parseCassava :: Char -> FilePath -> Text -> Either String [CsvRecord]+parseCassava separator path content =+ -- XXX we now remove all blank lines before parsing; will Cassava will still produce [""] records ?+ -- filter (/=[""])+ either (Left . errorBundlePretty) (Right . parseResultToCsv) <$>+ CassavaMegaparsec.decodeWith decodeOptions Cassava.NoHeader path $+ BL.fromStrict $ T.encodeUtf8 content+ where+ decodeOptions = Cassava.defaultDecodeOptions {+ Cassava.decDelimiter = fromIntegral (ord separator)+ }+ parseResultToCsv :: (Foldable t, Functor t) => t (t B.ByteString) -> [CsvRecord]+ parseResultToCsv = toListList . unpackFields+ where+ toListList = toList . fmap toList+ unpackFields = (fmap . fmap) T.decodeUtf8++-- The lazy tuples in these Located* types are ok to use:+-- they live only briefly, between parsing and transaction conversion,+-- where mkPos and a deepseq force the line numbers;+-- and locateCsvRecords forces each end line to avoid thunk chains.++-- | A CSV record, together with the range of file lines it came from+-- (first line, last line; 1-based, inclusive).+type LocatedCsvRecord = ((Int, Int), CsvRecord)++-- | One or more CSV records being converted to a single transaction:+-- the first is the main record, any others were appended by a merge rule.+type CsvRecordGroup = [CsvRecord]++-- | A CSV record group, together with the range of file lines it came from.+type LocatedCsvRecordGroup = ((Int, Int), CsvRecordGroup)++-- | Pair each parsed csv record with the range of file lines it came from.+-- The first argument is the original file line numbers of the (non-blank,+-- non-header) lines that were parsed. Each record consumes one of these,+-- plus one more for each newline embedded in its field values (a quoted+-- field can span multiple lines). If the line numbers run out (eg when+-- reading from stdin, whose lines were not counted), continue counting+-- sequentially from the last known line.+locateCsvRecords :: [Int] -> [CsvRecord] -> [LocatedCsvRecord]+locateCsvRecords = go 1+ where+ go _ _ [] = []+ go nextline linenos (r:rs) = l2 `seq` (((l1, l2), r) : go (l2+1) linenos' rs)+ where+ numlines = 1 + sum (map (T.count "\n") r)+ (consumed, linenos') = splitAt numlines linenos+ l1 = headDef nextline consumed+ l2 = lastDef (l1 + numlines - 1) consumed++-- | Scan for csv records where a `skip` or `end` rule applies+-- (conditionally or unconditionally), and apply that rule,+-- removing one or more records.+-- Return an error message if a rule's value can't be parsed as a positive number.+applyConditionalSkips :: CsvRules -> [LocatedCsvRecord] -> Either String [LocatedCsvRecord]+applyConditionalSkips _ [] = Right []+applyConditionalSkips rules (lr@(_, r):rest) = do+ mskip <- ruleRecordCount rules r "skip"+ case (hledgerField rules [r] "end", mskip) of+ (Just _, _) -> Right []+ (_, Just cnt) -> applyConditionalSkips rules $ drop (cnt-1) rest+ _ -> (lr:) <$> applyConditionalSkips rules rest++-- | Scan for csv records where a `merge` rule applies+-- (conditionally or unconditionally), and apply that rule:+-- the next N records are appended to the current record's group,+-- to be converted to a single transaction located at+-- the whole group's range of file lines.+-- If fewer than N records remain in the file, merge just appends those.+-- Return an error message if a rule's value can't be parsed as a positive number.+applyMergeRules :: CsvRules -> [LocatedCsvRecord] -> Either String [LocatedCsvRecordGroup]+applyMergeRules _ [] = Right []+applyMergeRules rules (((l1,l2), r):rest) = do+ mmerge <- ruleRecordCount rules r "merge"+ case mmerge of+ Just cnt -> (((l1, l2'), r : map snd merged) :) <$> applyMergeRules rules rest'+ where+ (merged, rest') = splitAt cnt rest+ l2' = lastDef l2 $ map (snd . fst) merged+ Nothing -> (((l1,l2), [r]) :) <$> applyMergeRules rules rest++-- | The value of this record's skip or merge rule, if any:+-- a positive record count (with no value meaning 1),+-- or an error message if the value can't be parsed as a positive number.+ruleRecordCount :: CsvRules -> CsvRecord -> HledgerFieldName -> Either String (Maybe Int)+ruleRecordCount rules r name =+ case hledgerField rules [r] name of+ Nothing -> Right Nothing+ Just "" -> Right $ Just 1+ Just x ->+ case readMay $ T.unpack x of+ Just n | n >= 1 -> Right $ Just n+ _ -> Left $ printf "could not parse %s value as a positive number: %s" (T.unpack name) (T.unpack x)++-- | Do some validation on the parsed CSV records (from the named file, read with the named rules file):+-- check that they all have at least two fields.+validateCsv :: FilePath -> FilePath -> [LocatedCsvRecordGroup] -> Either String [LocatedCsvRecordGroup]+validateCsv rulesfile f rs =+ case [g | g@(_, recs) <- rs, any ((<2).length) recs] of+ ((l1,l2), recs):_ -> Left $ T.unpack $+ csvRecordErrPrefix rulesfile (mkpos l1, mkpos (l2+1)) recs+ <> "This CSV record has less than two fields.\n"+ <> "Perhaps the separator is wrong (it can be set with a separator rule)."+ [] -> Right rs+ where+ mkpos l = SourcePos f (mkPos l) (mkPos 1)++-- -- | 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+-- ,date2Field r+-- ]++--- ** converting csv records to transactions++transactionFromCsvRecord :: Bool -> Maybe TimeZone -> TimeZone -> FilePath -> (SourcePos, SourcePos) -> CsvRules -> CsvRecordGroup -> Transaction+transactionFromCsvRecord timesarezoned mtzin tzout rulesfile sourcepospair rules record =+ -- log the record and all the transaction fields from this record+ -- XXX avoid possibly-pessimising deepseq if not needed for debug output ?+ dbg2Msg (T.unpack $ showRecord record) $ deepseq t+ t+ where++ ----------------------------------------------------------------------+ -- 1. Define some helpers:++ -- the start of any error message about this record: its position, an excerpt, and the rules file+ errpfx = csvRecordErrPrefix rulesfile sourcepospair record+ rule = csvRule rules :: DirectiveName -> Maybe FieldTemplate+ -- ruleval = csvRuleValue rules record :: DirectiveName -> Maybe String+ fieldval = hledgerFieldValue rules record :: HledgerFieldName -> Maybe Text+ mdateformat = rule "date-format"+ parseDate = parseDateWithCustomOrDefaultFormats timesarezoned mtzin tzout mdateformat+ mkdateerror datefield datevalue mdateformat' = T.unpack $ errpfx <> T.unlines+ ["could not parse \""<>datevalue<>"\" as a date using date format "+ <>maybe "\"YYYY/M/D\", \"YYYY-M-D\" or \"YYYY.M.D\"" (T.pack . show) mdateformat'+ ,showRecordFields rules record+ ,let ma = hledgerFieldAssignment rules record datefield+ in withRulesPos+ ("the "<>datefield<>" rule is: "<>maybe "required, but missing" faTemplate ma)+ (faPos =<< ma)+ ,"the date-format is: "<>fromMaybe "unspecified" mdateformat'+ ,"you may need to "+ <>"change your "<>datefield<>" rule, "+ <>maybe "add a" (const "change your") mdateformat'<>" date-format rule, "+ <>"or "<>maybe "add a" (const "change your") mskip<>" skip rule"+ ,"for m/d/y or d/m/y dates, use date-format %-m/%-d/%Y or date-format %-d/%-m/%Y"+ ]+ where+ mskip = rule "skip"++ ----------------------------------------------------------------------+ -- 2. Gather values needed for the transaction itself, by evaluating the+ -- field assignment rules using the CSV record's data, and parsing a bit+ -- more where needed (dates, status).++ date = fromMaybe "" $ fieldval "date"+ -- PARTIAL:+ date' = fromMaybe (error' $ mkdateerror "date" date mdateformat) $ parseDate date+ mdate2 = fieldval "date2"+ mdate2' = (maybe (error' $ mkdateerror "date2" (fromMaybe "" mdate2) mdateformat) Just . parseDate) =<< mdate2+ status =+ case fieldval "status" of+ Nothing -> Unmarked+ Just s -> either statuserror id $ runParser (statusp <* eof) "" s+ where+ statuserror err = error' . T.unpack $ errpfx <> T.unlines+ ["could not parse status value \""<>s<>"\" (should be *, ! or empty)"+ ,"the parse error is: "<>T.pack (customErrorBundlePretty err)+ ]+ code = maybe "" (fixparens . singleline') $ fieldval "code"+ description = maybe "" (fixsemicolons . singleline') $ fieldval "description"+ -- Journal format can't represent a semicolon in a description (when reparsed, it would+ -- start a comment, truncating the description; #2413), or a right parenthesis in a code+ -- (it would end the code early). Replace them with lookalikes.+ -- readJournalFromCsv prints a warning when this happens.+ fixsemicolons = T.replace ";" ".,"+ fixparens = T.replace ")" "]"+ comment = maybe "" unescapeNewlines $ fieldval "comment"++ -- Convert some parsed comment text back into following comment syntax,+ -- with the semicolons and indents, so it can be parsed again for tags.+ textToFollowingComment :: Text -> Text+ textToFollowingComment = T.stripStart . T.unlines . map (" ;"<>) . T.lines++ ttags = fromRight [] $ fmap snd $ rtp transactioncommentp $ textToFollowingComment comment++ singleline' = T.unwords . filter (not . T.null) . map T.strip . T.lines+ unescapeNewlines = T.intercalate "\n" . T.splitOn "\\n"++ ----------------------------------------------------------------------+ -- 3. Generate the postings for which an account has been assigned+ -- (possibly indirectly due to an amount or balance assignment)++ p1IsVirtual = (accountNamePostingType <$> fieldval "account1") == Just VirtualPosting+ ps = [p | n <- [1..maxpostings]+ ,let cmt = maybe "" unescapeNewlines $ fieldval ("comment"<> T.pack (show n))+ -- Tags in the comment will be parsed and attached to the posting.+ -- A posting date, in the date: tag or in brackets, will also be parsed and applied to the posting.+ -- But it must have a year, or it will be ignored.+ -- A secondary posting date will also be ignored.+ ,let (tags,mdate) =+ fromRight ([],Nothing) $+ fmap (\(_,ts,md,_)->(ts,md)) $+ rtp (postingcommentp Nothing) $+ textToFollowingComment cmt+ ,let currency = fromMaybe "" (fieldval ("currency"<> T.pack (show n)) <|> fieldval "currency")+ ,let mamount = getAmount errpfx rules record currency p1IsVirtual n+ ,let mbalance = getBalance errpfx rules record currency n+ ,Just (acct,isfinal) <- [getAccount errpfx rules record mamount mbalance n] -- skips Nothings+ ,let acct' | not isfinal && acct==unknownExpenseAccount &&+ fromMaybe False (mamount >>= isNegativeMixedAmount) = unknownIncomeAccount+ | otherwise = acct+ ,let p = nullposting{pdate = mdate+ ,paccount = accountNameWithoutPostingType acct'+ ,pamount = fromMaybe missingmixedamt mamount+ ,ptransaction = Just t+ ,pbalanceassertion = mkBalanceAssertion errpfx rules record (fst sourcepospair) <$> mbalance+ ,pcomment = cmt+ ,ptags = tags+ ,preal = accountNamePostingType acct+ }+ ]++ ----------------------------------------------------------------------+ -- 4. Build the transaction (and name it, so the postings can reference it).+ -- Amounts calculated with * or / in an amount expression are rounded, as in journal format.++ t = transactionRoundCalculatedAmounts nulltransaction{+ tsourcepos = sourcepospair -- the CSV file line(s) this transaction came from+ ,tdate = date'+ ,tdate2 = mdate2'+ ,tstatus = status+ ,tcode = code+ ,tdescription = description+ ,tcomment = comment+ ,ttags = ttags+ ,tprecedingcomment = ""+ ,tpostings = ps+ }++-- | Parse the date string using the specified date-format, or if unspecified+-- the "simple date" formats (YYYY/MM/DD, YYYY-MM-DD, YYYY.MM.DD, leading+-- zeroes optional). If a timezone is provided, we assume the DateFormat+-- produces a zoned time and we localise that to the given timezone.+parseDateWithCustomOrDefaultFormats :: Bool -> Maybe TimeZone -> TimeZone -> Maybe DateFormat -> Text -> Maybe Day+parseDateWithCustomOrDefaultFormats timesarezoned mtzin tzout mformat s = localdate <$> mutctime+ -- this time code can probably be simpler, I'm just happy to get out alive+ where+ localdate :: UTCTime -> Day =+ localDay .+ dbg7 ("time in output timezone "++show tzout) .+ utcToLocalTime tzout+ mutctime :: Maybe UTCTime = asum $ map parseWithFormat formats++ parseWithFormat :: String -> Maybe UTCTime+ parseWithFormat fmt =+ if timesarezoned+ then+ dbg7 "zoned CSV time, expressed as UTC" $+ parseTimeM True defaultTimeLocale fmt $ T.unpack s :: Maybe UTCTime+ else+ -- parse as a local day and time; then if an input timezone is provided,+ -- assume it's in that, otherwise assume it's in the output timezone;+ -- then convert to UTC like the above+ let+ mlocaltime =+ fmap (dbg7 "unzoned CSV time") $+ parseTimeM True defaultTimeLocale fmt $ T.unpack s :: Maybe LocalTime+ localTimeAsZonedTime tz lt = ZonedTime lt tz+ in+ case mtzin of+ Just tzin ->+ (dbg7 ("unzoned CSV time, declared as "++show tzin++ ", expressed as UTC") .+ localTimeToUTC tzin)+ <$> mlocaltime+ Nothing ->+ (dbg7 ("unzoned CSV time, treated as "++show tzout++ ", expressed as UTC") .+ zonedTimeToUTC .+ localTimeAsZonedTime tzout)+ <$> mlocaltime++ formats = map T.unpack $ maybe+ ["%Y/%-m/%-d"+ ,"%Y-%-m-%-d"+ ,"%Y.%-m.%-d"+ -- ,"%-m/%-d/%Y"+ -- ,parseTimeM TruedefaultTimeLocale "%Y/%m/%e" (take 5 s ++ "0" ++ drop 5 s)+ -- ,parseTimeM TruedefaultTimeLocale "%Y-%m-%e" (take 5 s ++ "0" ++ drop 5 s)+ -- ,parseTimeM TruedefaultTimeLocale "%m/%e/%Y" ('0':s)+ -- ,parseTimeM TruedefaultTimeLocale "%m-%e-%Y" ('0':s)+ ]+ (:[])+ mformat++-- | Figure out the amount specified for posting N, if any.+-- A currency symbol to prepend to the amount, if any, is provided,+-- and whether posting 1 requires balancing or not.+-- This looks for a non-empty amount value assigned to "amountN", "amountN-in", or "amountN-out".+-- For postings 1 or 2 it also looks at "amount", "amount-in", "amount-out".+-- If more than one of these has a value, it looks for one that is non-zero.+-- If there's multiple non-zeros, or no non-zeros but multiple zeros, it throws an error.+getAmount :: Text -> CsvRules -> CsvRecordGroup -> Text -> Bool -> Int -> Maybe MixedAmount+getAmount errpfx rules record currency p1IsVirtual n =+ -- Warning! Many tricky corner cases here.+ -- Keep synced with:+ -- hledger_csv.m4.md -> CSV FORMAT -> "amount", "Setting amounts",+ -- hledger/test/csv.test -> 13, 31-34+ let+ unnumberedfieldnames = ["amount","amount-in","amount-out"]++ -- amount field names which can affect this posting+ fieldnames = map (("amount"<> T.pack (show n))<>) ["","-in","-out"]+ -- For posting 1, also recognise the old amount/amount-in/amount-out names.+ -- For posting 2, the same but only if posting 1 needs balancing.+ ++ if n==1 || n==2 && not p1IsVirtual then unnumberedfieldnames else []++ -- assignments to any of these field names with non-empty values+ assignments = [(f,a') | f <- fieldnames+ , Just v <- [T.strip <$> hledgerFieldValue rules record f]+ , not $ T.null v+ -- XXX maybe ignore rule-generated values like "", "-", "$", "-$", "$-" ? cf CSV FORMAT -> "amount", "Setting amounts",+ , let a = parseAmount errpfx rules record currency v+ -- With amount/amount-in/amount-out, in posting 2,+ -- flip the sign and convert to cost, as they did before 1.17+ , let a' = if f `elem` unnumberedfieldnames && n==2 then mixedAmountCost (maNegate a) else a+ ]++ -- if any of the numbered field names are present, discard all the unnumbered ones+ discardUnnumbered xs = if null numbered then xs else numbered+ where+ numbered = filter (T.any isDigit . fst) xs++ -- discard all zero amounts, unless all amounts are zero, in which case discard all but the first+ discardExcessZeros xs = if null nonzeros then take 1 xs else nonzeros+ where+ nonzeros = filter (not . mixedAmountLooksZero . snd) xs++ -- for -out fields, flip the sign XXX unless it's already negative ? back compat issues / too confusing ?+ negateIfOut f = if "-out" `T.isSuffixOf` f then maNegate else id++ in case discardExcessZeros $ discardUnnumbered assignments of+ [] -> Nothing+ [(f,a)] -> Just $ negateIfOut f a+ fs -> error' . T.unpack . (errpfx <>) . textChomp . T.unlines $+ ["Multiple non-zero amounts were assigned for an amount field, for posting " <> T.pack (show n) <> "."+ ,showRecordFields rules record+ ] +++ [withRulesPos+ ("rule \"" <> f <> " " <>+ maybe "" faTemplate massignment <>+ "\" assigned value \"" <> wbToText (showMixedAmountB defaultFmt a) <> "\"") -- XXX not sure this is showing all the right info+ (faPos =<< massignment)+ | (f,a) <- fs+ , let massignment = hledgerFieldAssignment rules record f+ ] +++ [""+ ,"Please ensure just one non-zero amount is assigned, perhaps with an if rule."+ ,"See also: https://hledger.org/hledger.html#setting-amounts"+ ,"(hledger manual -> CSV format -> Tips -> Setting amounts)"+ ]+-- | Figure out the expected balance (assertion or assignment) specified for posting N, if any.+getBalance :: Text -> CsvRules -> CsvRecordGroup -> Text -> Int -> Maybe Amount+getBalance errpfx rules record currency n = do+ v <- (fieldval ("balance"<> T.pack (show n))+ -- for posting 1, also recognise the old field name+ <|> if n==1 then fieldval "balance" else Nothing)+ case v of+ "" -> Nothing+ s -> Just $ parseBalanceAmount errpfx rules record currency n s+ where+ fieldval = fmap T.strip . hledgerFieldValue rules record :: HledgerFieldName -> Maybe Text++-- | Given a non-empty amount string (from CSV) to parse, along with a+-- possibly non-empty currency rule value (see parseCurrency),+-- parse as a hledger MixedAmount (as in journal format), or raise an error.+-- The whole CSV record is provided for the error message.+parseAmount :: Text -> CsvRules -> CsvRecordGroup -> Text -> Text -> MixedAmount+parseAmount errpfx rules record currency s =+ either mkerror mixedAmount $+ if isAmountExpression s+ then runCsvAmountParser rules mcs (postingamountp OrdinaryAmount) s+ else runCsvAmountParser rules mcs amountp (simplifySign s)+ where+ mcs = parseCurrency errpfx rules record currency+ mkerror e = error' . T.unpack $ errpfx <> T.unlines+ ["could not parse \"" <> s <> "\" as an amount"+ ,showRecordFields rules record+ ,showRules rules record+ -- ,"the default-currency is: "++fromMaybe "unspecified" (getDirective "default-currency" rules)+ ,"the parse error is: " <> T.pack (customErrorBundlePretty e)+ ,"you may need to change your amount*, balance*, or currency* rules, or add or change your skip rule"+ ]++-- | Show the values assigned to each journal field.+showRules rules record = T.unlines $ "hledger field assignment rules:" : concatMap showfieldrules journalfieldnames+ where+ -- the field's effective rule, and below it any earlier-declared rules it overrides+ showfieldrules fld =+ case reverse $ map fst $ hledgerFieldAssignments rules record fld of+ (a:overridden) ->+ withRulesPos (fieldlabel <> faTemplate a) (faPos a)+ : [ withRulesPos (" (overrides: "<>faTemplate o) (faPos o) <> ")" | o <- overridden ]+ [] -> []+ where+ -- indented field name, padded to a standard column (or longer)+ fieldlabel = T.justifyLeft (fieldColumn - 1) ' ' (" "<>fld<>":") <> " "+ fieldColumn = 15++-- | Append a rules file position ("(FILE:LINE)") to a line of text, if known.+-- The full file path is shown, so editors/IDEs can jump to the location.+-- To visually separate the paths, they are aligned at a standard column+-- when possible (longer lines push them further right).+withRulesPos :: Text -> Maybe (FilePath, Int) -> Text+withRulesPos txt =+ maybe txt $ \(f,l) ->+ T.justifyLeft (rulesPosColumn - 2) ' ' txt <> " ("<>T.pack f<>":"<>T.pack (show l)<>")"+ where rulesPosColumn = 45++-- XXX unify these ^v++-- | Almost but not quite the same as parseAmount.+-- Given a non-empty amount string (from CSV) to parse, along with a+-- possibly non-empty currency symbol to prepend,+-- parse as a hledger Amount (as in journal format), or raise an error.+-- The CSV record and the field's numeric suffix are provided for the error message.+parseBalanceAmount :: Text -> CsvRules -> CsvRecordGroup -> Text -> Int -> Text -> Amount+parseBalanceAmount errpfx rules record currency n s =+ either (mkerror n s) id $+ runCsvAmountParser rules (parseCurrency errpfx rules record currency) amountp (simplifySign s)+ where+ mkerror n' s' e = error' . T.unpack $ errpfx <> T.unlines+ ["could not parse \"" <> s' <> "\" as balance"<> T.pack (show n') <> " amount"+ ,showRecordFields rules record+ ,showRules rules record+ -- ,"the default-currency is: "++fromMaybe "unspecified" mdefaultcurrency+ ,"the parse error is: "<> T.pack (customErrorBundlePretty e)+ ]++-- | Run a journal amount parser on a CSV amount value, with the rules' decimal mark+-- and the given default commodity and style (if any) in effect, as with a D directive.+runCsvAmountParser :: CsvRules -> Maybe (CommoditySymbol, AmountStyle) -> StateT Journal SimpleTextParser Amount -> Text -> Either HledgerParseErrors Amount+runCsvAmountParser rules mcs p =+ runParser (evalStateT (p <* eof) nulljournal{jparsedecimalmark=parseDecimalMark rules, jparsedefaultcommodity=mcs}) ""++-- | Parse a currency rule's value, if non-empty, as a default commodity and style+-- (like a D directive's): either an amount like "1 USD" or "USD 1", whose symbol+-- and style are used (its decimal mark need not match the decimal-mark rule, as with+-- a D directive), or just a commodity symbol, placed on the left with no space.+-- Raises an error if it is neither; the record is provided for the error message.+parseCurrency :: Text -> CsvRules -> CsvRecordGroup -> Text -> Maybe (CommoditySymbol, AmountStyle)+parseCurrency errpfx rules record currency+ | T.null currency = Nothing+ | otherwise = Just $ fromMaybe mkerror $ asDefault currency <|> asDefault (currency <> "1")+ where+ asDefault t = case runCsvAmountParser rules Nothing (amountp' StyleAmount) t of+ Right a | not (T.null $ acommodity a) -> Just (acommodity a, astyle a)+ _ -> Nothing+ mkerror = error' . T.unpack $ errpfx <> T.unlines+ ["could not parse \"" <> currency <> "\" as a currency"+ ,showRecordFields rules record+ ,showRules rules record+ ,"a currency rule's value should be a commodity symbol, like USD or \"Some Fund\","+ ,"or an amount showing the symbol's position, like 1 USD"+ ]++-- | The start of an error message about a CSV record, in hledger's standard error format:+-- the record's file position (lines), an excerpt showing (an approximation of) the record,+-- and a line naming the rules file being used to convert it.+csvRecordErrPrefix :: FilePath -> (SourcePos, SourcePos) -> CsvRecordGroup -> Text+csvRecordErrPrefix rulesfile (SourcePos f l1 _, SourcePos _ lend _) record =+ T.pack (f ++ ":" ++ show firstline ++ lastline ++ ":\n")+ <> T.pack (show firstline) <> " | " <> recordAsApproximateText record <> "\n\n"+ <> "While converting this record with rules file " <> T.pack rulesfile <> ":\n"+ where+ firstline = unPos l1+ -- the end position is the start of the line after the record+ lastline = let l2 = unPos lend - 1 in if l2 > firstline then "-" ++ show l2 else ""++-- | Show the approximation of the original CSV record, labelled, for debug output.+showRecord :: CsvRecordGroup -> Text+showRecord = ("record: "<>) . recordAsApproximateText++-- | Show a CSV record like showRecord (whose whole-record view helps+-- troubleshoot whole-record matchers), and below it the field values one+-- per line, each with its CSV field number and its field name if one was+-- declared with a fields list; to help troubleshoot rules.+-- A merged record group's rows are shown in turn, with the later rows'+-- references shown with their _ROWNUM suffix.+showRecordFields :: CsvRules -> CsvRecordGroup -> Text+showRecordFields rules rows = T.stripEnd $ T.unlines $ showRecord rows : concatMap showrow (zip [1..] rows)+ where+ showrow (rownum, row) = heading ++ map showfield (zip [1..] row)+ where+ heading = if length rows > 1 then ["row " <> tshow rownum <> ":"] else []+ suffix = if (rownum::Int) > 1 then "_" <> tshow rownum else ""+ showfield (i, v) =+ " " <> T.justifyLeft (numwidth + 1 + T.length suffix) ' ' ("%" <> tshow i <> suffix)+ <> " " <> T.justifyLeft (namewidth + T.length suffix) ' ' (maybe "" (<> suffix) $ mfieldname i)+ <> " " <> v+ tshow = T.pack . show :: Int -> Text+ mfieldname i = lookup i [(ix,n) | (n,ix) <- rcsvfieldindexes rules, not $ T.null n]+ numwidth = length $ show $ maximum $ 1 : map length rows+ namewidth = maximum $ 0 : [T.length n | (n,_) <- rcsvfieldindexes rules, not $ T.null n]++-- Read a valid decimal mark from the decimal-mark rule, if any.+-- If the rule is present with an invalid argument, raise an error.+parseDecimalMark :: CsvRules -> Maybe DecimalMark+parseDecimalMark rules = do+ s <- T.strip <$> rules `csvRule` "decimal-mark"+ case T.uncons s of+ Just (c, rest) | T.null rest && isDecimalMark c -> return c+ _ -> error' . T.unpack $ "decimal-mark's argument should be \".\" or \",\" (not \""<>s<>"\")"++-- | Make a balance assertion for the given amount, with the given parse+-- position (to be shown in assertion failures), with the assertion type+-- possibly set by a balance-type rule.+-- The CSV rules and current record are also provided, to be shown in case+-- balance-type's argument is bad (XXX refactor).+-- The position of the CSV record is also provided, to be shown if the assertion fails.+mkBalanceAssertion :: Text -> CsvRules -> CsvRecordGroup -> SourcePos -> Amount -> BalanceAssertion+mkBalanceAssertion errpfx rules record pos amt = assrt{baamount=amt, baposition=pos}+ where+ assrt =+ case getDirective "balance-type" rules of+ Nothing -> nullassertion+ Just x ->+ case parseBalanceAssertionType $ T.unpack $ T.strip x of+ Just (total, inclusive) -> nullassertion{batotal=total, bainclusive=inclusive}+ Nothing -> error' . T.unpack $ errpfx <> T.unlines -- PARTIAL:+ [ "balance-type \"" <> x <>"\" is invalid. Use =, ==, =* or ==*."+ , showRecordFields rules record+ , showRules rules record+ ]++-- | Detect from a balance assertion's syntax (=, ==, =*, ==*)+-- whether it is (a) total (multi-commodity) and (b) subaccount-inclusive.+-- Returns nothing if invalid syntax was provided.+parseBalanceAssertionType :: String -> Maybe (Bool, Bool)+parseBalanceAssertionType = \case+ "=" -> Just (False, False)+ "==" -> Just (True, False)+ "=*" -> Just (False, True )+ "==*" -> Just (True, True )+ _ -> Nothing++-- | Figure out the account name specified for posting N, if any.+-- And whether it is the default unknown account (which may be+-- improved later) or an explicitly set account (which may not).+-- The error message prefix is used if the account name is invalid.+getAccount :: Text -> CsvRules -> CsvRecordGroup -> Maybe MixedAmount -> Maybe Amount -> Int -> Maybe (AccountName, Bool)+getAccount errpfx rules record mamount mbalance n =+ let+ fieldval = hledgerFieldValue rules record :: HledgerFieldName -> Maybe Text+ maccount = T.strip <$> fieldval ("account"<> T.pack (show n))+ in case maccount of+ -- accountN is set to the empty string - no posting will be generated+ Just "" -> Nothing+ -- accountN is set (possibly to "expenses:unknown"! #1192) - mark it final+ Just a ->+ -- Check it and reject if invalid.. sometimes people try+ -- to set an amount or comment along with the account name.+ case parsewith (accountnamep >> eof) a of+ Left e -> error' . T.unpack $ errpfx <> T.unlines+ ["could not use \"" <> a <> "\" as the account name for posting " <> T.pack (show n)+ ,showRecordFields rules record+ ,showRules rules record+ ,"the parse error is: " <> T.pack (customErrorBundlePretty e)+ ,"you may need to change your account" <> T.pack (show n) <> " rules"+ <> (if accountNameHasEmptyPart a then ", or add an if rule for empty fields" else "")+ ]+ Right _ -> Just (a, True)+ -- accountN is unset+ Nothing ->+ case (mamount, mbalance) of+ -- amountN is set, or implied by balanceN - set accountN to+ -- the default unknown account ("expenses:unknown") and+ -- allow it to be improved later+ (Just _, _) -> Just (unknownExpenseAccount, False)+ (_, Just _) -> Just (unknownExpenseAccount, False)+ -- amountN is also unset - no posting will be generated+ (Nothing, Nothing) -> Nothing++-- | Default account names to use when needed.+unknownExpenseAccount = "expenses:unknown"+unknownIncomeAccount = "income:unknown"++type CsvAmountString = Text++-- | Does this CSV amount value contain an arithmetic operator, making it an amount expression ?+-- That means a * or / anywhere, or a + or - which is not a leading sign+-- (preceded only by spaces, opening parentheses or other signs)+-- or an exponent sign (immediately preceded by a digit and e or E, as in 1e-5).+-- Double-quoted text is ignored.+--+-- >>> map isAmountExpression ["5", "-5", "+5", "(5)", "-(5)", "--5", "1 + 2", "-(1 + 2)", "(1) + 2", "2 * 3", "\"A-B\" 1", "(1e-5)", "5 e-3"]+-- [False,False,False,False,False,False,True,True,True,True,False,False,True]+isAmountExpression :: Text -> Bool+isAmountExpression = go [] . T.unpack+ where+ -- the first argument is the preceding characters, most recent first+ go _ [] = False+ go prevs ('"':cs) = go ('"':prevs) $ drop 1 $ dropWhile (/= '"') cs+ go prevs (c:cs)+ | c `elem` ['*','/'] = True+ | c `elem` ['+','-'], isOperator prevs = True+ | otherwise = go (c:prevs) cs+ -- is a sign after these characters an operator, not a leading sign or an exponent sign ?+ isOperator (e:d:_) | e `elem` ['e','E'], isDigit d = False+ isOperator prevs = case dropWhile (== ' ') prevs of+ [] -> False+ (p:_) -> p `notElem` ['(','+','-']++-- | Canonicalise the sign in a CSV amount string.+-- Such strings can have a minus sign, parentheses (equivalent to minus),+-- or any two of these (which cancel out),+-- or a plus sign (which is removed),+-- or any sign by itself with no following number (which is removed).+-- See hledger > CSV FORMAT > Tips > Setting amounts.+--+-- These are supported (note, not every possibile combination):+--+-- >>> simplifySign "1"+-- "1"+-- >>> simplifySign "+1"+-- "1"+-- >>> simplifySign "-1"+-- "-1"+-- >>> simplifySign "(1)"+-- "-1"+-- >>> simplifySign "--1"+-- "1"+-- >>> simplifySign "-(1)"+-- "1"+-- >>> simplifySign "-+1"+-- "-1"+-- >>> simplifySign "(-1)"+-- "1"+-- >>> simplifySign "((1))"+-- "1"+-- >>> simplifySign "-"+-- ""+-- >>> simplifySign "()"+-- ""+-- >>> simplifySign "+"+-- ""+simplifySign :: CsvAmountString -> CsvAmountString+simplifySign amtstr+ | Just (' ',t) <- T.uncons amtstr = simplifySign t+ | Just (t,' ') <- T.unsnoc amtstr = simplifySign t+ | Just ('(',t) <- T.uncons amtstr, Just (amt,')') <- T.unsnoc t = simplifySign $ negateStr amt+ | Just ('-',b) <- T.uncons amtstr, Just ('(',t) <- T.uncons b, Just (amt,')') <- T.unsnoc t = simplifySign amt+ | Just ('-',m) <- T.uncons amtstr, Just ('-',amt) <- T.uncons m = amt+ | Just ('-',m) <- T.uncons amtstr, Just ('+',amt) <- T.uncons m = negateStr amt+ | amtstr `elem` ["-","+","()"] = ""+ | Just ('+',amt) <- T.uncons amtstr = simplifySign amt+ | otherwise = amtstr++negateStr :: Text -> Text+negateStr amtstr = case T.uncons amtstr of+ Just ('-',s) -> s+ _ -> T.cons '-' amtstr++--- ** tests+_TESTS__________________________________________ = undefined++tests_RulesReader = testGroup "RulesReader" [+ testGroup "parseCsvRules" [+ testCase "empty file" $+ parseCsvRules "unknown" "" @?= Right (mkrules defrules)+ ]+ ,testGroup "rulesp" [+ testCase "trailing comments" $+ parseWithState' defrules rulesp "skip\n# \n#\n" @?= Right (mkrules $ defrules{rdirectives = [("skip","")]})++ ,testCase "trailing blank lines" $+ parseWithState' defrules rulesp "skip\n\n \n" @?= (Right (mkrules $ defrules{rdirectives = [("skip","")]}))++ ,testCase "no final newline" $+ parseWithState' defrules rulesp "skip" @?= (Right (mkrules $ defrules{rdirectives=[("skip","")]}))++ ,testCase "assignment with empty value" $+ parseWithState' defrules rulesp "account1 \nif foo\n account2 foo\n" @?=+ (Right (mkrules $ defrules{rassignments = [fa "account1" ""], rconditionalblocks = [CB{cbMatchers=[RecordMatcher Or (toRegex' "foo")],cbAssignments=[fa "account2" "foo"],cbPos=Nothing}]}))+ ]+ ,testGroup "conditionalblockp" [+ testCase "space after conditional" $+ parseWithState' defrules conditionalblockp "if a\n account2 b\n \n" @?=+ (Right $ CB{cbMatchers=[RecordMatcher Or $ toRegexCI' "a"],cbAssignments=[fa "account2" "b"],cbPos=Nothing})+ ],++ testGroup "csvfieldreferencep" [+ testCase "number" $ parseWithState' defrules csvfieldreferencep "%1" @?= (Right "%1")+ ,testCase "name" $ parseWithState' defrules csvfieldreferencep "%date" @?= (Right "%date")+ ,testCase "quoted name" $ parseWithState' defrules csvfieldreferencep "%\"csv date\"" @?= (Right "%\"csv date\"")+ ]++ ,testGroup "recordmatcherp" [++ testCase "recordmatcherp" $+ parseWithState' defrules matcherp "A A\n" @?= (Right $ RecordMatcher Or $ toRegexCI' "A A")++ ,testCase "recordmatcherp.starts-with-&" $+ parseWithState' defrules matcherp "& A A\n" @?= (Right $ RecordMatcher And $ toRegexCI' "A A")++ ,testCase "recordmatcherp.starts-with-&&" $+ parseWithState' defrules matcherp "&& A A\n" @?= (Right $ RecordMatcher And $ toRegexCI' "A A")++ ,testCase "recordmatcherp.starts-with-&&-!" $+ parseWithState' defrules matcherp "&& ! A A\n" @?= (Right $ RecordMatcher AndNot $ toRegexCI' "A A")++ ,testCase "recordmatcherp.does-not-start-with-%" $+ parseWithState' defrules matcherp "description A A\n" @?= (Right $ RecordMatcher Or $ toRegexCI' "description A A")+ ]++ ,testGroup "fieldmatcherp" [+ testCase "fieldmatcherp" $+ parseWithState' defrules matcherp "%description A A\n" @?= (Right $ FieldMatcher Or "%description" $ toRegexCI' "A A")++ ,testCase "fieldmatcherp.starts-with-&" $+ parseWithState' defrules matcherp "& %description A A\n" @?= (Right $ FieldMatcher And "%description" $ toRegexCI' "A A")++ ,testCase "fieldmatcherp.starts-with-&&" $+ parseWithState' defrules matcherp "&& %description A A\n" @?= (Right $ FieldMatcher And "%description" $ toRegexCI' "A A")++ ,testCase "fieldmatcherp.starts-with-&&-!" $+ parseWithState' defrules matcherp "&& ! %description A A\n" @?= (Right $ FieldMatcher AndNot "%description" $ toRegexCI' "A A")++ -- ,testCase "fieldmatcherp with operator" $+ -- parseWithState' defrules matcherp "%description ~ A A\n" @?= (Right $ FieldMatcher "%description" "A A")+ ]+++ ,testGroup "regexp" [+ testCase "regexp.ends-before-&&" $+ parseWithState' defrules (regexp eof) "A A && xxx" @?= (Right $ toRegexCI' "A A")+ ,testCase "regexp contains &" $+ parseWithState' defrules (regexp eof) "A & B" @?= (Right $ toRegexCI' "A & B")+ ]++ , let matchers = [RecordMatcher Or (toRegexCI' "A"), RecordMatcher And (toRegexCI' "B")]+ assignments = [fa "account2" "foo", fa "comment2" "bar"]+ block = CB matchers assignments Nothing+ in+ testGroup "Combine multiple matchers on the same line" [+ testCase "conditionalblockp" $+ parseWithState' defrules conditionalblockp "if A && B\n account2 foo\n comment2 bar" @?= (Right block)+ ,testCase "conditionaltablep" $+ parseWithState' defrules conditionaltablep "if,account2,comment2\nA && B,foo,bar" @?= (Right [block])+ ]++ ,testGroup "hledgerField" [+ let rules = mkrules $ defrules {rcsvfieldindexes=[("csvdate",1)],rassignments=[fa "date" "%csvdate"]}++ in testCase "toplevel" $ hledgerField rules [["a","b"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1)], rconditionalblocks=[CB [FieldMatcher Or "%csvdate" $ toRegex' "a"] [fa "date" "%csvdate"] Nothing]}+ in testCase "conditional" $ hledgerField rules [["a","b"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1)], rconditionalblocks=[CB [FieldMatcher Not "%csvdate" $ toRegex' "a"] [fa "date" "%csvdate"] Nothing]}+ in testCase "negated-conditional-false" $ hledgerField rules [["a","b"]] "date" @?= (Nothing)+ + ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1)], rconditionalblocks=[CB [FieldMatcher Not "%csvdate" $ toRegex' "b"] [fa "date" "%csvdate"] Nothing]}+ in testCase "negated-conditional-true" $ hledgerField rules [["a","b"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1),("description",2)], rconditionalblocks=[CB [FieldMatcher Or "%csvdate" $ toRegex' "a", FieldMatcher Or "%description" $ toRegex' "b"] [fa "date" "%csvdate"] Nothing]}+ in testCase "conditional-with-or-a" $ hledgerField rules [["a"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1),("description",2)], rconditionalblocks=[CB [FieldMatcher Or "%csvdate" $ toRegex' "a", FieldMatcher Or "%description" $ toRegex' "b"] [fa "date" "%csvdate"] Nothing]}+ in testCase "conditional-with-or-b" $ hledgerField rules [["_", "b"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1),("description",2)], rconditionalblocks=[CB [FieldMatcher Or "%csvdate" $ toRegex' "a", FieldMatcher And "%description" $ toRegex' "b"] [fa "date" "%csvdate"] Nothing]}+ in testCase "conditional.with-and" $ hledgerField rules [["a", "b"]] "date" @?= (Just "%csvdate")++ ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1),("description",2)], rconditionalblocks=[CB [FieldMatcher Or "%csvdate" $ toRegex' "a", FieldMatcher And "%description" $ toRegex' "b", FieldMatcher Or "%description" $ toRegex' "c"] [fa "date" "%csvdate"] Nothing]}+ in testCase "conditional.with-and-or" $ hledgerField rules [["_", "c"]] "date" @?= (Just "%csvdate")++ ]++ -- testing match groups (#2158)+ ,testGroup "hledgerFieldValue" $+ let rules = mkrules $ defrules+ { rcsvfieldindexes=[ ("date",1), ("description",2) ]+ , rassignments=[ fa "account2" "equity", fa "amount1" "1" ]+ -- ConditionalBlocks here are in reverse order: mkrules reverses the list+ , rconditionalblocks=[ CB { cbMatchers=[FieldMatcher Or "%description" (toRegex' "PREFIX (.*) - (.*)")]+ , cbAssignments=[fa "account1" "account:\\1:\\2"]+ , cbPos=Nothing }+ , CB { cbMatchers=[FieldMatcher Or "%description" (toRegex' "PREFIX (.*)")]+ , cbAssignments=[fa "account1" "account:\\1", fa "comment1" "\\1"]+ , cbPos=Nothing }+ ]+ }+ record = [["2019-02-01","PREFIX Text 1 - Text 2"]]+ in [ testCase "scoped match groups forwards" $ hledgerFieldValue rules record "account1" @?= (Just "account:Text 1:Text 2")+ , testCase "scoped match groups backwards" $ hledgerFieldValue rules record "comment1" @?= (Just "Text 1 - Text 2")+ ]+ ]
+ Hledger/Read/TimeclockReader.hs view
@@ -0,0 +1,253 @@+--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.++-- Keep relevant parts synced with manual:+{-|++A reader for the timeclock file format.++What exactly is this format ? It was introduced in timeclock.el (<http://www.emacswiki.org/emacs/TimeClock>).+The old specification in timeclock.el 2.6 was:++@+A timeclock contains data in the form of a single entry per line.+Each entry has the form:++ CODE YYYY/MM/DD HH:MM:SS [COMMENT]++CODE is one of: b, h, i, o or O. COMMENT is optional when the code is+i, o or O. The meanings of the codes are:++ b Set the current time balance, or \"time debt\". Useful when+ archiving old log data, when a debt must be carried forward.+ The COMMENT here is the number of seconds of debt.++ h Set the required working time for the given day. This must+ be the first entry for that day. The COMMENT in this case is+ the number of hours in this workday. Floating point amounts+ are allowed.++ i Clock in. The COMMENT in this case should be the name of the+ project worked on.++ o Clock out. COMMENT is unnecessary, but can be used to provide+ a description of how the period went, for example.++ O Final clock out. Whatever project was being worked on, it is+ now finished. Useful for creating summary reports.+@++Ledger's timeclock format is different, and hledger's timeclock format is different again.+For example: in a clock-in entry, after the time,++- timeclock.el's timeclock has 0-1 fields: [COMMENT]+- Ledger's timeclock has 0-2 fields: [ACCOUNT[ PAYEE]]+- hledger's timeclock has 1-3 fields: ACCOUNT[ DESCRIPTION[;COMMENT]]++hledger's timeclock format is:++@+# 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](#simple-dates) (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.++In 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:++```timeclock+i 2015/03/30 09:00:00 session1+o 2015/03/30 10:00:00+```++```cli+$ 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-outs does not specify a name, the most recent unclosed clock-in is closed.+Also, sessions spanning more than one day are automatically split at day boundaries.+Eg, the following time log:++```timeclock+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 multple 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:++```cli+$ hledger -f t.timeclock print+2015-03-30 * optional description after 2 spaces ; optional comment, tags:+ (some account) 0.33h++2015-03-31 * 22:21-23:59+ (another:account) 1.64h++2015-04-01 * 00:00-02:00+ (another:account) 2.01h++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++```++-}++--- ** language+{-# LANGUAGE OverloadedStrings #-}++--- ** exports+module Hledger.Read.TimeclockReader (+ -- * Reader+ reader,+ -- * Misc other exports+ timeclockfilep,+)+where++--- ** imports+import Control.Monad+import Control.Monad.Except (ExceptT, liftEither)+import Control.Monad.State.Strict+import Data.Char (isSpace)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Text.Megaparsec hiding (parse)++import Hledger.Data+-- XXX too much reuse ?+import Hledger.Read.Common+import Hledger.Utils+import Data.Text as T (strip)+import Data.Functor ((<&>))++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++--- ** reader++reader :: MonadIO m => Reader m+reader = Reader+ {rFormat = Timeclock+ ,rExtensions = ["timeclock"]+ ,rReadFn = handleReadFnToTextReadFn parse+ ,rParser = timeclockfilep+ }++-- | Parse and post-process a "Journal" from timeclock.el's timeclock+-- format, saving the provided file path and the current time, or give an+-- error.+parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal+parse iopts fp t = initialiseAndParseJournal (timeclockfilep iopts) iopts fp t+ >>= liftEither . journalApplyAliases (aliasesFromOpts iopts)+ >>= journalFinalise iopts fp t++--- ** parsers++-- timeclockfilepspecial :: InputOpts -> JournalParser m ParsedJournal+-- timeclockfilepspecial args = +-- timeclockfilep args++timeclockfilep :: MonadIO m => InputOpts -> JournalParser m ParsedJournal+timeclockfilep iopts = do+ many timeclockitemp+ eof+ j@Journal{jparsetimeclockentries=es} <- get+ -- Convert timeclock entries in this journal to transactions, closing any unfinished sessions.+ -- Doing this here rather than in journalFinalise means timeclock sessions can't span file boundaries,+ -- but it simplifies code above.+ now <- liftIO getCurrentLocalTime+ -- journalFinalise expects the transactions in reverse order, so reverse the output in either case+ let+ j' = if _oldtimeclock iopts+ then+ -- timeclockToTransactionsOld expects the entries to be in normal order, + -- but they have been parsed in reverse order, so reverse them before calling+ j{jtxns = reverse $ timeclockToTransactionsOld now $ reverse es, jparsetimeclockentries = []}+ else+ -- We don't need to reverse these transactions + -- since they are sorted inside of timeclockToTransactions+ j{jtxns = reverse $ timeclockToTransactions now es, jparsetimeclockentries = []}+ return j'+ where+ -- As all ledger line types can be distinguished by the first+ -- character, excepting transactions versus empty (blank or+ -- comment-only) lines, can use choice w/o try+ timeclockitemp = choice [+ void (lift emptyorcommentlinep)+ ,entryp >>= \e -> modify' (\j -> j{jparsetimeclockentries = e : jparsetimeclockentries j})+ ] <?> "timeclock entry, comment line, or empty line"+ where entryp = if _oldtimeclock iopts then oldtimeclockentryp else timeclockentryp++-- | Parse a timeclock entry (loose pre-1.50 format).+oldtimeclockentryp :: JournalParser m TimeclockEntry+oldtimeclockentryp = do+ pos <- getSourcePos+ code <- oneOf ("bhioO" :: [Char])+ lift skipNonNewlineSpaces1+ datetime <- datetimep+ account <- fmap (fromMaybe "") $ optional $ lift skipNonNewlineSpaces1 >> modifiedaccountnamep True+ description <- fmap (maybe "" T.strip) $ optional $ lift $ skipNonNewlineSpaces1 >> descriptionp+ (comment, tags) <- lift transactioncommentp+ return $ TimeclockEntry pos (read [code]) datetime account description comment tags++-- | Parse a timeclock entry (more robust post-1.50 format).+timeclockentryp :: JournalParser m TimeclockEntry+timeclockentryp = do+ pos <- getSourcePos+ code <- oneOf ("iobhO" :: [Char])+ lift skipNonNewlineSpaces1+ datetime <- datetimep+ (account, description) <- case code of+ 'i' -> do+ lift skipNonNewlineSpaces1+ a <- modifiedaccountnamep False+ d <- optional (lift $ skipNonNewlineSpaces1 >> descriptionp) <&> maybe "" T.strip+ return (a, d)+ 'o' -> do+ -- Notice the try needed here to avoid a parse error if there's trailing spaces.+ -- Unlike descriptionp above, modifiedaccountnamep requires nonempty text.+ -- And when a parser in an optional fails after consuming input, optional doesn't backtrack,+ -- it propagates the failure. The try covers only the spaces and the account name's first character,+ -- so the account name's own errors (eg an empty part) are reported.+ a <- optional (try (lift skipNonNewlineSpaces1 >> lookAhead (satisfy (\c -> not $ isSpace c || isSameLineCommentStart c)))+ >> modifiedaccountnamep False) <&> fromMaybe ""+ return (a, "")+ _ -> return ("", "")+ lift skipNonNewlineSpaces+ (comment, tags) <- lift $ optional transactioncommentp <&> fromMaybe ("",[])+ return $ TimeclockEntry pos (read [code]) datetime account description comment tags
+ Hledger/Read/TimedotReader.hs view
@@ -0,0 +1,289 @@+--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.+{-|++A reader for the "timedot" file format.+Example:++@+;DATE+;ACCT DOTS # Each dot represents 15m, spaces are ignored+;ACCT 8 # numbers with or without a following h represent hours+;ACCT 5m # numbers followed by m represent minutes++; on 2/1, 1h was spent on FOSS haskell work, 0.25h on research, etc.+2/1+fos.haskell .... ..+biz.research .+inc.client1 .... .... .... .... .... ....++2/2+biz.research .+inc.client1 .... .... ..++@++-}++--- ** language+{-# LANGUAGE OverloadedStrings #-}++--- ** exports+module Hledger.Read.TimedotReader (+ -- * Reader+ reader,+ -- * Misc other exports+ timedotfilep,+)+where++--- ** imports+import Control.Monad+import Control.Monad.Except (ExceptT, liftEither)+import Control.Monad.State.Strict+import Data.Char (isSpace)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time (Day)+import Text.Megaparsec hiding (parse)+import Text.Megaparsec.Char++import Hledger.Data+import Hledger.Read.Common+import Hledger.Utils+import Data.Functor ((<&>))+import Data.List (sort)+import Data.List (group)+-- import Text.Megaparsec.Debug (dbg)++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++--- ** reader++reader :: MonadIO m => Reader m+reader = Reader+ {rFormat = Timedot+ ,rExtensions = ["timedot"]+ ,rReadFn = handleReadFnToTextReadFn parse+ ,rParser = timedotp+ }++-- | Parse and post-process a "Journal" from the timedot format, or give an error.+parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal+parse iopts fp t = initialiseAndParseJournal (timedotp iopts) iopts fp t+ >>= liftEither . journalApplyAliases (aliasesFromOpts iopts)+ >>= journalFinalise iopts fp t++--- ** utilities++-- Trace parser state above a certain --debug level ?+tracelevel = 9+dp :: String -> JournalParser m ()+dp = if tracelevel >= 0 then lift . dbgparse tracelevel else const $ return ()++--- ** parsers+{-+Rough grammar for timedot format:++timedot: preamble day*+preamble: (emptyline | commentline | orgheading)*+orgheading: orgheadingprefix restofline+day: dateline entry* (emptyline | commentline)*+dateline: orgheadingprefix? date description?+orgheadingprefix: star+ space++description: restofline ; till semicolon?+entry: orgheadingprefix? space* singlespaced (doublespace quantity?)?+doublespace: space space++quantity: (dot (dot | space)* | number | number unit)++Date lines and item lines can begin with an org heading prefix, which is ignored.+Org headings before the first date line are ignored, regardless of content.+-}++timedotfilep = timedotp -- XXX rename export above++timedotp :: InputOpts -> JournalParser m ParsedJournal+timedotp _ = preamblep >> many dayp >> eof >> get++-- | A lookahead that succeeds when the current line looks like a date line attempt:+-- either a valid date line (full or partial date, with optional org heading prefix),+-- or three groups of digits separated by '-', '/', or '.' (catches malformed full dates,+-- so they error clearly via datep rather than being silently treated as a comment or entry).+-- Does not consume input.+datelineattemptp :: JournalParser m ()+datelineattemptp = lift datelikep <|> void datelinep+ where+ datelikep = try . lookAhead $ do+ optional . try $ skipSome (char '*') >> skipNonNewlineSpaces1+ void $ some digitChar+ void datesepchar+ void $ some digitChar+ void datesepchar+ void $ some digitChar++preamblep :: JournalParser m ()+preamblep = do+ dp "preamblep"+ void $ many $ do+ notFollowedBy datelineattemptp+ lift $ emptyorcommentlinep2 "#;*"++-- | Parse timedot day entries to multi-posting time transactions for that day.+-- @+-- 2020/2/1 optional day description+-- fos.haskell .... ..+-- biz.research .+-- inc.client1 .... .... .... .... .... ....+-- @+dayp :: JournalParser m ()+dayp = label "timedot day entry" $ do+ dp "dayp"+ pos <- getSourcePos+ (date,desc,comment,tags) <- datelinep+ dp "dayp1"+ commentlinesp+ dp "dayp2"+ ps <- (many $ dp "dayp3" >> timedotentryp <* commentlinesp) <&> concat+ endpos <- getSourcePos+ let t = txnTieKnot $ nulltransaction{+ tsourcepos = (pos, endpos),+ tdate = date,+ tstatus = Cleared,+ tdescription = desc,+ tcomment = comment,+ ttags = tags,+ tpostings = ps+ }+ modify' $ addTransaction t++datelinep :: JournalParser m (Day,Text,Text,[Tag])+datelinep = do+ dp "datelinep"+ lift $ optional orgheadingprefixp+ date <- datep+ desc <- T.strip <$> lift descriptionp+ (comment, tags) <- lift transactioncommentp+ return (date, desc, comment, tags)++-- | Zero or more empty lines or hash/semicolon comment lines+-- or org headlines which do not start a new day.+commentlinesp :: JournalParser m ()+commentlinesp = do+ dp "commentlinesp"+ void $ many $ try $ lift $ emptyorcommentlinep2 "#;"++-- orgnondatelinep :: JournalParser m ()+-- orgnondatelinep = do+-- dp "orgnondatelinep"+-- lift orgheadingprefixp+-- notFollowedBy datelinep+-- void $ lift restofline++orgheadingprefixp = skipSome (char '*') >> skipNonNewlineSpaces1++-- | Parse a single timedot data line as one or more postings.+-- (Multiple postings can arise if timedot letter syntax is used.)+-- @+-- fos.haskell .... ..+-- @+timedotentryp :: JournalParser m [Posting]+timedotentryp = do+ dp "timedotentryp"+ notFollowedBy datelineattemptp+ lift $ optional $ choice [orgheadingprefixp, skipNonNewlineSpaces1]+ a <- modifiedaccountnamep False+ lift skipNonNewlineSpaces+ taggedhours <- lift durationsp+ (comment0, tags0) <-+ lift transactioncommentp -- not postingp, don't bother with date: tags here+ <|> (newline >> return ("",[]))+ mcs <- getDefaultCommodityAndStyle+ let + (c,s) = case mcs of+ Just (defc,defs) -> (defc, defs{asprecision=max (asprecision defs) (Precision 2)})+ _ -> ("", amountstyle{asprecision=Precision 2})+ ps = [+ nullposting{paccount=a+ ,pamount=mixedAmount $ nullamt{acommodity=c, aquantity=hours, astyle=s}+ ,preal=VirtualPosting+ ,pcomment=comment+ ,ptags=tags+ }+ | (hours,tagval) <- taggedhours+ , let tag = ("t",tagval)+ , let tags = if T.null tagval then tags0 else tags0 ++ [tag]+ , let comment = if T.null tagval then comment0 else comment0 `commentAddTagUnspaced` tag+ ]+ return ps++type Hours = Quantity++-- | Parse one or more durations in hours, each with an optional tag value+-- (or empty string for none).+durationsp :: TextParser m [(Hours,TagValue)]+durationsp =+ (try numericquantityp <&> \h -> [(h,"")]) -- try needed because numbers can begin with .+ <|> (dotquantityp <&> \h -> [(h,"")])+ <|> letterquantitiesp+ <|> pure [(0,"")]++-- | Parse a duration of seconds, minutes, hours, days, weeks, months or years,+-- written as a decimal number followed by s, m, h, d, w, mo or y, assuming h+-- if there is no unit. Returns the duration as hours, assuming+-- 1m = 60s, 1h = 60m, 1d = 24h, 1w = 7d, 1mo = 30d, 1y=365d.+-- @+-- 1.5+-- 1.5h+-- 90m+-- @+numericquantityp :: TextParser m Hours+numericquantityp = do+ -- dp "numericquantityp"+ (q, _, _, _) <- numberp Nothing+ msymbol <- optional $ choice $ map (string . fst) timeUnits+ skipNonNewlineSpaces+ return $ maybe q ($ q) $ msymbol >>= (`lookup` timeUnits)++-- (symbol, conversion to hours). The conversion is exact,+-- or as exact as possible (dividing by 60 or 3600 is rounded at the 255th decimal place).+timeUnits :: [(Text, Hours -> Hours)]+timeUnits =+ [("s", (/ 3600))+ ,("mo", (* 720)) -- 30 days. Before "m"+ ,("m", (/ 60))+ ,("h", id)+ ,("d", (* 24))+ ,("w", (* 168))+ ,("y", (* 8760)) -- 365 days+ ]++-- | Parse a quantity written as a line of one or more dots,+-- each representing 0.25, ignoring any interspersed spaces+-- after the first dot.+-- @+-- .... ..+-- @+dotquantityp :: TextParser m Hours+dotquantityp = do+ -- dp "dotquantityp"+ char '.'+ dots <- many (oneOf ['.', ' ']) <&> filter (not.isSpace)+ return $ fromIntegral (1 + length dots) / 4++-- | Parse a quantity written as a line of one or more letters,+-- each representing 0.25 with a tag "t" whose value is the letter,+-- ignoring any interspersed spaces after the first letter.+letterquantitiesp :: TextParser m [(Hours, TagValue)]+letterquantitiesp =+ -- dp "letterquantitiesp"+ do+ letter1 <- letterChar+ letters <- many (letterChar <|> spacenonewline) <&> filter (not.isSpace)+ let groups =+ [ (fromIntegral (length t) / 4, T.singleton c)+ | t@(c:_) <- group $ sort $ letter1:letters+ ]+ return groups
− Hledger/Read/TimelogReader.hs
@@ -1,104 +0,0 @@-{-|--A reader for the timelog file format generated by timeclock.el.--From timeclock.el 2.6:--@-A timelog contains data in the form of a single entry per line.-Each entry has the form:-- CODE YYYY/MM/DD HH:MM:SS [COMMENT]--CODE is one of: b, h, i, o or O. COMMENT is optional when the code is-i, o or O. The meanings of the codes are:-- b Set the current time balance, or \"time debt\". Useful when- archiving old log data, when a debt must be carried forward.- The COMMENT here is the number of seconds of debt.-- h Set the required working time for the given day. This must- be the first entry for that day. The COMMENT in this case is- the number of hours in this workday. Floating point amounts- are allowed.-- i Clock in. The COMMENT in this case should be the name of the- project worked on.-- o Clock out. COMMENT is unnecessary, but can be used to provide- a description of how the period went, for example.-- O Final clock out. Whatever project was being worked on, it is- now finished. Useful for creating summary reports.-@--Example:--@-i 2007/03/10 12:26:00 hledger-o 2007/03/10 17:26:02-@---}--module Hledger.Read.TimelogReader (- reader,- tests_Hledger_Read_TimelogReader-)-where-import Control.Monad-import Control.Monad.Error-import Test.HUnit-import Text.ParserCombinators.Parsec hiding (parse)--import Hledger.Data-import Hledger.Read.Utils-import Hledger.Read.JournalReader (ledgerDirective, ledgerHistoricalPrice,- ledgerDefaultYear, emptyLine, ledgerdatetime)-import Hledger.Utils---reader :: Reader-reader = Reader format detect parse--format :: String-format = "timelog"---- | Does the given file path and data provide timeclock.el's timelog format ?-detect :: FilePath -> String -> Bool-detect f _ = fileSuffix f == format---- | Parse and post-process a "Journal" from timeclock.el's timelog--- format, saving the provided file path and the current time, or give an--- error.-parse :: FilePath -> String -> ErrorT String IO Journal-parse = parseJournalWith timelogFile--timelogFile :: GenParser Char JournalContext (JournalUpdate,JournalContext)-timelogFile = do items <- many timelogItem- eof- ctx <- getState- return (liftM (foldr (.) id) $ sequence items, ctx)- where - -- As all ledger line types can be distinguished by the first- -- character, excepting transactions versus empty (blank or- -- comment-only) lines, can use choice w/o try- timelogItem = choice [ ledgerDirective- , liftM (return . addHistoricalPrice) ledgerHistoricalPrice- , ledgerDefaultYear- , emptyLine >> return (return id)- , liftM (return . addTimeLogEntry) timelogentry- ] <?> "timelog entry, or default year or historical price directive"---- | Parse a timelog entry.-timelogentry :: GenParser Char JournalContext TimeLogEntry-timelogentry = do- code <- oneOf "bhioO"- many1 spacenonewline- datetime <- ledgerdatetime- comment <- optionMaybe (many1 spacenonewline >> liftM2 (++) getParentAccount restofline)- return $ TimeLogEntry (read [code]) datetime (maybe "" rstrip comment)--tests_Hledger_Read_TimelogReader = TestList [- ]-
− Hledger/Read/Utils.hs
@@ -1,86 +0,0 @@-{-# LANGUAGE RecordWildCards #-}-{-|-Utilities common to hledger journal readers.--}--module Hledger.Read.Utils-where--import Control.Monad.Error-import Data.List-import System.Directory (getHomeDirectory)-import System.FilePath(takeDirectory,combine)-import System.Time (getClockTime)-import Text.ParserCombinators.Parsec--import Hledger.Data.Types-import Hledger.Utils-import Hledger.Data.Posting-import Hledger.Data.Dates (getCurrentYear)-import Hledger.Data.Journal---juSequence :: [JournalUpdate] -> JournalUpdate-juSequence us = liftM (foldr (.) id) $ sequence us---- | Given a JournalUpdate-generating parsec parser, file path and data string,--- parse and post-process a Journal so that it's ready to use, or give an error.-parseJournalWith :: (GenParser Char JournalContext (JournalUpdate,JournalContext)) -> FilePath -> String -> ErrorT String IO Journal-parseJournalWith p f s = do- tc <- liftIO getClockTime- tl <- liftIO getCurrentLocalTime- y <- liftIO getCurrentYear- case runParser p nullctx{ctxYear=Just y} f s of- Right (updates,ctx) -> do- j <- updates `ap` return nulljournal- case journalFinalise tc tl f s ctx j of- Right j' -> return j'- Left estr -> throwError estr- Left e -> throwError $ show e--setYear :: Integer -> GenParser tok JournalContext ()-setYear y = updateState (\ctx -> ctx{ctxYear=Just y})--getYear :: GenParser tok JournalContext (Maybe Integer)-getYear = liftM ctxYear getState--setCommodity :: Commodity -> GenParser tok JournalContext ()-setCommodity c = updateState (\ctx -> ctx{ctxCommodity=Just c})--getCommodity :: GenParser tok JournalContext (Maybe Commodity)-getCommodity = liftM ctxCommodity getState--pushParentAccount :: String -> GenParser tok JournalContext ()-pushParentAccount parent = updateState addParentAccount- where addParentAccount ctx0 = ctx0 { ctxAccount = parent : ctxAccount ctx0 }--popParentAccount :: GenParser tok JournalContext ()-popParentAccount = do ctx0 <- getState- case ctxAccount ctx0 of- [] -> unexpected "End of account block with no beginning"- (_:rest) -> setState $ ctx0 { ctxAccount = rest }--getParentAccount :: GenParser tok JournalContext String-getParentAccount = liftM (concatAccountNames . reverse . ctxAccount) getState--addAccountAlias :: (AccountName,AccountName) -> GenParser tok JournalContext ()-addAccountAlias a = updateState (\(ctx@Ctx{..}) -> ctx{ctxAliases=a:ctxAliases})--getAccountAliases :: GenParser tok JournalContext [(AccountName,AccountName)]-getAccountAliases = liftM ctxAliases getState--clearAccountAliases :: GenParser tok JournalContext ()-clearAccountAliases = updateState (\(ctx@Ctx{..}) -> ctx{ctxAliases=[]})---- | Convert a possibly relative, possibly tilde-containing file path to an absolute one.--- using the current directory from a parsec source position. ~username is not supported.-expandPath :: (MonadIO m) => SourcePos -> FilePath -> m FilePath-expandPath pos fp = liftM mkAbsolute (expandHome fp)- where- mkAbsolute = combine (takeDirectory (sourceName pos))- expandHome inname | "~/" `isPrefixOf` inname = do homedir <- liftIO getHomeDirectory- return $ homedir ++ drop 1 inname- | otherwise = return inname--fileSuffix :: FilePath -> String-fileSuffix = reverse . takeWhile (/='.') . reverse . dropWhile (/='.')
Hledger/Reports.hs view
@@ -1,612 +1,44 @@-{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+ {-| Generate several common kinds of report from a journal, as \"*Report\" - simple intermediate data structures intended to be easily rendered as text, html, json, csv etc. by hledger commands, hamlet templates,-javascript, or whatever. This is under Hledger.Cli since it depends-on the command-line options, should move to hledger-lib later.+javascript, or whatever. -} module Hledger.Reports (- ReportOpts(..),- DisplayExp,- FormatStr,- defreportopts,- dateSpanFromOpts,- intervalFromOpts,- clearedValueFromOpts,- whichDateFromOpts,- journalSelectingDateFromOpts,- journalSelectingAmountFromOpts,- optsToFilterSpec,- -- * Entries report- EntriesReport,- EntriesReportItem,- entriesReport,- -- * Postings report- PostingsReport,- PostingsReportItem,- postingsReport,- mkpostingsReportItem, -- XXX for showPostingWithBalanceForVty in Hledger.Cli.Register- -- * Transactions report- TransactionsReport,- TransactionsReportItem,- triDate,- triBalance,- journalTransactionsReport,- accountTransactionsReport,- -- * Accounts report- AccountsReport,- AccountsReportItem,- accountsReport,- accountsReport2,- isInteresting,+ module Hledger.Reports.ReportOptions,+ module Hledger.Reports.ReportTypes,+ module Hledger.Reports.EntriesReport,+ module Hledger.Reports.PostingsReport,+ module Hledger.Reports.AccountTransactionsReport,+ module Hledger.Reports.BalanceReport,+ module Hledger.Reports.MultiBalanceReport,+ module Hledger.Reports.BudgetReport, -- * Tests- tests_Hledger_Reports+ tests_Reports ) where -import Control.Monad-import Data.List-import Data.Maybe-import Data.Ord-import Data.Time.Calendar-import Data.Tree-import Safe (headMay, lastMay)-import System.Console.CmdArgs -- for defaults support-import Test.HUnit-import Text.ParserCombinators.Parsec-import Text.Printf--import Hledger.Data-import Hledger.Utils---- report options, used in hledger-lib and above-data ReportOpts = ReportOpts {- begin_ :: Maybe Day- ,end_ :: Maybe Day- ,period_ :: Maybe (Interval,DateSpan)- ,cleared_ :: Bool- ,uncleared_ :: Bool- ,cost_ :: Bool- ,depth_ :: Maybe Int- ,display_ :: Maybe DisplayExp- ,effective_ :: Bool- ,empty_ :: Bool- ,no_elide_ :: Bool- ,real_ :: Bool- ,flat_ :: Bool -- balance- ,drop_ :: Int -- balance- ,no_total_ :: Bool -- balance- ,daily_ :: Bool- ,weekly_ :: Bool- ,monthly_ :: Bool- ,quarterly_ :: Bool- ,yearly_ :: Bool- ,format_ :: Maybe FormatStr- ,patterns_ :: [String]- } deriving (Show)--type DisplayExp = String-type FormatStr = String--defreportopts = ReportOpts- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def- def--instance Default ReportOpts where def = defreportopts---- | Figure out the date span we should report on, based on any--- begin/end/period options provided. A period option will cause begin and--- end options to be ignored.-dateSpanFromOpts :: Day -> ReportOpts -> DateSpan-dateSpanFromOpts _ ReportOpts{..} =- case period_ of Just (_,span) -> span- Nothing -> DateSpan begin_ end_---- | Figure out the reporting interval, if any, specified by the options.--- --period overrides --daily overrides --weekly overrides --monthly etc.-intervalFromOpts :: ReportOpts -> Interval-intervalFromOpts ReportOpts{..} =- case period_ of- Just (interval,_) -> interval- Nothing -> i- where i | daily_ = Days 1- | weekly_ = Weeks 1- | monthly_ = Months 1- | quarterly_ = Quarters 1- | yearly_ = Years 1- | otherwise = NoInterval---- | Get a maybe boolean representing the last cleared/uncleared option if any.-clearedValueFromOpts :: ReportOpts -> Maybe Bool-clearedValueFromOpts ReportOpts{..} | cleared_ = Just True- | uncleared_ = Just False- | otherwise = Nothing---- | Report which date we will report on based on --effective.-whichDateFromOpts :: ReportOpts -> WhichDate-whichDateFromOpts ReportOpts{..} = if effective_ then EffectiveDate else ActualDate---- | Select a Transaction date accessor based on --effective.-transactionDateFn :: ReportOpts -> (Transaction -> Day)-transactionDateFn ReportOpts{..} = if effective_ then transactionEffectiveDate else transactionActualDate---- | Convert this journal's transactions' primary date to either the--- actual or effective date, as per options.-journalSelectingDateFromOpts :: ReportOpts -> Journal -> Journal-journalSelectingDateFromOpts opts = journalSelectingDate (whichDateFromOpts opts)---- | Convert this journal's postings' amounts to the cost basis amounts if--- specified by options.-journalSelectingAmountFromOpts :: ReportOpts -> Journal -> Journal-journalSelectingAmountFromOpts opts- | cost_ opts = journalConvertAmountsToCost- | otherwise = id---- | Convert application options to the library's generic filter specification.-optsToFilterSpec :: ReportOpts -> Day -> FilterSpec-optsToFilterSpec opts@ReportOpts{..} d = FilterSpec {- datespan=dateSpanFromOpts d opts- ,cleared= clearedValueFromOpts opts- ,real=real_- ,empty=empty_- ,acctpats=apats- ,descpats=dpats- ,depth = depth_- }- where (apats,dpats) = parsePatternArgs patterns_---- | Gather filter pattern arguments into a list of account patterns and a--- list of description patterns. We interpret pattern arguments as--- follows: those prefixed with "desc:" are description patterns, all--- others are account patterns; also patterns prefixed with "not:" are--- negated. not: should come after desc: if both are used.-parsePatternArgs :: [String] -> ([String],[String])-parsePatternArgs args = (as, ds')- where- descprefix = "desc:"- (ds, as) = partition (descprefix `isPrefixOf`) args- ds' = map (drop (length descprefix)) ds------------------------------------------------------------------------------------- | A journal entries report is a list of whole transactions as--- originally entered in the journal (mostly). Used by eg hledger's print--- command and hledger-web's journal entries view.-type EntriesReport = [EntriesReportItem]-type EntriesReportItem = Transaction---- | Select transactions for an entries report.-entriesReport :: ReportOpts -> FilterSpec -> Journal -> EntriesReport-entriesReport opts fspec j = sortBy (comparing f) $ jtxns $ filterJournalTransactions fspec j'- where- f = transactionDateFn opts- j' = journalSelectingAmountFromOpts opts j------------------------------------------------------------------------------------- | A postings report is a list of postings with a running total, a label--- for the total field, and a little extra transaction info to help with rendering.-type PostingsReport = (String -- label for the running balance column XXX remove- ,[PostingsReportItem] -- line items, one per posting- )-type PostingsReportItem = (Maybe (Day, String) -- transaction date and description if this is the first posting- ,Posting -- the posting- ,MixedAmount -- the running total after this posting- )---- | Select postings from the journal and add running balance and other--- information to make a postings report. Used by eg hledger's register command.-postingsReport :: ReportOpts -> FilterSpec -> Journal -> PostingsReport-postingsReport opts fspec j = (totallabel, postingsReportItems ps nullposting startbal (+))- where- ps | interval == NoInterval = displayableps- | otherwise = summarisePostingsByInterval interval depth empty reportspan displayableps- j' = journalSelectingDateFromOpts opts- $ journalSelectingAmountFromOpts opts- j- (precedingps, displayableps, _) = postingsMatchingDisplayExpr (display_ opts)- $ depthClipPostings depth- $ journalPostings- $ filterJournalPostings fspec{depth=Nothing}- j'- (interval, depth, empty, displayexpr) = (intervalFromOpts opts, depth_ opts, empty_ opts, display_ opts)- journalspan = journalDateSpan j'- -- requestedspan should be the intersection of any span specified- -- with period options and any span specified with display option.- -- The latter is not easily available, fake it for now.- requestedspan = periodspan `spanIntersect` displayspan- periodspan = datespan fspec- displayspan = postingsDateSpan ps- where (_,ps,_) = postingsMatchingDisplayExpr displayexpr $ journalPostings j'- matchedspan = postingsDateSpan displayableps- reportspan | empty = requestedspan `orDatesFrom` journalspan- | otherwise = requestedspan `spanIntersect` matchedspan- startbal = sumPostings precedingps--totallabel = "Total"-balancelabel = "Balance"---- | Generate postings report line items.-postingsReportItems :: [Posting] -> Posting -> MixedAmount -> (MixedAmount -> MixedAmount -> MixedAmount) -> [PostingsReportItem]-postingsReportItems [] _ _ _ = []-postingsReportItems (p:ps) pprev b sumfn = i:(postingsReportItems ps p b' sumfn)- where- i = mkpostingsReportItem isfirst p b'- isfirst = ptransaction p /= ptransaction pprev- b' = b `sumfn` pamount p---- | Generate one postings report line item, from a flag indicating--- whether to include transaction info, a posting, and the current running--- balance.-mkpostingsReportItem :: Bool -> Posting -> MixedAmount -> PostingsReportItem-mkpostingsReportItem False p b = (Nothing, p, b)-mkpostingsReportItem True p b = (ds, p, b)- where ds = case ptransaction p of Just (Transaction{tdate=da,tdescription=de}) -> Just (da,de)- Nothing -> Just (nulldate,"")---- | Date-sort and split a list of postings into three spans - postings matched--- by the given display expression, and the preceding and following postings.-postingsMatchingDisplayExpr :: Maybe String -> [Posting] -> ([Posting],[Posting],[Posting])-postingsMatchingDisplayExpr d ps = (before, matched, after)- where- sorted = sortBy (comparing postingDate) ps- (before, rest) = break (displayExprMatches d) sorted- (matched, after) = span (displayExprMatches d) rest---- | Does this display expression allow this posting to be displayed ?--- Raises an error if the display expression can't be parsed.-displayExprMatches :: Maybe String -> Posting -> Bool-displayExprMatches Nothing _ = True-displayExprMatches (Just d) p = (fromparse $ parsewith datedisplayexpr d) p---- | Parse a hledger display expression, which is a simple date test like--- "d>[DATE]" or "d<=[DATE]", and return a "Posting"-matching predicate.-datedisplayexpr :: GenParser Char st (Posting -> Bool)-datedisplayexpr = do- char 'd'- op <- compareop- char '['- (y,m,d) <- smartdate- char ']'- let date = parsedate $ printf "%04s/%02s/%02s" y m d- test op = return $ (`op` date) . postingDate- case op of- "<" -> test (<)- "<=" -> test (<=)- "=" -> test (==)- "==" -> test (==)- ">=" -> test (>=)- ">" -> test (>)- _ -> mzero- where- compareop = choice $ map (try . string) ["<=",">=","==","<","=",">"]---- | Clip the account names to the specified depth in a list of postings.-depthClipPostings :: Maybe Int -> [Posting] -> [Posting]-depthClipPostings depth = map (depthClipPosting depth)---- | Clip a posting's account name to the specified depth.-depthClipPosting :: Maybe Int -> Posting -> Posting-depthClipPosting Nothing p = p-depthClipPosting (Just d) p@Posting{paccount=a} = p{paccount=clipAccountName d a}---- XXX confusing, refactor---- | Convert a list of postings into summary postings. Summary postings--- are one per account per interval and aggregated to the specified depth--- if any.-summarisePostingsByInterval :: Interval -> Maybe Int -> Bool -> DateSpan -> [Posting] -> [Posting]-summarisePostingsByInterval interval depth empty reportspan ps = concatMap summarisespan $ splitSpan interval reportspan- where- summarisespan s = summarisePostingsInDateSpan s depth empty (postingsinspan s)- postingsinspan s = filter (isPostingInDateSpan s) ps---- | Given a date span (representing a reporting interval) and a list of--- postings within it: aggregate the postings so there is only one per--- account, and adjust their date/description so that they will render--- as a summary for this interval.------ As usual with date spans the end date is exclusive, but for display--- purposes we show the previous day as end date, like ledger.------ When a depth argument is present, postings to accounts of greater--- depth are aggregated where possible.------ The showempty flag includes spans with no postings and also postings--- with 0 amount.-summarisePostingsInDateSpan :: DateSpan -> Maybe Int -> Bool -> [Posting] -> [Posting]-summarisePostingsInDateSpan (DateSpan b e) depth showempty ps- | null ps && (isNothing b || isNothing e) = []- | null ps && showempty = [summaryp]- | otherwise = summaryps'- where- summaryp = summaryPosting b' ("- "++ showDate (addDays (-1) e'))- b' = fromMaybe (maybe nulldate postingDate $ headMay ps) b- e' = fromMaybe (maybe (addDays 1 nulldate) postingDate $ lastMay ps) e- summaryPosting date desc = nullposting{ptransaction=Just nulltransaction{tdate=date,tdescription=desc}}-- summaryps' = (if showempty then id else filter (not . isZeroMixedAmount . pamount)) summaryps- summaryps = [summaryp{paccount=a,pamount=balancetoshowfor a} | a <- clippedanames]- anames = sort $ nub $ map paccount ps- -- aggregate balances by account, like journalToLedger, then do depth-clipping- (_,_,exclbalof,inclbalof) = groupPostings ps- clippedanames = nub $ map (clipAccountName d) anames- isclipped a = accountNameLevel a >= d- d = fromMaybe 99999 $ depth- balancetoshowfor a =- (if isclipped a then inclbalof else exclbalof) (if null a then "top" else a)------------------------------------------------------------------------------------- | A transactions report includes a list of transactions--- (posting-filtered and unfiltered variants), a running balance, and some--- other information helpful for rendering a register view (a flag--- indicating multiple other accounts and a display string describing--- them) with or without a notion of current account(s).-type TransactionsReport = (String -- label for the balance column, eg "balance" or "total"- ,[TransactionsReportItem] -- line items, one per transaction- )-type TransactionsReportItem = (Transaction -- the corresponding transaction- ,Transaction -- the transaction with postings to the current account(s) removed- ,Bool -- is this a split, ie more than one other account posting- ,String -- a display string describing the other account(s), if any- ,MixedAmount -- the amount posted to the current account(s) (or total amount posted)- ,MixedAmount -- the running balance for the current account(s) after this transaction- )--triDate (t,_,_,_,_,_) = tdate t-triBalance (_,_,_,_,_,Mixed a) = case a of [] -> "0"- (Amount{quantity=q}):_ -> show q---- | Select transactions from the whole journal for a transactions report,--- with no \"current\" account. The end result is similar to--- "postingsReport" except it uses matchers and transaction-based report--- items and the items are most recent first. Used by eg hledger-web's--- journal view.-journalTransactionsReport :: ReportOpts -> Journal -> Matcher -> TransactionsReport-journalTransactionsReport _ Journal{jtxns=ts} m = (totallabel, items)- where- ts' = sortBy (comparing tdate) $ filter (not . null . tpostings) $ map (filterTransactionPostings m) ts- items = reverse $ accountTransactionsReportItems m Nothing nullmixedamt id ts'- -- XXX items' first element should be the full transaction with all postings------------------------------------------------------------------------------------- | Select transactions within one or more \"current\" accounts, and make a--- transactions report relative to those account(s). This means:------ 1. it shows transactions from the point of view of the current account(s).--- The transaction amount is the amount posted to the current account(s).--- The other accounts' names are provided. ------ 2. With no transaction filtering in effect other than a start date, it--- shows the accurate historical running balance for the current account(s).--- Otherwise it shows a running total starting at 0.------ Currently, reporting intervals are not supported, and report items are--- most recent first. Used by eg hledger-web's account register view.----accountTransactionsReport :: ReportOpts -> Journal -> Matcher -> Matcher -> TransactionsReport-accountTransactionsReport opts j m thisacctmatcher = (label, items)- where- -- transactions affecting this account, in date order- ts = sortBy (comparing tdate) $ filter (matchesTransaction thisacctmatcher) $ jtxns $- journalSelectingDateFromOpts opts $ journalSelectingAmountFromOpts opts j- -- starting balance: if we are filtering by a start date and nothing else,- -- the sum of postings to this account before that date; otherwise zero.- (startbal,label) | matcherIsNull m = (nullmixedamt, balancelabel)- | matcherIsStartDateOnly (effective_ opts) m = (sumPostings priorps, balancelabel)- | otherwise = (nullmixedamt, totallabel)- where- priorps = -- ltrace "priorps" $- filter (matchesPosting- (-- ltrace "priormatcher" $- MatchAnd [thisacctmatcher, tostartdatematcher]))- $ transactionsPostings ts- tostartdatematcher = MatchDate (DateSpan Nothing startdate)- startdate = matcherStartDate (effective_ opts) m- items = reverse $ accountTransactionsReportItems m (Just thisacctmatcher) startbal negate ts---- | Generate transactions report items from a list of transactions,--- using the provided query and current account matchers, starting balance,--- sign-setting function and balance-summing function.-accountTransactionsReportItems :: Matcher -> Maybe Matcher -> MixedAmount -> (MixedAmount -> MixedAmount) -> [Transaction] -> [TransactionsReportItem]-accountTransactionsReportItems _ _ _ _ [] = []-accountTransactionsReportItems matcher thisacctmatcher bal signfn (t:ts) =- -- This is used for both accountTransactionsReport and journalTransactionsReport,- -- which makes it a bit overcomplicated- case i of Just i' -> i':is- Nothing -> is- where- tmatched@Transaction{tpostings=psmatched} = filterTransactionPostings matcher t- (psthisacct,psotheracct) = case thisacctmatcher of Just m -> partition (matchesPosting m) psmatched- Nothing -> ([],psmatched)- numotheraccts = length $ nub $ map paccount psotheracct- amt = negate $ sum $ map pamount psthisacct- acct | isNothing thisacctmatcher = summarisePostings psmatched -- journal register- | numotheraccts == 0 = "transfer between " ++ summarisePostingAccounts psthisacct- | otherwise = prefix ++ summarisePostingAccounts psotheracct- where prefix = maybe "" (\b -> if b then "from " else "to ") $ isNegativeMixedAmount amt- (i,bal') = case psmatched of- [] -> (Nothing,bal)- _ -> (Just (t, tmatched, numotheraccts > 1, acct, a, b), b)- where- a = signfn amt- b = bal + a- is = accountTransactionsReportItems matcher thisacctmatcher bal' signfn ts---- | Generate a short readable summary of some postings, like--- "from (negatives) to (positives)".-summarisePostings :: [Posting] -> String-summarisePostings ps =- case (summarisePostingAccounts froms, summarisePostingAccounts tos) of- ("",t) -> "to "++t- (f,"") -> "from "++f- (f,t) -> "from "++f++" to "++t- where- (froms,tos) = partition (fromMaybe False . isNegativeMixedAmount . pamount) ps---- | Generate a simplified summary of some postings' accounts.-summarisePostingAccounts :: [Posting] -> String-summarisePostingAccounts = intercalate ", " . map accountLeafName . nub . map paccount--filterTransactionPostings :: Matcher -> Transaction -> Transaction-filterTransactionPostings m t@Transaction{tpostings=ps} = t{tpostings=filter (m `matchesPosting`) ps}------------------------------------------------------------------------------------- | An accounts report is a list of account names (full and short--- variants) with their balances, appropriate indentation for rendering as--- a hierarchy, and grand total.-type AccountsReport = ([AccountsReportItem] -- line items, one per account- ,MixedAmount -- total balance of all accounts- )-type AccountsReportItem = (AccountName -- full account name- ,AccountName -- short account name for display (the leaf name, prefixed by any boring parents immediately above)- ,Int -- how many steps to indent this account (0-based account depth excluding boring parents)- ,MixedAmount) -- account balance, includes subs unless --flat is present---- | Select accounts, and get their balances at the end of the selected--- period, and misc. display information, for an accounts report. Used by--- eg hledger's balance command.-accountsReport :: ReportOpts -> FilterSpec -> Journal -> AccountsReport-accountsReport opts filterspec j = accountsReport' opts j (journalToLedger filterspec)---- | Select accounts, and get their balances at the end of the selected--- period, and misc. display information, for an accounts report. Like--- "accountsReport" but uses the new matchers. Used by eg hledger-web's--- accounts sidebar.-accountsReport2 :: ReportOpts -> Matcher -> Journal -> AccountsReport-accountsReport2 opts matcher j = accountsReport' opts j (journalToLedger2 matcher)---- Accounts report helper.-accountsReport' :: ReportOpts -> Journal -> (Journal -> Ledger) -> AccountsReport-accountsReport' opts j jtol = (items, total)- where- items = map mkitem interestingaccts- interestingaccts | no_elide_ opts = acctnames- | otherwise = filter (isInteresting opts l) acctnames- acctnames = sort $ tail $ flatten $ treemap aname accttree- accttree = ledgerAccountTree (fromMaybe 99999 $ depth_ opts) l- total = sum $ map abalance $ ledgerTopAccounts l- l = jtol $ journalSelectingDateFromOpts opts $ journalSelectingAmountFromOpts opts j-- -- | Get data for one balance report line item.- mkitem :: AccountName -> AccountsReportItem- mkitem a = (a, adisplay, indent, abal)- where- adisplay | flat_ opts = a- | otherwise = accountNameFromComponents $ reverse (map accountLeafName ps) ++ [accountLeafName a]- where ps = takeWhile boring parents where boring = not . (`elem` interestingparents)- indent | flat_ opts = 0- | otherwise = length interestingparents- interestingparents = filter (`elem` interestingaccts) parents- parents = parentAccountNames a- abal | flat_ opts = exclusiveBalance acct- | otherwise = abalance acct- where acct = ledgerAccount l a--exclusiveBalance :: Account -> MixedAmount-exclusiveBalance = sumPostings . apostings---- | Is the named account considered interesting for this ledger's accounts report,--- following the eliding style of ledger's balance command ?-isInteresting :: ReportOpts -> Ledger -> AccountName -> Bool-isInteresting opts l a | flat_ opts = isInterestingFlat opts l a- | otherwise = isInterestingIndented opts l a---- | Determine whether an account should get its own line in the --flat balance report.-isInterestingFlat :: ReportOpts -> Ledger -> AccountName -> Bool-isInterestingFlat opts l a = notempty || emptyflag- where- acct = ledgerAccount l a- notempty = not $ isZeroMixedAmount $ exclusiveBalance acct- emptyflag = empty_ opts---- | Determine whether an account should get its own line in the indented--- balance report. Cf Balance module doc.-isInterestingIndented :: ReportOpts -> Ledger -> AccountName -> Bool-isInterestingIndented opts l a- | numinterestingsubs == 1 && samebalanceassub && not atmaxdepth = False- | numinterestingsubs < 2 && zerobalance && not emptyflag = False- | otherwise = True- where- atmaxdepth = isJust d && Just (accountNameLevel a) == d where d = depth_ opts- emptyflag = empty_ opts- acct = ledgerAccount l a- zerobalance = isZeroMixedAmount inclbalance where inclbalance = abalance acct- samebalanceassub = isZeroMixedAmount exclbalance where exclbalance = sumPostings $ apostings acct- numinterestingsubs = length $ filter isInterestingTree subtrees- where- isInterestingTree = treeany (isInteresting opts l . aname)- subtrees = map (fromJust . ledgerAccountTreeAt l) $ ledgerSubAccounts l $ ledgerAccount l a-----------------------------------------------------------------------------------tests_Hledger_Reports :: Test-tests_Hledger_Reports = TestList- [-- "summarisePostingsByInterval" ~: do- summarisePostingsByInterval (Quarters 1) Nothing False (DateSpan Nothing Nothing) [] ~?= []-- -- ,"summarisePostingsInDateSpan" ~: do- -- let gives (b,e,depth,showempty,ps) =- -- (summarisePostingsInDateSpan (mkdatespan b e) depth showempty ps `is`)- -- let ps =- -- [- -- nullposting{lpdescription="desc",lpaccount="expenses:food:groceries",lpamount=Mixed [dollars 1]}- -- ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining", lpamount=Mixed [dollars 2]}- -- ,nullposting{lpdescription="desc",lpaccount="expenses:food", lpamount=Mixed [dollars 4]}- -- ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining", lpamount=Mixed [dollars 8]}- -- ]- -- ("2008/01/01","2009/01/01",0,9999,False,[]) `gives`- -- []- -- ("2008/01/01","2009/01/01",0,9999,True,[]) `gives`- -- [- -- nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31"}- -- ]- -- ("2008/01/01","2009/01/01",0,9999,False,ts) `gives`- -- [- -- nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food", lpamount=Mixed [dollars 4]}- -- ,nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food:dining", lpamount=Mixed [dollars 10]}- -- ,nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food:groceries",lpamount=Mixed [dollars 1]}- -- ]- -- ("2008/01/01","2009/01/01",0,2,False,ts) `gives`- -- [- -- nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses:food",lpamount=Mixed [dollars 15]}- -- ]- -- ("2008/01/01","2009/01/01",0,1,False,ts) `gives`- -- [- -- nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="expenses",lpamount=Mixed [dollars 15]}- -- ]- -- ("2008/01/01","2009/01/01",0,0,False,ts) `gives`- -- [- -- nullposting{lpdate=parsedate "2008/01/01",lpdescription="- 2008/12/31",lpaccount="",lpamount=Mixed [dollars 15]}- -- ]+import Test.Tasty (testGroup)+import Hledger.Reports.ReportOptions+import Hledger.Reports.ReportTypes+import Hledger.Reports.AccountTransactionsReport+import Hledger.Reports.EntriesReport+import Hledger.Reports.PostingsReport+import Hledger.Reports.BalanceReport+import Hledger.Reports.MultiBalanceReport+import Hledger.Reports.BudgetReport - ]+tests_Reports = testGroup "Reports" [+ tests_BalanceReport+ ,tests_BudgetReport+ ,tests_AccountTransactionsReport+ ,tests_EntriesReport+ ,tests_MultiBalanceReport+ ,tests_PostingsReport+ ]
+ Hledger/Reports/AccountTransactionsReport.hs view
@@ -0,0 +1,348 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-|++An account-centric transactions report.++-}++module Hledger.Reports.AccountTransactionsReport (+ AccountTransactionsReport,+ AccountTransactionsReportItem,+ accountTransactionsReport,+ accountTransactionsReportWithStart,+ accountTransactionsReportItems,+ transactionRegisterDate,+ transactionRegisterDateExtra,+ triOrigTransaction,+ triDate,+ triAmount,+ triBalance,+ triCommodityAmount,+ triCommodityBalance,+ accountTransactionsReportByCommodity,+ filterAccountTransactionsReportByCommodity,+ tests_AccountTransactionsReport+)+where++import Data.Foldable (asum)+import Data.List (mapAccumR, nub, partition, sortBy)+import Data.List.Extra (nubSort)+import Data.Maybe (catMaybes, fromMaybe)+import Data.Ord (Down(..), comparing)+import Data.Text qualified as T+import Data.Time.Calendar (Day, fromGregorian)++import Hledger.Data+import Hledger.Query+import Hledger.Reports.PostingsReport (registerRunningCalculationFn)+import Hledger.Reports.ReportOptions+import Hledger.Utils+++-- | An account transactions report represents transactions affecting+-- a particular account (or possibly several accounts, but we don't+-- use that). It is used eg by hledger-ui's and hledger-web's register+-- view, and hledger's aregister report, where we want to show one row+-- per transaction, in the context of the current account. Report+-- items consist of:+--+-- - the transaction, unmodified+--+-- - the transaction as seen in the context of the current account and query,+-- which means:+--+-- - the transaction date is set to the "transaction context date":+-- the earliest of the transaction date and any other posting dates+-- of postings to the current account (matched by the report query).+--+-- - the transaction's postings are filtered, excluding any which are not+-- matched by the report query+--+-- - a text description of the other account(s) posted to/from+--+-- - a flag indicating whether there's more than one other account involved+--+-- - the total increase/decrease to the current account+--+-- - the report transactions' running total after this transaction;+-- or if historical balance is requested (-H), the historical running total;+-- or if average is requested (-A), the running average change per transaction+-- (also including transactions before the report start date, with -H).+-- The historical running total includes transactions from before the+-- report start date if one is specified, filtered by the report query.+-- The historical running total may or may not be the account's historical+-- running balance, depending on the report query.+--+-- Items are sorted by transaction register date (the earliest date the transaction+-- posts to the current account), most recent first.+-- Reporting intervals are currently ignored.+--+type AccountTransactionsReport = [AccountTransactionsReportItem] -- line items, one per transaction++type AccountTransactionsReportItem =+ (+ 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 (or running average), after this transaction+ )++instance HasAmounts AccountTransactionsReportItem where+ styleAmounts styles (torig,tacct,b,c,a1,a2) =+ (styleAmounts styles torig,styleAmounts styles tacct,b,c,styleAmounts styles a1,styleAmounts styles a2)++triOrigTransaction (torig,_,_,_,_,_) = torig+triDate (_,tacct,_,_,_,_) = tdate tacct+triAmount (_,_,_,_,a,_) = a+triBalance (_,_,_,_,_,a) = a+triCommodityAmount c = filterMixedAmountByCommodity c . triAmount+triCommodityBalance c = filterMixedAmountByCommodity c . triBalance++accountTransactionsReport :: ReportSpec -> Journal -> Query -> AccountTransactionsReport+accountTransactionsReport rspec j = snd . accountTransactionsReportWithStart rspec j++-- | The account transactions report, and the balance its running total+-- starts from: zero, or, with historical balances and a start date in+-- the query, the sum of the account's postings before that date (with+-- --average, their average per transaction). A register can show the+-- latter as a balance brought forward.+accountTransactionsReportWithStart :: ReportSpec -> Journal -> Query -> (MixedAmount, AccountTransactionsReport)+accountTransactionsReportWithStart rspec@ReportSpec{_rsReportOpts=ropts} j thisacctq = (startbal, items)+ where+ -- A depth limit should not affect the account transactions report; it should show all transactions in/below this account.+ -- Queries on currency or amount are also ignored at this stage; they are handled earlier, before valuation.+ reportq = simplifyQuery $ And [aregisterq, periodq]+ where+ aregisterq = filterQuery (not . queryIsCurOrAmt) . filterQuery (not . queryIsDepth) $ _rsQuery rspec+ periodq = Date . periodAsDateSpan $ period_ ropts+ amtq = filterQuery queryIsCurOrAmt $ _rsQuery rspec+ queryIsCurOrAmt q = queryIsCur q || queryIsAmt q+ wd = whichDate ropts++ -- Note that within this function, we are only allowed limited+ -- transformation of the transaction postings: this is due to the need to+ -- pass the original transactions into accountTransactionsReportItem.+ -- Generally, we either include a transaction in full, or not at all.+ -- Do some limited filtering and valuing of the journal's transactions:+ -- - filter them by the account query if any,+ -- - discard amounts not matched by the currency and amount query if any,+ -- - then apply valuation if any.+ -- Additional reportq filtering, such as date filtering, happens down in + -- accountTransactionsReportItem, which discards transactions with no matched postings.+ acctJournal =+ -- With most calls we will not require transaction prices past this point, and can get a big+ -- speed improvement by stripping them early. In some cases, such as in hledger-ui, we still+ -- want to keep prices around, so we can toggle between cost and no cost quickly. We can use+ -- the show_costs_ flag to be efficient when we can, and detailed when we have to.+ (if show_costs_ ropts then id else journalMapPostingAmounts mixedAmountStripCosts)+ . dbg5With (("ts3:\n"++).pshowTransactions.jtxns)+ -- maybe convert these transactions to cost or value+ . journalApplyValuationFromOpts rspec+ . dbg5With (("ts2:\n"++).pshowTransactions.jtxns)+ -- apply any cur: or amt: filters in reportq+ . (if queryIsNull amtq then id else filterJournalAmounts amtq)+ -- only consider transactions which match thisacctq (possibly excluding postings+ -- which are not real or have the wrong status)+ . dbg3Msg ("thisacctq: "++show thisacctq)+ $ dbg5With (("ts1:\n"++).pshowTransactions.jtxns)+ j{jtxns = filter (matchesTransaction thisacctq . relevantPostings) $ jtxns j}+ where+ relevantPostings+ | queryIsNull realq && queryIsNull statusq = id+ | otherwise = filterTransactionPostings . simplifyQuery $ And [realq, statusq]+ realq = filterQuery queryIsReal reportq+ statusq = filterQuery queryIsStatus reportq++ -- The number of the first report item, and the running total or average before it.+ -- In historical mode, these include the transactions before the report start date.+ (startnum, startbal)+ | balanceaccum_ ropts /= Historical = (1, nullmixedamt)+ | average_ ropts = (numpriorts + 1, divideMixedAmount (fromIntegral numpriorts) priorsum)+ | otherwise = (numpriorts + 1, priorsum)+ -- The account's postings before the report start, and their sum: the balance brought forward+ -- in historical mode, and the starting point for the real balances tested by balance: query terms.+ priorpss = dbg5 "priorpss" . filter (not . null) . map (filter hasAmount . tpostings) . jtxns $+ filterJournalPostings priorq acctJournal+ numpriorts = length priorpss+ priorsum = sumPostings $ concat priorpss+ priorq = dbg5 "priorq" $ And [thisacctq, tostartdateq, datelessreportq]+ where+ -- The postings before the report start, by whichever kind of date+ -- the query's start date is: the report's kind if it has one,+ -- else the other, so that a date2: term selects the prior postings+ -- by secondary date as it selects the report's postings.+ -- With no start date, there are no prior postings.+ tostartdateq = fromMaybe None $ asum [cutoff (date2_ ropts), cutoff (not $ date2_ ropts)]+ cutoff secondary =+ (if secondary then Date2 else Date) . DateSpan Nothing . Just . Exact+ <$> queryStartDate secondary reportq+ datelessreportq = filterQuery (not . queryIsDateOrDate2) reportq++ items =+ accountTransactionsReportItems reportq (_rsRowQuery rspec) thisacctq (registerRunningCalculationFn ropts) startnum startbal priorsum maNegate (journalAccountType j)+ -- sort by the transaction's register date, then index, for accurate starting balance+ . dbg5With (("ts4:\n"++).pshowTransactions.map snd)+ . sortBy (comparing (Down . fst) <> comparing (Down . tindex . snd))+ . map (\t -> (transactionRegisterDateExtra (journalAccountType j) wd reportq thisacctq t, t))+ . map (if invert_ ropts then (\t -> t{tpostings = map postingNegateMainAmount $ tpostings t}) else id)+ $ jtxns acctJournal++pshowTransactions :: [Transaction] -> String+pshowTransactions = pshow . map (\t -> unwords [show $ tdate t, T.unpack $ tdescription t])++-- | Generate transactions report items from a list of transactions,+-- using the provided user-specified report query, the report query's change:/balance:+-- terms (selecting items by their change to the account, or the account's real balance+-- after them; hidden items still count in the running total), a query specifying+-- which account to use as the focus, a running calculation function+-- (see registerRunningCalculationFn), the starting item number,+-- the running total/average and the real balance before the first item,+-- and a sign-setting function.+-- Each transaction is accompanied by the date that should be shown for it+-- in the report. This is not necessarily the transaction date - see+-- transactionRegisterDate.+accountTransactionsReportItems :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)+ -> Int -> MixedAmount -> MixedAmount -> (MixedAmount -> MixedAmount)+ -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)]+ -> [AccountTransactionsReportItem]+accountTransactionsReportItems reportq rowq thisacctq runningcalc i bal realbal signfn accttypefn =+ catMaybes . snd . mapAccumR (accountTransactionsReportItem reportq rowq thisacctq runningcalc signfn accttypefn) (i, bal, realbal)++accountTransactionsReportItem :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)+ -> (MixedAmount -> MixedAmount)+ -> (AccountName -> Maybe AccountType) -> (Int, MixedAmount, MixedAmount) -> (Day, Transaction)+ -> ((Int, MixedAmount, MixedAmount), Maybe AccountTransactionsReportItem)+accountTransactionsReportItem reportq rowq thisacctq runningcalc signfn accttypefn (i, bal, realbal) (d, t)+ -- 201407: I've lost my grip on this, let's just hope for the best+ -- 201606: we now calculate change and balance from filtered postings, check this still works well for all callers XXX+ | null reportps = ((i, bal, realbal), Nothing) -- no matched postings in this transaction, skip it+ | not $ matchesRowAmounts rowq amt realbal' = ((i + 1, bal', realbal'), Nothing) -- its change/balance doesn't match the row terms: hide it, but count it+ | otherwise = ((i + 1, bal', realbal'), Just (t, tacct{tdate=d}, numotheraccts > 1, otheraccts, amt, bal'))+ where+ tacct@Transaction{tpostings=reportps} = filterTransactionPostingsExtra accttypefn reportq t -- TODO needs to consider --date2, #1731+ (thisacctps, otheracctps) = partition (matchesPosting thisacctq) reportps+ numotheraccts = length $ nub $ map paccount otheracctps+ otheraccts | thisacctq == None = summarisePostingAccounts reportps -- no current account ? summarise all matched postings+ | numotheraccts == 0 = summarisePostingAccounts thisacctps -- only postings to current account ? summarise those+ | otherwise = summarisePostingAccounts otheracctps -- summarise matched postings to other account(s)+ -- 202302: Impact of t on thisacct - normally the sum of thisacctps,+ -- but if they are null it probably means reportq is an account filter+ -- and we should sum otheracctps instead.+ -- This fixes hledger areg ACCT ACCT2 (#2007), hopefully it's correct in general.+ amt+ | null thisacctps = signfn $ sumPostings otheracctps+ | otherwise = signfn . maNegate $ sumPostings thisacctps+ bal' = runningcalc i bal amt+ realbal' = if queryHasBalance rowq then maPlus realbal amt else nullmixedamt++-- TODO needs checking, cf #1731+-- | What date should be shown for a transaction in an account register report ?+-- This will be in context of a particular account (the "this account" query)+-- and any additional report query. It could be:+--+-- - if postings are matched by both thisacctq and reportq, the earliest of those+-- matched postings' dates (or their secondary dates if --date2 was used)+--+-- - the transaction date, or its secondary date if --date2 was used.+--+transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day+transactionRegisterDate = transactionRegisterDateExtra (const Nothing)++-- | Like 'transactionRegisterDate', but given the accounts' types, so+-- that a type: term in the report query matches postings here as it+-- does in the report itself.+transactionRegisterDateExtra :: (AccountName -> Maybe AccountType) -> WhichDate -> Query -> Query -> Transaction -> Day+transactionRegisterDateExtra accttypefn wd reportq thisacctq t+ | not $ null thisacctps = minimum $ map (postingDateOrDate2 wd) thisacctps+ | otherwise = transactionDateOrDate2 wd t+ where+ reportps = tpostings $ filterTransactionPostingsExtra accttypefn reportq t+ thisacctps = filter (matchesPosting thisacctq) reportps++-- -- | Generate a short readable summary of some postings, like+-- -- "from (negatives) to (positives)".+-- summarisePostings :: [Posting] -> String+-- summarisePostings ps =+-- case (summarisePostingAccounts froms, summarisePostingAccounts tos) of+-- ("",t) -> "to "++t+-- (f,"") -> "from "++f+-- (f,t) -> "from "++f++" to "++t+-- where+-- (froms,tos) = partition (fromMaybe False . isNegativeMixedAmount . pamount) ps++-- | Generate a simplified summary of some postings' accounts.+-- To reduce noise, if there are both real and virtual postings, show only the real ones.+summarisePostingAccounts :: [Posting] -> [AccountName]+summarisePostingAccounts ps = map paccount displayps+ where+ realps = filter isReal ps+ displayps | null realps = ps+ | otherwise = realps++-- | Split an account transactions report whose items may involve several commodities,+-- into one or more single-commodity account transactions reports.+accountTransactionsReportByCommodity :: AccountTransactionsReport -> [(CommoditySymbol, AccountTransactionsReport)]+accountTransactionsReportByCommodity tr =+ [(c, filterAccountTransactionsReportByCommodity c tr) | c <- commodities tr]+ where+ commodities = nubSort . map acommodity . concatMap (amounts . triAmount)++-- | Remove account transaction report items and item amount (and running+-- balance amount) components that don't involve the specified+-- commodity. Other item fields such as the transaction are left unchanged.+filterAccountTransactionsReportByCommodity :: CommoditySymbol -> AccountTransactionsReport -> AccountTransactionsReport+filterAccountTransactionsReportByCommodity comm =+ fixTransactionsReportItemBalances . concatMap (filterTransactionsReportItemByCommodity comm)+ where+ filterTransactionsReportItemByCommodity c (t,t2,s,o,a,bal)+ | c `elem` cs = [item']+ | otherwise = []+ where+ cs = map acommodity $ amounts a+ item' = (t,t2,s,o,a',bal)+ a' = filterMixedAmountByCommodity c a++ fixTransactionsReportItemBalances [] = []+ fixTransactionsReportItemBalances [i] = [i]+ fixTransactionsReportItemBalances items = reverse $ i:(go startbal is)+ where+ i:is = reverse items+ startbal = filterMixedAmountByCommodity comm $ triBalance i+ go _ [] = []+ go bal ((t,t2,s,o,amt,_):is') = (t,t2,s,o,amt,bal'):go bal' is'+ where bal' = bal `maPlus` amt++-- tests++tests_AccountTransactionsReport = testGroup "AccountTransactionsReport" [+ testCase "accountTransactionsReportWithStart" $ do+ let checking = Acct $ toRegex' "assets:bank:checking"+ fromJune = Date $ DateSpan (Just $ Exact $ fromGregorian 2008 6 1) Nothing+ rspec accum = defreportspec{_rsQuery=fromJune, _rsReportOpts=defreportopts{balanceaccum_=accum}}+ (histstart, histitems) = accountTransactionsReportWithStart (rspec Historical) samplejournal checking+ (start, items) = accountTransactionsReportWithStart (rspec PerPeriod) samplejournal checking+ -- with historical balances, the running balance starts from the postings before the start date+ showMixedAmount histstart @?= "$1.00"+ map (showMixedAmount . triBalance) histitems @?= ["$1.00", "$2.00", "$1.00", "$2.00"]+ -- otherwise from zero+ showMixedAmount start @?= "0"+ map (showMixedAmount . triBalance) items @?= ["0", "$1.00", "0", "$1.00"]+ -- a date2: start date counts too, by secondary date (here the same days)+ let fromJune2 = Date2 $ DateSpan (Just $ Exact $ fromGregorian 2008 6 1) Nothing+ (histstart2, _) = accountTransactionsReportWithStart (rspec Historical){_rsQuery=fromJune2} samplejournal checking+ showMixedAmount histstart2 @?= "$1.00"++ ,testCase "transactionRegisterDateExtra" $ do+ let t = nulltransaction{tdate=fromGregorian 2008 1 1, tpostings=[+ ("assets:bank:checking" `post` usd 1){pdate=Just $ fromGregorian 2008 1 5}+ ,"income:salary" `post` usd (-1)]}+ checking = Acct $ toRegex' "assets:bank:checking"+ assettypes a = if "assets" `T.isPrefixOf` a then Just Asset else Nothing+ -- a type: term in the report query matches the posting only when the account types are known+ transactionRegisterDate PrimaryDate (Type [Asset]) checking t @?= fromGregorian 2008 1 1+ transactionRegisterDateExtra assettypes PrimaryDate (Type [Asset]) checking t @?= fromGregorian 2008 1 5+ ]
+ Hledger/Reports/BalanceReport.hs view
@@ -0,0 +1,330 @@+{-|++Balance report, used by the balance command.++-}++{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Hledger.Reports.BalanceReport (+ BalanceReport,+ BalanceReportItem,+ balanceReport,+ flatShowsExclusiveBalance,++ -- * Tests+ tests_BalanceReport+)+where++import Data.Time.Calendar++import Hledger.Data+import Hledger.Query+import Hledger.Utils+import Hledger.Reports.MultiBalanceReport (multiBalanceReport)+import Hledger.Reports.ReportOptions+import Hledger.Reports.ReportTypes+++-- | A simple balance report. It has:+--+-- 1. a list of items, one per account, each containing:+--+-- * the full account name+--+-- * the Ledger-style elided short account name+-- (the leaf account name, prefixed by any boring parents immediately above);+-- or with --flat, the full account name again+--+-- * the number of indentation steps for rendering a Ledger-style account tree,+-- taking into account elided boring parents, --no-elide and --flat+--+-- * an amount+--+-- 2. the total of all amounts+--+type BalanceReport = ([BalanceReportItem], MixedAmount)+type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount)++instance HasAmounts BalanceReportItem where+ styleAmounts styles (a,b,c,d) = (a,b,c,styleAmounts styles d)++-- | When true (the default), this makes balance --flat reports and their implementation clearer.+-- Single/multi-col balance reports currently aren't all correct if this is false.+flatShowsExclusiveBalance = True++-- | Enabling this makes balance --flat --empty also show parent accounts without postings,+-- in addition to those with postings and a zero balance. Disabling it shows only the latter.+-- No longer supported, but leave this here for a bit.+-- flatShowsPostinglessAccounts = True++-- | Generate a simple balance report, containing the matched accounts and+-- their balances (change of balance) during the specified period.+-- If the normalbalance_ option is set, it adjusts the sorting and sign of+-- amounts (see ReportOpts and CompoundBalanceCommand).+balanceReport :: ReportSpec -> Journal -> BalanceReport+balanceReport rspec j = (rows, total)+ where+ report = multiBalanceReport rspec j+ rows = [( prrFullName row+ , prrDisplayName row+ , prrIndent row+ , prrTotal row+ ) | row <- prRows report]+ total = prrTotal $ prTotals report+++-- tests++Right samplejournal2 =+ journalBalanceTransactions defbalancingopts+ nulljournal{+ jtxns = [+ txnTieKnot Transaction{+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2008 01 01,+ tdate2=Just $ fromGregorian 2009 01 01,+ tstatus=Unmarked,+ tcode="",+ tdescription="income",+ tcomment="",+ ttags=[],+ tpostings=+ [posting {paccount="assets:bank:checking", pamount=mixedAmount (usd 1)}+ ,posting {paccount="income:salary", pamount=missingmixedamt}+ ],+ tprecedingcomment=""+ }+ ]+ }++tests_BalanceReport = testGroup "BalanceReport" [++ let+ (rspec,journal) `gives` r = do+ let opts' = rspec{_rsQuery=And [queryFromFlags $ _rsReportOpts rspec, _rsQuery rspec]}+ (eitems, etotal) = r+ (aitems, atotal) = balanceReport opts' journal+ showw (acct,acct',indent,amt) = (acct, acct', indent, showMixedAmountDebug amt)+ (map showw aitems) @?= (map showw eitems)+ (showMixedAmountDebug atotal) @?= (showMixedAmountDebug etotal)+ in+ testGroup "balanceReport" [++ testCase "no args, null journal" $+ (defreportspec, nulljournal) `gives` ([], nullmixedamt)++ ,testCase "no args, sample journal" $+ (defreportspec, samplejournal) `gives`+ ([+ ("assets:bank:checking","assets:bank:checking",0, mixedAmount (usd 1))+ ,("assets:bank:saving","assets:bank:saving",0, mixedAmount (usd 1))+ ,("assets:cash","assets:cash",0, mixedAmount (usd (-2)))+ ,("expenses:food","expenses:food",0, mixedAmount (usd 1))+ ,("expenses:supplies","expenses:supplies",0, mixedAmount (usd 1))+ ,("income:gifts","income:gifts",0, mixedAmount (usd (-1)))+ ,("income:salary","income:salary",0, mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with --tree" $+ (defreportspec{_rsReportOpts=defreportopts{accountlistmode_=ALTree}}, samplejournal) `gives`+ ([+ ("assets","assets",0, mixedAmount (usd 0))+ ,("assets:bank","bank",1, mixedAmount (usd 2))+ ,("assets:bank:checking","checking",2, mixedAmount (usd 1))+ ,("assets:bank:saving","saving",2, mixedAmount (usd 1))+ ,("assets:cash","cash",1, mixedAmount (usd (-2)))+ ,("expenses","expenses",0, mixedAmount (usd 2))+ ,("expenses:food","food",1, mixedAmount (usd 1))+ ,("expenses:supplies","supplies",1, mixedAmount (usd 1))+ ,("income","income",0, mixedAmount (usd (-2)))+ ,("income:gifts","gifts",1, mixedAmount (usd (-1)))+ ,("income:salary","salary",1, mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with --depth=N" $+ (defreportspec{_rsReportOpts=defreportopts{depth_=DepthSpec (Just 1) []}}, samplejournal) `gives`+ ([+ ("expenses", "expenses", 0, mixedAmount (usd 2))+ ,("income", "income", 0, mixedAmount (usd (-2)))+ ],+ mixedAmount (usd 0))++ ,testCase "with depth:N" $+ (defreportspec{_rsQuery=Depth 1}, samplejournal) `gives`+ ([+ ("expenses", "expenses", 0, mixedAmount (usd 2))+ ,("income", "income", 0, mixedAmount (usd (-2)))+ ],+ mixedAmount (usd 0))++ ,testCase "with date:" $+ (defreportspec{_rsQuery=Date $ DateSpan (Just $ Exact $ fromGregorian 2009 01 01) (Just $ Exact $ fromGregorian 2010 01 01)}, samplejournal2) `gives`+ ([], nullmixedamt)++ ,testCase "with date2:" $+ (defreportspec{_rsQuery=Date2 $ DateSpan (Just $ Exact $ fromGregorian 2009 01 01) (Just $ Exact $ fromGregorian 2010 01 01)}, samplejournal2) `gives`+ ([+ ("assets:bank:checking","assets:bank:checking",0,mixedAmount (usd 1))+ ,("income:salary","income:salary",0,mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with desc:" $+ (defreportspec{_rsQuery=Desc $ toRegexCI' "income"}, samplejournal) `gives`+ ([+ ("assets:bank:checking","assets:bank:checking",0,mixedAmount (usd 1))+ ,("income:salary","income:salary",0, mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with not:desc:" $+ (defreportspec{_rsQuery=Not . Desc $ toRegexCI' "income"}, samplejournal) `gives`+ ([+ ("assets:bank:saving","assets:bank:saving",0, mixedAmount (usd 1))+ ,("assets:cash","assets:cash",0, mixedAmount (usd (-2)))+ ,("expenses:food","expenses:food",0, mixedAmount (usd 1))+ ,("expenses:supplies","expenses:supplies",0, mixedAmount (usd 1))+ ,("income:gifts","income:gifts",0, mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with period on a populated period" $+ (defreportspec{_rsReportOpts=defreportopts{period_= PeriodBetween (fromGregorian 2008 1 1) (fromGregorian 2008 1 2)}}, samplejournal) `gives`+ (+ [+ ("assets:bank:checking","assets:bank:checking",0, mixedAmount (usd 1))+ ,("income:salary","income:salary",0, mixedAmount (usd (-1)))+ ],+ mixedAmount (usd 0))++ ,testCase "with period on an unpopulated period" $+ (defreportspec{_rsReportOpts=defreportopts{period_= PeriodBetween (fromGregorian 2008 1 2) (fromGregorian 2008 1 3)}}, samplejournal) `gives`+ ([], nullmixedamt)++++ {-+ ,testCase "accounts report with account pattern o" ~:+ defreportopts{patterns_=["o"]} `gives`+ [" $1 expenses:food"+ ," $-2 income"+ ," $-1 gifts"+ ," $-1 salary"+ ,"--------------------"+ ," $-1"+ ]++ ,testCase "accounts report with account pattern o and --depth 1" ~:+ defreportopts{patterns_=["o"],depth_=(Just 1, [])} `gives`+ [" $1 expenses"+ ," $-2 income"+ ,"--------------------"+ ," $-1"+ ]++ ,testCase "accounts report with account pattern a" ~:+ defreportopts{patterns_=["a"]} `gives`+ [" $-1 assets"+ ," $1 bank:saving"+ ," $-2 cash"+ ," $-1 income:salary"+ ," $1 liabilities:debts"+ ,"--------------------"+ ," $-1"+ ]++ ,testCase "accounts 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"+ ]++ ,testCase "accounts report with unmatched parent of two matched subaccounts" ~:+ defreportopts{patterns_=["cash","saving"]} `gives`+ [" $-1 assets"+ ," $1 bank:saving"+ ," $-2 cash"+ ,"--------------------"+ ," $-1"+ ]++ ,testCase "accounts report with multi-part account name" ~:+ defreportopts{patterns_=["expenses:food"]} `gives`+ [" $1 expenses:food"+ ,"--------------------"+ ," $1"+ ]++ ,testCase "accounts 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"+ ]++ ,testCase "accounts report negative account pattern always matches full name" ~:+ defreportopts{patterns_=["not:e"]} `gives`+ ["--------------------"+ ," 0"+ ]++ ,testCase "accounts report negative patterns affect totals" ~:+ defreportopts{patterns_=["expenses","not:food"]} `gives`+ [" $1 expenses:supplies"+ ,"--------------------"+ ," $1"+ ]++ ,testCase "accounts report with -E shows zero-balance accounts" ~:+ defreportopts{patterns_=["assets"],empty_=True} `gives`+ [" $-1 assets"+ ," $1 bank"+ ," 0 checking"+ ," $1 saving"+ ," $-2 cash"+ ,"--------------------"+ ," $-1"+ ]++ ,testCase "accounts report with cost basis" $+ j <- (readJournal def Nothing $ unlines+ [""+ ,"2008/1/1 test "+ ," a:b 10h @ $50"+ ," c:d "+ ]) >>= either error' return+ let j' = journalCanonicaliseAmounts $ journalToCost ToCost j -- enable cost basis adjustment+ balanceReportAsText defreportopts (balanceReport defreportopts Any j') `is`+ [" $500 a:b"+ ," $-500 c:d"+ ,"--------------------"+ ," 0"+ ]+ -}+ ]++ ]+
+ Hledger/Reports/BudgetReport.hs view
@@ -0,0 +1,268 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Hledger.Reports.BudgetReport (+ BudgetGoal,+ BudgetTotal,+ BudgetAverage,+ BudgetCell,+ BudgetReportRow,+ BudgetReport,+ budgetReport,+ -- * Tests+ tests_BudgetReport+)+where++import Control.Applicative ((<|>))+import Control.Monad ((>=>))+import Data.Bifunctor (bimap)+import Data.Foldable (toList)+import Data.List (find, maximumBy, intercalate)+import Data.Maybe (catMaybes, fromMaybe, isJust)+import Data.Map qualified as M+import Data.Ord (comparing)+import Data.Set qualified as S+import Data.Text qualified as T+import Data.These (These(..), these)+import Safe (minimumDef)++import Hledger.Data+import Hledger.Query+import Hledger.Utils+import Hledger.Reports.ReportOptions+import Hledger.Reports.ReportTypes+import Hledger.Reports.MultiBalanceReport++-- All MixedAmounts:+type BudgetGoal = Change+type BudgetTotal = Total+type BudgetAverage = Average++-- | A budget report tracks expected and actual changes per account and subperiod.+-- Each table cell has an actual change amount and/or a budget goal amount.+type BudgetCell = (Maybe Change, Maybe BudgetGoal)+-- | A row in a budget report table - account name and data cells.+type BudgetReportRow = PeriodicReportRow DisplayName BudgetCell+-- | A full budget report table.+type BudgetReport = PeriodicReport DisplayName BudgetCell++_brrShowDebug :: BudgetReportRow -> String+_brrShowDebug (PeriodicReportRow dname budgetpairs _tot _avg) =+ unwords [+ T.unpack $ displayFull dname,+ "",+ intercalate " | "+ [ maybe "-" showMixedAmount mactual <> " [" <> maybe "-" showMixedAmount mgoal <> "]"+ | (mactual,mgoal) <- budgetpairs ]+ ]++-- | Calculate per-account, per-period budget (balance change) goals+-- from all periodic transactions, calculate actual balance changes+-- from the regular transactions, and compare these to get a 'BudgetReport'.+-- Unbudgeted accounts may be hidden or renamed (see journalWithBudgetAccountNames).+budgetReport :: ReportSpec -> BalancingOpts -> DateSpan -> Journal -> BudgetReport+budgetReport rspec bopts reportspan j = dbg4 "sortedbudgetreport" budgetreport+ where+ -- Budget report demands ALTree mode to ensure subaccounts and subaccount budgets are properly handled+ -- and that reports with and without --empty make sense when compared side by side+ ropts = (_rsReportOpts rspec){ accountlistmode_ = ALTree }+ -- ropts = _rsReportOpts rspec+ showunbudgeted = empty_ ropts++ budgetedaccts =+ dbg3 "budgetedacctsinperiod" $+ S.fromList $+ expandAccountNames $+ accountNamesFromPostings $+ concatMap tpostings $+ concatMap (\pt -> runPeriodicTransaction False pt reportspan) $+ jperiodictxns j++ actualj = journalWithBudgetAccountNames budgetedaccts showunbudgeted j+ budgetj = journalAddBudgetGoalTransactions bopts ropts reportspan j+ priceoracle = journalPriceOracle (infer_prices_ ropts) j++ -- The report spec used for selecting budget goals, with the query terms+ -- that describe actual transactions/postings dropped. (#2545)+ -- The change:/balance: terms are applied below, to the combined rows.+ budgetrspec = rspec{_rsQuery = budgetGoalQuery $ _rsQuery rspec, _rsRowQuery = Any}+ actualrspec = rspec{_rsRowQuery = Any}++ (_, actualspans) = dbg5 "actualspans" $ reportSpan actualj rspec+ (_, budgetspans) = dbg5 "budgetspans" $ reportSpan budgetj budgetrspec+ allspans = dbg5 "allspans" $ case (interval_ ropts, budgetspans) of+ -- If no interval is specified:+ -- budgetgoalreport's span might be shorter actualreport's due to periodic txns;+ -- it should be safe to replace it with the latter, so they combine well.+ (NoInterval, _) -> actualspans+ (_, Nothing) -> actualspans+ (_, Just bspan) -> unionDayPartitions bspan =<< actualspans++ actualps = dbg5 "actualps" $ getPostings rspec actualj priceoracle reportspan -- rspec, so a balance: term fetches the earlier postings+ budgetps = dbg5 "budgetps" $ getPostings budgetrspec budgetj priceoracle reportspan++ actualAcct = dbg5 "actualAcct" $ generateMultiBalanceAccount actualrspec actualj priceoracle actualspans actualps+ budgetAcct = dbg5 "budgetAcct" $ generateMultiBalanceAccount budgetrspec budgetj priceoracle budgetspans budgetps++ combinedAcct = dbg5 "combinedAcct" . hideNonMatchingRows $ if null budgetps+ -- If no budget postings, just use actual account, to avoid unnecssary budget zeros+ then This <$> actualAcct+ else mergeAccounts actualAcct budgetAcct++ -- Apply the change:/balance: terms, if any, by hiding the rows whose actual change over the+ -- report period, or actual balance at its end (including subaccounts), doesn't match.+ -- Unlike other balance reports, this doesn't change the other rows or the totals,+ -- since budget goals are often set on parent accounts.+ hideNonMatchingRows+ | queryIsNull rowq = id+ | otherwise = mapAccounts $ \a -> if matches a then a else a{aboring = True}+ where+ rowq = _rsRowQuery rspec+ matches a = uncurry (matchesRowAmounts rowq) $ inclusiveRowAmounts (aname a)+ -- Each account's own change and end balance, from the actual postings (clipped as the report clips them),+ inclusiveRowAmounts a = (maSum $ map fst amts, maSum $ map snd amts)+ where amts = [cb | (n, cb) <- M.toList ownRowAmounts, n == a || (a <> ":") `T.isPrefixOf` n]+ ownRowAmounts = accountRowAmounts rspec actualj priceoracle actualspans+ [p{paccount = clipOrEllipsifyAccountName (queryDepth $ _rsQuery rspec) $ paccount p} | p <- actualps]++ budgetreport = generateBudgetReport ropts allspans combinedAcct++-- | Reduce a report query to the terms which are meaningful for selecting budget goals:+-- the account, account type, depth, date and commodity terms.+-- The remaining terms (status, code, description, payee, note, tag, realness, amount)+-- describe actual transactions and postings, and are dropped;+-- budget goal transactions are synthetic, so applying those terms to them+-- would discard budget goals unexpectedly (#2545).+budgetGoalQuery :: Query -> Query+budgetGoalQuery = filterQuery selectsAccountOrPeriod+ where+ selectsAccountOrPeriod q = case q of+ Acct{} -> True+ DepthAcct{} -> True+ Depth{} -> True+ Type{} -> True+ Date{} -> True+ Date2{} -> True+ Cur{} -> True+ None -> True+ Not q' -> selectsAccountOrPeriod q'+ _ -> False++-- | Lay out a set of postings grouped by date span into a regular matrix with rows+-- given by AccountName and columns by DateSpan, then generate a MultiBalanceReport+-- from the columns.+generateBudgetReport :: ReportOpts -> Maybe DayPartition -> Account (These BalanceData BalanceData) -> BudgetReport+generateBudgetReport = generatePeriodicReport makeBudgetReportRow treeActualBalance flatActualBalance+ where+ treeActualBalance = these bdincludingsubs (const nullmixedamt) (const . bdincludingsubs)+ flatActualBalance = fromMaybe nullmixedamt . fst++-- | Build a report row.+--+-- Calculate the column totals. These are always the sum of column amounts.+makeBudgetReportRow :: ReportOpts -> (BalanceData -> MixedAmount)+ -> a -> Account (These BalanceData BalanceData) -> PeriodicReportRow a BudgetCell+makeBudgetReportRow ropts balance =+ makePeriodicReportRow (Just nullmixedamt, Nothing) avg ropts (theseToMaybe . bimap balance balance)+ where+ avg xs = ((actualtotal, budgettotal), (actualavg, budgetavg))+ where+ (actuals, budgets) = unzip $ toList xs+ (actualtotal, actualavg) = bimap Just Just . sumAndAverageMixedAmounts $ catMaybes actuals+ (budgettotal, budgetavg) = bimap Just Just . sumAndAverageMixedAmounts $ catMaybes budgets++ theseToMaybe (This a) = (Just a, Nothing)+ theseToMaybe (That b) = (Just nullmixedamt, Just b)+ theseToMaybe (These a b) = (Just a, Just b)++-- | Use all (or all matched by --budget's argument) periodic transactions in the journal +-- to generate budget goal transactions in the specified date span (and before, to support+-- --historical. The precise start date is the natural start date of the largest interval+-- of the active periodic transaction rules that is on or before the earlier of journal start date,+-- report start date.)+-- Budget goal transactions are similar to forecast transactions except their purpose +-- and effect is to define balance change goals, per account and period, for BudgetReport.+--+journalAddBudgetGoalTransactions :: BalancingOpts -> ReportOpts -> DateSpan -> Journal -> Journal+journalAddBudgetGoalTransactions bopts ropts reportspan j =+ either error' id $ -- PARTIAL:+ (journalStyleAmounts >=> journalBalanceTransactions bopts) j{ jtxns = budgetts }+ where+ budgetspan = dbg3 "budget span" $ DateSpan (Exact <$> mbudgetgoalsstartdate) (Exact <$> spanEnd reportspan)+ where+ mbudgetgoalsstartdate =+ -- We want to also generate budget goal txns before the report start date, in case -H is used.+ -- What should the actual starting date for goal txns be ? This gets tricky. + -- Consider a journal with a "~ monthly" periodic transaction rule, where the first transaction is on 1/5.+ -- Users will certainly expect a budget goal for january, but "~ monthly" generates transactions+ -- on the first of month, and starting from 1/5 would exclude 1/1.+ -- Secondly, consider a rule like "~ every february 2nd from 2020/01"; we should not start that+ -- before 2020-02-02.+ -- Hopefully the following algorithm produces intuitive behaviour in general:+ -- from the earlier of the journal start date and the report start date,+ -- move backward to the nearest natural start date of the largest period seen among the+ -- active periodic transactions, unless that is disallowed by a start date in the periodic rule.+ -- (Do we need to pay attention to an end date in the rule ? Don't think so.)+ -- (So with "~ monthly", the journal start date 1/5 is adjusted to 1/1.)+ case minimumDef Nothing $ filter isJust [journalStartDate False j, spanStart reportspan] of+ Nothing -> Nothing+ Just d -> Just d'+ where+ -- the interval and any date span of the periodic transaction with longest period+ (intervl, spn) =+ case budgetpts of+ [] -> (Days 1, nulldatespan)+ pts -> (ptinterval pt, ptspan pt)+ where pt = maximumBy (comparing ptinterval) pts -- PARTIAL: maximumBy won't fail+ -- the natural start of this interval on or before the journal/report start+ intervalstart = intervalBoundaryBefore intervl d+ -- the natural interval start before the journal/report start,+ -- or the rule-specified start if later,+ -- but no later than the journal/report start.+ d' = min d $ maybe intervalstart (max intervalstart) $ spanStart spn++ -- select periodic transactions matching a pattern+ -- (the argument of the (final) --budget option).+ -- XXX two limitations/wishes, requiring more extensive type changes:+ -- - give an error if pat is non-null and matches no periodic txns+ -- - allow a regexp or a full hledger query, not just a substring+ pat = fromMaybe "" $ dbg3 "budget pattern" $ T.toLower <$> budgetpat_ ropts+ budgetpts = [pt | pt <- jperiodictxns j, pat `T.isInfixOf` T.toLower (ptdescription pt)]+ budgetts =+ dbg5 "budget goal txns" $+ [makeBudgetTxn t+ | pt <- budgetpts+ , t <- runPeriodicTransaction False pt budgetspan+ ]+ makeBudgetTxn t = txnTieKnot $ t { tdescription = T.pack "Budget transaction" }++-- | Adjust a journal's account names for budget reporting, in two ways:+--+-- 1. accounts with no budget goal anywhere in their ancestry are moved+-- under the "unbudgeted" top level account.+--+-- 2. subaccounts with no budget goal are merged with their closest parent account+-- with a budget goal, so that only budgeted accounts are shown.+-- This can be disabled by -E/--empty.+--+journalWithBudgetAccountNames :: S.Set AccountName -> Bool -> Journal -> Journal+journalWithBudgetAccountNames budgetedaccts showunbudgeted j =+ dbg5With (("budget account names: "++).pshow.journalAccountNamesUsed) $+ j { jtxns = remapTxn <$> jtxns j }+ where+ remapTxn = txnTieKnot . transactionTransformPostings remapPosting+ remapPosting p = p { paccount = remapAccount $ paccount p, poriginal = poriginal p <|> Just p }+ remapAccount a+ | a `S.member` budgetedaccts = a+ | Just p <- budgetedparent = if showunbudgeted then a else p+ | otherwise = if showunbudgeted then u <> acctsep <> a else u+ where+ budgetedparent = find (`S.member` budgetedaccts) $ parentAccountNames a+ u = unbudgetedAccountName+++-- tests++tests_BudgetReport = testGroup "BudgetReport" [+ ]
+ Hledger/Reports/EntriesReport.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-|++Journal entries report, used by the print command.++-}++module Hledger.Reports.EntriesReport (+ EntriesReport,+ EntriesReportItem,+ entriesReport,+ entriesReportUnsorted,+ -- * Tests+ tests_EntriesReport+)+where++import Data.List (sortBy)+import Data.Ord (comparing)+import Data.Time (fromGregorian)++import Hledger.Data+import Hledger.Query (Query(..), filterQuery, matchesRowAmounts, queryIsDepth, queryIsNull)+import Hledger.Reports.ReportOptions+import Hledger.Utils+++-- | A journal entries report is a list of whole transactions as+-- originally entered in the journal (mostly). This is used by eg+-- hledger's print command and hledger-web's journal entries view.+type EntriesReport = [EntriesReportItem]+type EntriesReportItem = Transaction++-- | Select transactions for an entries report, sorted by date.+entriesReport :: ReportSpec -> Journal -> EntriesReport+entriesReport rspec@ReportSpec{_rsReportOpts=ropts} =+ sortBy (comparing $ transactionDateFn ropts) . entriesReportUnsorted rspec++-- | Select transactions for an entries report, keeping their journal order.+-- The query's change: and balance: terms, if any, are both tested against each entry's sum of postings+-- (an entry has no balance), converted to cost as in transaction balancing (see 'transactionBalancingSum'),+-- regardless of valuation and --invert.+entriesReportUnsorted :: ReportSpec -> Journal -> EntriesReport+entriesReportUnsorted rspec@ReportSpec{_rsReportOpts=ropts, _rsRowQuery=rowq} =+ map (if invert_ ropts then transactionNegate else id)+ . jtxns+ . journalApplyValuationFromOpts (setDefaultConversionOp NoConversionOp rspec)+ . filterJournalTransactions (filterQuery (not.queryIsDepth) $ _rsQuery rspec)+ . (if queryIsNull rowq then id else \j -> j{jtxns = filter (\t -> let s = transactionBalancingSum t in matchesRowAmounts rowq s s) $ jtxns j})++tests_EntriesReport = testGroup "EntriesReport" [+ testGroup "entriesReport" [+ testCase "not acct" $ (length $ entriesReport defreportspec{_rsQuery=Not . Acct $ toRegex' "bank"} samplejournal) @?= 1+ ,testCase "date" $ (length $ entriesReport defreportspec{_rsQuery=Date $ DateSpan (Just $ Exact $ fromGregorian 2008 06 01) (Just $ Exact $ fromGregorian 2008 07 01)} samplejournal) @?= 3+ ]+ ]+
+ Hledger/Reports/MultiBalanceReport.hs view
@@ -0,0 +1,639 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-|++Multi-column balance reports, used by the balance command.++-}++module Hledger.Reports.MultiBalanceReport (+ MultiBalanceReport,+ MultiBalanceReportRow,++ multiBalanceReport,+ multiBalanceReportWith,++ compoundBalanceReport,+ compoundBalanceReportWith,++ -- * Helper functions+ makeReportQuery,+ balanceReportStyles,+ getPostings,+ accountRowAmounts,+ generateMultiBalanceAccount,+ generatePeriodicReport,+ makePeriodicReportRow,+ rowTotal,++ -- -- * Tests+ tests_MultiBalanceReport+)+where++#if !MIN_VERSION_base(4,18,0)+import Control.Applicative (liftA2)+#endif+import Control.Monad (guard)+import Data.Containers.ListUtils (nubOrdOn)+import Data.Foldable (toList)+import Data.HashSet qualified as HS+import Data.List (sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.List.NonEmpty (NonEmpty((:|)))+import Data.Map qualified as M+import Data.Maybe (fromMaybe, isJust)+import Data.Ord (Down(..))+import Data.Semigroup (sconcat)+import Data.These (these)+import Data.Time.Calendar (Day(..), fromGregorian)+import Data.Traversable (mapAccumL)++import Hledger.Data+import Hledger.Query+import Hledger.Utils+import Hledger.Reports.ReportOptions+import Hledger.Reports.ReportTypes+++-- | A multi balance report is a kind of periodic report, where the amounts+-- correspond to balance changes or ending balances in a given period. It has:+--+-- 1. a list of each column's period (date span)+--+-- 2. a list of rows, each containing:+--+-- * the full account name, display name, and display depth+--+-- * A list of amounts, one for each column.+--+-- * the total of the row's amounts for a periodic report+--+-- * the average of the row's amounts+--+-- 3. the column totals, and the overall grand total (or zero for+-- cumulative/historical reports) and grand average.++type MultiBalanceReport = PeriodicReport DisplayName MixedAmount+type MultiBalanceReportRow = PeriodicReportRow DisplayName MixedAmount+++-- | Generate a multicolumn balance report for the matched accounts,+-- showing the change of balance, accumulated balance, or historical balance+-- in each of the specified periods. If the normalbalance_ option is set, it+-- adjusts the sorting and sign of amounts (see ReportOpts and+-- CompoundBalanceCommand). hledger's most powerful and useful report, used+-- by the balance command (in multiperiod mode) and (via compoundBalanceReport)+-- by the bs/cf/is commands.+multiBalanceReport :: ReportSpec -> Journal -> MultiBalanceReport+multiBalanceReport rspec j = multiBalanceReportWith rspec j (journalPriceOracle infer j)+ where infer = infer_prices_ $ _rsReportOpts rspec++-- | A helper for multiBalanceReport. This one takes some extra arguments,+-- a 'PriceOracle' to be used for looking up market prices, and a set of+-- 'AccountName's which should not be elided. Commands which run multiple+-- reports (bs etc.) can generate the price oracle just once for efficiency,+-- passing it to each report by calling this function directly.+multiBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> MultiBalanceReport+multiBalanceReportWith rspec' j priceoracle = report+ where+ -- Queries, report/column dates.+ (reportspan, colspans) = dbg5 "multiBalanceReportWith reportSpan" $ reportSpan j rspec'+ rspec = dbg3 "multiBalanceReportWith rspec" $ makeReportQuery rspec' reportspan+ -- force evaluation order to show price lookup after date spans in debug output (XXX not working)+ -- priceoracle = reportspan `seq` priceoracle0++ -- Get postings+ ps = dbg5 "multiBalanceReportWith ps" $ getPostings rspec j priceoracle reportspan++ -- Process changes into normal, cumulative, or historical amounts, plus value them and mark which are uninteresting+ acct = dbg5 "multiBalanceReportWith acct" $ generateMultiBalanceAccount rspec j priceoracle colspans ps++ -- Generate and postprocess the report, negating balances and taking percentages if needed+ report = dbg4 "multiBalanceReportWith report" $ generateMultiBalanceReport (_rsReportOpts rspec) colspans acct++-- | Generate a compound balance report from a list of CBCSubreportSpec. This+-- shares postings between the subreports.+compoundBalanceReport :: ReportSpec -> Journal -> [CBCSubreportSpec a]+ -> CompoundPeriodicReport a MixedAmount+compoundBalanceReport rspec j = compoundBalanceReportWith rspec j (journalPriceOracle infer j)+ where infer = infer_prices_ $ _rsReportOpts rspec++-- | A helper for compoundBalanceReport, similar to multiBalanceReportWith.+compoundBalanceReportWith :: ReportSpec -> Journal -> PriceOracle+ -> [CBCSubreportSpec a]+ -> CompoundPeriodicReport a MixedAmount+compoundBalanceReportWith rspec' j priceoracle subreportspecs = cbr+ where+ -- Queries, report/column dates.+ (reportspan, colspans) = dbg5 "compoundBalanceReportWith reportSpan" $ reportSpan j rspec'+ rspec = dbg3 "compoundBalanceReportWith rspec" $ makeReportQuery rspec' reportspan++ -- Get postings+ ps = dbg5 "compoundBalanceReportWith ps" $ getPostings rspec j priceoracle reportspan++ subreports = map generateSubreport subreportspecs+ where+ generateSubreport CBCSubreportSpec{..} =+ ( cbcsubreporttitle+ -- Postprocess the report, negating balances and taking percentages if needed+ , cbcsubreporttransform $ generateMultiBalanceReport ropts colspans acct+ , cbcsubreportincreasestotal+ )+ where+ ropts = cbcsubreportoptions $ _rsReportOpts rspec+ -- Add a restriction to this subreport to the report query.+ -- XXX in non-thorough way, consider updateReportSpec ?+ rspecsub = rspec{_rsReportOpts=ropts, _rsQuery=And [cbcsubreportquery, _rsQuery rspec]}+ -- Match and postings for the subreport+ subreportps = countSign $ filter (matchesPostingExtra (journalAccountType j) cbcsubreportquery) ps+ -- With --count, a normally negative subreport counts each posting as -1,+ -- so that its display negation shows positive counts.+ countSign+ | counting && normalbalance_ ropts == Just NormallyNegative = map postingNegateMainAmount+ | otherwise = id+ -- Account representing this subreport+ acct = generateMultiBalanceAccount rspecsub j priceoracle colspans subreportps++ -- Sum the subreport totals by column. Handle these cases:+ -- - no subreports+ -- - empty subreports, having no subtotals (#588)+ -- - subreports with a shorter subtotals row than the others+ -- With --count, the subreports' counts are all added.+ overalltotals = case subreports of+ [] -> PeriodicReportRow () [] nullmixedamt nullmixedamt+ (r:rs) -> sconcat $ fmap subreportTotal (r:|rs)+ where+ subreportTotal (_, sr, increasestotal) =+ (if increasestotal || counting then id else fmap maNegate) $ prTotals sr++ counting = balanceCalcIsCount $ balancecalc_ (_rsReportOpts rspec)++ cbr = CompoundPeriodicReport "" (maybeDayPartitionToDateSpans colspans) subreports overalltotals+++-- | Remove any date queries and insert queries from the report span.+-- The user's query expanded to the report span+-- if there is one (otherwise any date queries are left as-is, which+-- handles the hledger-ui+future txns case above).+makeReportQuery :: ReportSpec -> DateSpan -> ReportSpec+makeReportQuery rspec reportspan+ | reportspan == nulldatespan = rspec+ | otherwise = rspec{_rsQuery=query}+ where+ query = simplifyQuery $ And [dateless $ _rsQuery rspec, reportspandatesq]+ reportspandatesq = dbg3 "makeReportQuery reportspandatesq" $ dateqcons reportspan+ dateless = dbg3 "makeReportQuery dateless" . filterQuery (not . queryIsDateOrDate2)+ dateqcons = if date2_ (_rsReportOpts rspec) then Date2 else Date++-- | Gather postings matching the query within the report period.+getPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting]+getPostings rspec@ReportSpec{_rsQuery=query, _rsRowQuery=rowq, _rsReportOpts=ropts} j priceoracle reportspan =+ setPostingsCount+ . filter hasAmount -- omit postings with no definite amount (#2571)+ . journalPostings+ $ journalValueAndFilterPostingsWith rspec' j priceoracle+ where+ -- If counting postings or transactions, set all posting amounts to "1".+ setPostingsCount+ | balanceCalcIsCount (balancecalc_ ropts) = map (postingTransformAmount (const $ mixed [num 1]))+ | otherwise = id++ rspec' = rspec{_rsQuery=fullreportq,_rsReportOpts=ropts'}+ -- If we're re-valuing every period, we need to have the unvalued start+ -- balance, so we can do it ourselves later.+ ropts' = if isJust (valuationAfterSum ropts)+ then ropts{period_=dateSpanAsPeriod fullreportspan, value_=Nothing} -- If we're valuing after the sum, don't do it now+ else ropts{period_=dateSpanAsPeriod fullreportspan}++ -- q projected back before the report start date.+ -- When there's no report start date, in case there are future txns (the hledger-ui case above),+ -- we use emptydatespan to make sure they aren't counted as starting balance.+ fullreportq = dbg3 "getPostings fullreportq" $ And [datelessq, fullreportspanq]+ datelessq = dbg3 "getPostings datelessq" $ filterQuery (not . queryIsDateOrDate2) depthlessq++ -- The user's query with no depth limit, and expanded to the report span+ -- if there is one (otherwise any date queries are left as-is, which+ -- handles the hledger-ui+future txns case above).+ depthlessq = dbg3 "getPostings depthlessq" $ filterQuery (not . queryIsDepth) query++ -- Historical reports, and balance: query terms, need the postings before the report start too.+ fullreportspan = if requiresHistorical ropts || queryHasBalance rowq then DateSpan Nothing (Exact <$> spanEnd reportspan) else reportspan+ fullreportspanq = (if date2_ ropts then Date2 else Date) $ case fullreportspan of+ DateSpan Nothing Nothing -> emptydatespan+ a -> a++-- | Generate the 'Account' for the requested multi-balance report from a list+-- of 'Posting's.+generateMultiBalanceAccount :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> Account BalanceData+generateMultiBalanceAccount rspec@ReportSpec{_rsReportOpts=ropts} j priceoracle colspans =+ -- Set account declaration info (for sorting purposes)+ mapAccounts (accountSetDeclarationInfo j)+ -- Add declared accounts if called with --declared and --empty+ . (if (declared_ ropts && empty_ ropts) then addDeclaredAccounts rspec j else id)+ -- Mark which accounts are boring and which are interesting+ . markAccountBoring rspec+ -- Negate amounts if applicable+ . (if invert_ ropts then fmap (mapBalanceData maNegate) else id)+ -- Process changes into normal, cumulative, or historical amounts, plus value them+ . calculateReportAccount rspec j priceoracle colspans+ -- Leave out the postings of accounts whose change or balance doesn't match the change:/balance: query terms, if any+ . applyRowQuery rspec j priceoracle colspans+ -- If counting transactions, keep just one posting per transaction and (clipped) account+ . (if balancecalc_ ropts == CalcTransactionsCount then nubOrdOn txnAndAccount else id)+ -- Clip account names+ . map clipPosting+ where+ txnAndAccount p = (tindex <$> ptransaction p, paccount p)+ -- Clip postings to the requested depth according to the query+ clipPosting p = p{paccount = clipOrEllipsifyAccountName depthSpec $ paccount p}+ depthSpec = dbg3 "generateMultiBalanceAccount depthSpec"+ . queryDepth . filterQuery queryIsDepth $ _rsQuery rspec++-- | Add declared accounts to the account tree.+addDeclaredAccounts :: Monoid a => ReportSpec -> Journal -> Account a -> Account a+addDeclaredAccounts rspec j acct =+ these id id const <$> mergeAccounts acct declaredTree+ where+ declaredTree =+ mapAccounts (\a -> a{aboring = not $ aname a `HS.member` HS.fromList declaredAccounts}) $+ accountTreeFromBalanceAndNames "root" (mempty <$ adata acct) declaredAccounts++ -- With --declared, add the query-matching declared accounts (as dummy postings+ -- so they are processed like the rest).+ declaredAccounts =+ map (clipOrEllipsifyAccountName depthSpec) .+ filter (matchesAccountExtra (journalAccountType j) (journalAccountTags j) accttypetagsq) $+ -- they have no postings, so their amount is zero+ (if matchesRowAmounts (_rsRowQuery rspec) nullmixedamt nullmixedamt then id else const []) $+ journalAccountNamesDeclared j++ accttypetagsq = dbg3 "addDeclaredAccounts accttypetagsq" .+ filterQueryOrNotQuery (\q -> queryIsAcct q || queryIsType q || queryIsTag q) $+ _rsQuery rspec++ depthSpec = queryDepth . filterQuery queryIsDepth $ _rsQuery rspec+++-- | Gather the account balance changes into a regular matrix, then+-- accumulate and value amounts, as specified by the report options.+-- Makes sure all report columns have an entry.+calculateReportAccount :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> Account BalanceData+calculateReportAccount _ _ _ Nothing _ =+ accountFromBalances "root" $ periodDataFromList mempty [(nulldate, mempty)]+calculateReportAccount rspec@ReportSpec{_rsReportOpts=ropts} j priceoracle (Just colspans) ps =+ mapPeriodData rowbals changesAcct+ where+ -- The valued row amounts to be displayed: per-period changes,+ -- zero-based cumulative totals, or+ -- starting-balance-based historical balances.+ rowbals :: PeriodData BalanceData -> PeriodData BalanceData+ rowbals unvaluedChanges = case balanceaccum_ ropts of+ PerPeriod -> changes+ Cumulative -> cumulative+ Historical -> historical+ where+ -- changes to report on: usually just the valued changes themselves, but use the+ -- differences in the valued historical amount for CalcValueChange and CalcGain.+ changes = case balancecalc_ ropts of+ CalcChange -> avalue unvaluedChanges+ CalcBudget -> avalue unvaluedChanges+ CalcValueChange -> periodChanges historical+ CalcGain -> periodChanges historical+ CalcPostingsCount -> avalue unvaluedChanges+ CalcTransactionsCount -> avalue unvaluedChanges+ -- the historical balance is the valued cumulative sum of all unvalued changes+ historical = avalue $ cumulativeSum unvaluedChanges+ -- since this is a cumulative sum of valued amounts, it should not be valued again+ cumulative = cumulativeSum changes{pdpre = mempty}+ avalue = periodDataValuation ropts j priceoracle colspans++ changesAcct = dbg5With (\x -> "calculateReportAccount changesAcct\n" ++ showAccounts x) .+ mapPeriodData (padPeriodData mempty (dayPartitionToPeriodData colspans)) $+ accountFromPostings getIntervalStartDate ps++ getIntervalStartDate p = fst $ dayPartitionFind (getPostingDate p) colspans+ getPostingDate = postingDateOrDate2 (whichDate (_rsReportOpts rspec))++-- | The valuation function to use for the chosen report options.+periodDataValuation :: ReportOpts -> Journal -> PriceOracle -> DayPartition+ -> PeriodData BalanceData -> PeriodData BalanceData+periodDataValuation ropts j priceoracle colspans =+ opPeriodData valueBalanceData (dayPartitionToPeriodData colspans)+ where+ valueBalanceData :: Day -> BalanceData -> BalanceData+ valueBalanceData d = mapBalanceData (valueMixedAmount d)++ valueMixedAmount :: Day -> MixedAmount -> MixedAmount+ valueMixedAmount = mixedAmountApplyValuationAfterSumFromOptsWith ropts j priceoracle++-- | Apply the report query's change: and balance: terms, if any, to these (clipped) postings:+-- leave out the postings of accounts whose own change over the report period, or own balance+-- at its end (their list mode row), doesn't match them. This acts like an account filter:+-- parent accounts' subaccount-inclusive balances, and the report's totals and percentages,+-- then reflect just the matching accounts. Amounts are tested with their real sign (not as+-- displayed after --invert or compound reports' sign normalisation), after any cost or value+-- conversion.+applyRowQuery :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> [Posting]+applyRowQuery rspec@ReportSpec{_rsRowQuery=rowq} j priceoracle mcolspans ps+ | queryIsNull rowq = ps+ | otherwise = filter ((`HS.member` matching) . paccount) ps+ where+ matching = HS.fromList [a | (a, (chg, bal)) <- M.toList $ accountRowAmounts rspec j priceoracle mcolspans ps+ , matchesRowAmounts rowq chg bal]++-- | Each account's own change over the report period, and own balance at the end of it,+-- from these postings (clipped to the report's depth), which may include postings before the+-- report start (see 'getPostings'); those count in the balances only. If valuation is to be+-- done after summing, the amounts are valued at the report end date.+accountRowAmounts :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> M.Map AccountName (MixedAmount, MixedAmount)+accountRowAmounts ReportSpec{_rsReportOpts=ropts} j priceoracle mcolspans ps =+ M.map (\(RowAmounts chg pre) -> (valued chg, valued $ maPlus pre chg)) $ foldl' add M.empty ps+ where+ add m p = M.insertWith (<>) (paccount p) amts m+ where amts | inPeriod p = RowAmounts (pamount p) nullmixedamt+ | otherwise = RowAmounts nullmixedamt (pamount p)+ inPeriod p = maybe True (isJust . fst . dayPartitionFind (postingDateOrDate2 (whichDate ropts) p)) mcolspans+ valued = maybe id (mixedAmountApplyValuationAfterSumFromOptsWith ropts j priceoracle . snd . dayPartitionStartEnd) mcolspans++-- | An account's change in the report period, and its balance before the report period.+data RowAmounts = RowAmounts !MixedAmount !MixedAmount+instance Semigroup RowAmounts where+ RowAmounts c1 p1 <> RowAmounts c2 p2 = RowAmounts (maPlus c1 c2) (maPlus p1 p2)++-- | Mark which nodes of an 'Account' are boring, and so should be omitted from reports.+markAccountBoring :: ReportSpec -> Account BalanceData -> Account BalanceData+markAccountBoring ReportSpec{_rsQuery=query,_rsRowQuery=rowq,_rsReportOpts=ropts}+ -- If depth 0, all accounts except the top-level account are boring+ | qdepthIsZero = markBoring False . mapAccounts (markBoring True)+ -- Otherwise the top level account is boring, and subaccounts are boring if+ -- they are both boring in and of themselves and are boring parents+ | otherwise = markBoring True . mapAccounts (markBoringBy (liftA2 (&&) isBoring isBoringParent))+ where+ -- Accounts boring on their own+ isBoring :: Account BalanceData -> Bool+ isBoring acct = tooDeep || allZeros+ where+ tooDeep = d > qdepth -- Throw out anything too deep+ allZeros = isZeroRow balance amts && not keepEmptyAccount -- Throw away everything with a zero balance in the row, unless..+ keepEmptyAccount = (empty_ ropts || hasbalanceq) && keepWhenEmpty acct -- We are keeping empty rows (or showing accounts by their balance,+ -- which may be unchanged in the period) and this row meets the criteria++ amts = pdperiods $ adata acct+ d = accountNameLevel $ aname acct++ qdepth = fromMaybe maxBound . getAccountNameClippedDepth depthspec $ aname acct+ balance = maybeStripPrices . case accountlistmode_ ropts of+ ALTree | d == qdepth -> bdincludingsubs+ _ -> bdexcludingsubs++ -- Accounts which don't have enough interesting subaccounts+ isBoringParent :: Account a -> Bool+ isBoringParent acct = case accountlistmode_ ropts of+ ALTree -> notEnoughSubs || droppedAccount+ ALFlat -> True+ where+ notEnoughSubs = length interestingSubs < minimumSubs+ droppedAccount = accountNameLevel (aname acct) <= drop_ ropts+ interestingSubs = filter (anyAccounts (not . aboring)) $ asubs acct+ minimumSubs = if no_elide_ ropts || atFoldDepth then 1 else 2+ atFoldDepth = fold_depth_ ropts == Just (accountNameLevel (aname acct))++ isZeroRow balance = all (mixedAmountLooksZero . balance)+ keepWhenEmpty acct = case accountlistmode_ ropts of+ ALTree -> null $ asubs acct -- In tree mode, keep only empty leaves+ ALFlat -> hasPostings acct -- In list mode, keep all accounts that have postings;+ || no_elide_ ropts && accountNameLevel (aname acct) > drop_ ropts && anyAccounts hasPostings acct+ -- or with --no-elide, also (undropped) parents of such accounts+ where hasPostings a = any ((0<) . bdnumpostings) $ (if hasbalanceq then (pdpre (adata a) :) else id) (toList . pdperiods $ adata a)+ -- a balance: query term keeps dormant accounts visible: their postings may all be before the report period+ hasbalanceq = queryHasBalance rowq+ maybeStripPrices = if conversionop_ ropts == Just NoConversionOp then id else mixedAmountStripCosts++ qdepthIsZero = depthspec == DepthSpec (Just 0) []+ depthspec = queryDepth query++ markBoring v a = a{aboring = v}+ markBoringBy f a = a{aboring = f a}+++-- | Build a report row.+--+-- Calculate the column totals. These are always the sum of column amounts.+generateMultiBalanceReport :: ReportOpts -> Maybe DayPartition -> Account BalanceData -> MultiBalanceReport+generateMultiBalanceReport ropts colspans =+ countAveragesPrecision . reportPercent ropts . generatePeriodicReport makeMultiBalanceReportRow bdincludingsubs id ropts colspans+ where+ -- Counts are whole numbers, but their averages are shown with one decimal place.+ countAveragesPrecision+ | balanceCalcIsCount (balancecalc_ ropts) && not (percent_ ropts) = \(PeriodicReport spans rows totals) ->+ PeriodicReport spans (map setAvgPrecision rows) (setAvgPrecision totals)+ | otherwise = id+ setAvgPrecision r = r{prrAverage = mixedAmountSetPrecision (Precision 1) $ prrAverage r}++-- | The display styles to apply to a balance report's amounts: the journal's commodity styles, hard-rounded,+-- except for counts, which keep their own (see generateMultiBalanceReport).+balanceReportStyles :: ReportOpts -> Journal -> M.Map CommoditySymbol AmountStyle+balanceReportStyles ropts j+ | balanceCalcIsCount (balancecalc_ ropts) = M.empty+ | otherwise = journalCommodityStylesWith HardRounding j++-- | Lay out a set of postings grouped by date span into a regular matrix with rows+-- given by AccountName and columns by DateSpan, then generate a MultiBalanceReport+-- from the columns.+generatePeriodicReport :: Show c =>+ (forall a. ReportOpts -> (BalanceData -> MixedAmount) -> a -> Account b -> PeriodicReportRow a c)+ -> (b -> MixedAmount) -> (c -> MixedAmount)+ -> ReportOpts -> Maybe DayPartition -> Account b -> PeriodicReport DisplayName c+generatePeriodicReport makeRow treeAmt flatAmt ropts colspans acct =+ PeriodicReport (maybeDayPartitionToDateSpans colspans) (buildAndSort acct) totalsrow+ where+ -- Build report rows and sort them+ buildAndSort = dbg5 "generatePeriodicReport buildAndSort" . case accountlistmode_ ropts of+ ALTree | sort_amount_ ropts -> buildRows . sortTreeByAmount+ ALFlat | sort_amount_ ropts -> sortFlatByAmount . buildRows+ _ -> buildRows . sortAccountTreeByDeclaration++ buildRows = buildReportRows makeRow ropts++ -- Calculate column totals from the inclusive balances of the root account+ totalsrow = dbg5 "generatePeriodicReport totalsrow" $ makeRow ropts bdincludingsubs () acct++ sortTreeByAmount = case fromMaybe NormallyPositive $ normalbalance_ ropts of+ NormallyPositive -> sortAccountTreeOn (\r -> (Down $ amt r, aname r))+ NormallyNegative -> sortAccountTreeOn (\r -> (amt r, aname r))+ where+ amt = mixedAmountStripCosts . sortKey . fmap treeAmt . pdperiods . adata+ sortKey = case balanceaccum_ ropts of+ PerPeriod -> maSum+ _ -> maybe nullmixedamt snd . M.lookupMax++ sortFlatByAmount = case fromMaybe NormallyPositive $ normalbalance_ ropts of+ NormallyPositive -> sortOn (\r -> (Down $ amt r, prrFullName r))+ NormallyNegative -> sortOn (\r -> (amt r, prrFullName r))+ where amt = mixedAmountStripCosts . flatAmt . prrTotal++-- | Build the report rows.+-- One row per account, with account name info, row amounts, row total and row average.+-- Rows are sorted according to the order in the 'Account' tree.+buildReportRows :: forall b c.+ (ReportOpts -> (BalanceData -> MixedAmount) -> DisplayName -> Account b -> PeriodicReportRow DisplayName c)+ -> ReportOpts -> Account b -> [PeriodicReportRow DisplayName c]+buildReportRows makeRow ropts = mkRows True (-drop_ ropts) 0+ where+ -- Build the row for an account at a given depth with some number of boring parents+ mkRows :: Bool -> Int -> Int -> Account b -> [PeriodicReportRow DisplayName c]+ mkRows isRoot d boringParents acct+ -- Account is boring and has no interesting children at any depth, so we stop+ | allBoring acct = []+ -- Account is a boring root account, and should be bypassed entirely+ | aboring acct && isRoot = buildSubrows d 0+ -- Account is boring and has been dropped, so should be skipped and move up the hierarchy+ | aboring acct && d < 0 = buildSubrows (d + 1) 0+ -- Account is boring, and we can omit boring parents, so we should omit but keep track+ | aboring acct && canOmitParents = buildSubrows d (boringParents + 1)+ -- Account is not boring or otherwise should be displayed.+ | otherwise = makeRow ropts balance displayname acct : buildSubrows (d + 1) 0+ where+ displayname = displayedName d boringParents $ aname acct+ buildSubrows i b = concatMap (mkRows False i b) $ asubs acct++ canOmitParents = flat_ ropts || not (no_elide_ ropts)+ allBoring a = aboring a && all allBoring (asubs a)+ balance = case accountlistmode_ ropts of+ ALTree -> bdincludingsubs+ ALFlat -> bdexcludingsubs++ displayedName d boringParents name+ | d == 0 && name == "root" = DisplayName "..." "..." 0+ | otherwise = case accountlistmode_ ropts of+ ALTree -> DisplayName name leaf $ max 0 d+ ALFlat -> DisplayName name droppedName 0+ where+ leaf = accountNameFromComponents+ . reverse . take (boringParents + 1) . reverse+ $ accountNameComponents droppedName+ droppedName = accountNameDrop (drop_ ropts) name+++-- | Build a report row.+--+-- Calculate the column totals. These are always the sum of column amounts.+makeMultiBalanceReportRow :: ReportOpts -> (BalanceData -> MixedAmount)+ -> a -> Account BalanceData -> PeriodicReportRow a MixedAmount+makeMultiBalanceReportRow = makePeriodicReportRow nullmixedamt sumAndAverageMixedAmounts++-- | Build a report row.+--+-- Calculate the column totals. These are always the sum of column amounts.+makePeriodicReportRow :: c -> (M.Map Day c -> (c, c))+ -> ReportOpts -> (b -> c)+ -> a -> Account b -> PeriodicReportRow a c+makePeriodicReportRow nullEntry totalAndAverage ropts balance name acct =+ PeriodicReportRow name (toList rowbals) rowtotal avg+ where+ rowbals = fmap balance . pdperiods $ adata acct+ (total, avg) = totalAndAverage rowbals+ rowtotal = rowTotal ropts nullEntry total rowbals++-- | A report row's total, given its amounts and their sum (or a null amount, for an empty row):+-- the sum, or for a cumulative or historical report, the last amount.+rowTotal :: ReportOpts -> c -> c -> M.Map Day c -> c+rowTotal ropts nullEntry total rowbals = case balanceaccum_ ropts of+ PerPeriod -> total+ _ -> maybe nullEntry snd $ M.lookupMax rowbals++-- | Map the report rows to percentages if needed+reportPercent :: ReportOpts -> MultiBalanceReport -> MultiBalanceReport+reportPercent ropts report@(PeriodicReport spans rows totalrow)+ | percent_ ropts = PeriodicReport spans (map percentRow rows) (percentRow totalrow)+ | otherwise = report+ where+ percentRow (PeriodicReportRow name rowvals rowtotal rowavg) =+ PeriodicReportRow name+ (zipWith perdivide rowvals $ prrAmounts totalrow)+ (perdivide rowtotal $ prrTotal totalrow)+ (perdivide rowavg $ prrAverage totalrow)++-- | A helper: what percentage is the second mixed amount of the first ?+-- Keeps the sign of the first amount.+-- Uses unifyMixedAmount to unify each argument and then divides them.+-- Both amounts should be in the same, single commodity.+-- This can call error if the arguments are not right.+perdivide :: MixedAmount -> MixedAmount -> MixedAmount+perdivide a b = fromMaybe (error' errmsg) $ do -- PARTIAL:+ a' <- unifyMixedAmount a+ b' <- unifyMixedAmount b+ guard $ amountIsZero a' || amountIsZero b' || acommodity a' == acommodity b'+ return $ mixed [per $ if aquantity b' == 0 then 0 else aquantity a' / abs (aquantity b') * 100]+ where errmsg = "Cannot calculate percentages if accounts have different commodities (Hint: Try --cost, -V or similar flags.)"++-- | Calculate a cumulative sum from a list of period changes.+cumulativeSum :: Traversable t => t BalanceData -> t BalanceData+cumulativeSum = snd . mapAccumL (\prev new -> let z = prev <> new in (z, z)) mempty++-- | Extract period changes from a cumulative list.+periodChanges :: Traversable t => t BalanceData -> t BalanceData+periodChanges = snd . mapAccumL (\prev new -> (new, opBalanceData maMinus new prev)) mempty++-- tests++tests_MultiBalanceReport = testGroup "MultiBalanceReport" [++ let+ amt0 = Amount {acommodity="$", aquantity=0, acost=Nothing, acostbasis=Nothing,+ astyle=AmountStyle {ascommodityside = L, ascommodityspaced = False, asdigitgroups = Nothing,+ asdecimalmark = Just '.', asprecision = Precision 2, asrounding = NoRounding}}+ (rspec,journal) `gives` r = do+ let rspec' = rspec{_rsQuery=And [queryFromFlags $ _rsReportOpts rspec, _rsQuery rspec]}+ (eitems, etotal) = r+ (PeriodicReport _ aitems atotal) = multiBalanceReport rspec' journal+ showw (PeriodicReportRow a lAmt amt amt')+ = (displayFull a, displayName a, displayIndent a, map showMixedAmountDebug lAmt, showMixedAmountDebug amt, showMixedAmountDebug amt')+ (map showw aitems) @?= (map showw eitems)+ showMixedAmountDebug (prrTotal atotal) @?= showMixedAmountDebug etotal -- we only check the sum of the totals+ in+ testGroup "multiBalanceReport" [+ testCase "null journal" $+ (defreportspec, nulljournal) `gives` ([], nullmixedamt)++ ,testCase "with -H on a populated period" $+ (defreportspec{_rsReportOpts=defreportopts{period_= PeriodBetween (fromGregorian 2008 1 1) (fromGregorian 2008 1 2), balanceaccum_=Historical}}, samplejournal) `gives`+ (+ [ PeriodicReportRow (flatDisplayName "assets:bank:checking") [mixedAmount $ usd 1] (mixedAmount $ usd 1) (mixedAmount amt0{aquantity=1})+ , PeriodicReportRow (flatDisplayName "income:salary") [mixedAmount $ usd (-1)] (mixedAmount $ usd (-1)) (mixedAmount amt0{aquantity=(-1)})+ ],+ mixedAmount $ usd 0)++ -- ,testCase "a valid history on an empty period" $+ -- (defreportopts{period_= PeriodBetween (fromGregorian 2008 1 2) (fromGregorian 2008 1 3), balanceaccum_=Historical}, samplejournal) `gives`+ -- (+ -- [+ -- ("assets:bank:checking","checking",3, [mamountp' "$1.00"], mamountp' "$1.00",mixedAmount amt0 {aquantity=1})+ -- ,("income:salary","salary",2, [mamountp' "$-1.00"], mamountp' "$-1.00",mixedAmount amt0 {aquantity=(-1)})+ -- ],+ -- mixedAmount usd0)++ -- ,testCase "a valid history on an empty period (more complex)" $+ -- (defreportopts{period_= PeriodBetween (fromGregorian 2009 1 1) (fromGregorian 2009 1 2), balanceaccum_=Historical}, samplejournal) `gives`+ -- (+ -- [+ -- ("assets:bank:checking","checking",3, [mamountp' "$1.00"], mamountp' "$1.00",mixedAmount amt0 {aquantity=1})+ -- ,("assets:bank:saving","saving",3, [mamountp' "$1.00"], mamountp' "$1.00",mixedAmount amt0 {aquantity=1})+ -- ,("assets:cash","cash",2, [mamountp' "$-2.00"], mamountp' "$-2.00",mixedAmount amt0 {aquantity=(-2)})+ -- ,("expenses:food","food",2, [mamountp' "$1.00"], mamountp' "$1.00",mixedAmount amt0 {aquantity=(1)})+ -- ,("expenses:supplies","supplies",2, [mamountp' "$1.00"], mamountp' "$1.00",mixedAmount amt0 {aquantity=(1)})+ -- ,("income:gifts","gifts",2, [mamountp' "$-1.00"], mamountp' "$-1.00",mixedAmount amt0 {aquantity=(-1)})+ -- ,("income:salary","salary",2, [mamountp' "$-1.00"], mamountp' "$-1.00",mixedAmount amt0 {aquantity=(-1)})+ -- ],+ -- mixedAmount usd0)+ ]+ ]
+ Hledger/Reports/PostingsReport.hs view
@@ -0,0 +1,483 @@+{-|++Postings report, used by the register command.++-}++{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE BangPatterns #-}++module Hledger.Reports.PostingsReport (+ PostingsReport,+ PostingsReportItem,+ postingsReport,+ postingsReportStartBalances,+ mkpostingsReportItem,+ registerRunningCalculationFn,+ SortSpec,+ defsortspec,++ -- * Tests+ tests_PostingsReport+)+where++import Data.List (mapAccumL, sortBy, sortOn)+import Data.Map.Strict qualified as M+import Data.Maybe (isJust, isNothing, fromMaybe)+import Data.Ord+import Data.Text (Text)+import Data.Time.Calendar (Day)+import Safe (headMay)++import Hledger.Data+import Hledger.Query+import Hledger.Utils+import Hledger.Reports.ReportOptions+++-- | A postings report is a list of postings with a running total, and a little extra+-- transaction info to help with rendering.+-- This is used eg for the register command.+type PostingsReport = [PostingsReportItem] -- line items, one per posting+type PostingsReportItem = (Maybe Day -- The posting date, if this is the first posting in a+ -- transaction or if it's different from the previous+ -- posting's date. Or if this a summary posting, the+ -- report interval's start date if this is the first+ -- summary posting in the interval.+ ,Maybe Period -- If this is a summary posting, the report interval's period.+ ,Maybe Text -- The posting's transaction's description, if this is the first posting in the transaction.+ ,Posting -- The posting, possibly with the account name depth-clipped.+ ,MixedAmount -- The running total after this posting, or with --average,+ -- the running average posting amount. With --historical,+ -- postings before the report start date are included in+ -- the running total/average.+ )++instance HasAmounts PostingsReportItem where+ styleAmounts styles (a,b,c,d,e) = (a,b,c,styleAmounts styles d,styleAmounts styles e)++-- | A summary posting summarises the activity in one account within a report+-- interval. It is by a regular Posting with no description, the interval's+-- start date stored as the posting date, and the interval's Period attached+-- with a tuple.+type SummaryPosting = (Posting, Period)++-- | Select postings from the journal and add running balance and other+-- information to make a postings report. Used by eg hledger's register command.+postingsReport :: ReportSpec -> Journal -> PostingsReport+postingsReport rspec@ReportSpec{_rsReportOpts=ropts@ReportOpts{..}} j = items+ where+ (reportspan, colspans) = reportSpanBothDatesLazy j rspec+ whichdate = whichDate ropts+ depthSpec = queryDepth $ _rsQuery rspec+ multiperiod = interval_ /= NoInterval++ -- postings to be included in the report, and similarly-matched postings before the report start date+ (precedingps, reportps) = matchedPostingsBeforeAndDuring rspec j reportspan++ -- Postings, or summary postings with their subperiod's end date, to be displayed.+ -- Without --empty, zero-amount postings are omitted.+ displayps :: [(Posting, Maybe Period)]+ displayps+ | multiperiod = [(p', Just period') | (p', period') <- summariseps reportps]+ | otherwise = [(p', Nothing) | p' <- reportps, showempty || not (mixedAmountLooksZero $ pamount p')]+ where+ summariseps = summarisePostingsByInterval whichdate depthSpec showempty colspans+ showempty = empty_ || average_++ sortedps = if sortspec_ /= defsortspec then sortPostings ropts sortspec_ displayps else displayps++ -- Posting report items ready for display: each posting with its running total (or average),+ -- less any whose amount or balance doesn't match the query's change:/balance: terms+ -- (hidden rows still count in the running totals).+ items =+ dbg4 "postingsReport items" $+ postingsReportItems (filter rowMatches $ withRunningTotals postings) (nullposting,Nothing) whichdate depthSpec+ where+ rowq = _rsRowQuery rspec+ rowMatches (p, _, _, histbal) = matchesRowAmounts rowq (pamount p) histbal+ -- Add each posting's running total/average after it, and (if a balance: term needs it)+ -- its historical running balance: the account(s)' real balance, whether or not -H was used.+ withRunningTotals = snd . mapAccumL step (startnum, startbal, precedingsum)+ where+ step (!n, !bal, !histbal) (p, mperiod) = ((n+1, bal', histbal'), (p, mperiod, bal', histbal'))+ where+ bal' = runningcalc n bal $ pamount p+ histbal' = if queryHasBalance rowq then maPlus histbal (pamount p) else nullmixedamt+ -- In historical mode we'll need a starting balance, which we+ -- may be converting to value per hledger_options.m4.md "Effect+ -- of --value on reports".+ -- XXX balance report doesn't value starting balance.. should this ?+ historical = balanceaccum_ == Historical+ startbal | average_ = if historical then precedingavg else nullmixedamt+ | otherwise = if historical then precedingsum else nullmixedamt+ precedingsum = sumPostings precedingps+ precedingavg = divideMixedAmount (fromIntegral $ length precedingps) precedingsum++ runningcalc = registerRunningCalculationFn ropts+ startnum = if historical then length precedingps + 1 else 1+ postings | historical = if sortspec_ /= defsortspec + then error' "--historical and --sort should not be used together" + else sortedps+ | otherwise = sortedps++-- | The account balances making up a postings report's starting balance: with --historical (and not --average),+-- the sums of the matched postings before the report period, by account (depth-clipped as in the report).+-- Otherwise, there is no starting balance, and this is empty.+-- Useful for showing each account's historical running total, eg in charts.+postingsReportStartBalances :: ReportSpec -> Journal -> M.Map AccountName MixedAmount+postingsReportStartBalances rspec@ReportSpec{_rsReportOpts=ropts, _rsQuery=q} j+ | balanceaccum_ ropts /= Historical || average_ ropts = M.empty+ | otherwise = M.fromListWith maPlus [(clipOrEllipsifyAccountName (queryDepth q) $ paccount p, pamount p) | p <- precedingps]+ where+ (reportspan, _) = reportSpanBothDatesLazy j rspec+ (precedingps, _) = matchedPostingsBeforeAndDuring rspec j reportspan++-- | Based on the given report options, return a function that does the appropriate+-- running calculation for the register report, ie a running average or running total.+-- This function will take the item number, previous average/total, and new posting amount,+-- and return the new average/total.+registerRunningCalculationFn :: ReportOpts -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)+registerRunningCalculationFn ropts+ | average_ ropts = \i avg amt -> avg `maPlus` divideMixedAmount (fromIntegral i) (amt `maMinus` avg)+ | otherwise = \_ bal amt -> bal `maPlus` amt++-- | Sort two postings by the current list of value expressions (given in SortSpec).+comparePostings :: ReportOpts -> SortSpec -> (Posting, Maybe Period) -> (Posting, Maybe Period) -> Ordering+comparePostings _ [] _ _ = EQ+comparePostings ropts (ex:es) (a, pa) (b, pb) = + let + getDescription p = + let tx = ptransaction p + description = fmap (\t -> tdescription t) tx+ -- If there's no transaction attached, then use empty text for the description+ in fromMaybe "" description+ comparison = case ex of+ AbsAmount' False -> compare (abs (pamount a)) (abs (pamount b))+ Amount' False -> compare (pamount a) (pamount b)+ Account' False -> compare (paccount a) (paccount b)+ Date' False -> compare (postingDateOrDate2 (whichDate ropts) a) (postingDateOrDate2 (whichDate ropts) b)+ Description' False -> compare (getDescription a) (getDescription b)+ AbsAmount' True -> compare (Down (abs (pamount a))) (Down (abs (pamount b)))+ Amount' True -> compare (Down (pamount a)) (Down (pamount b))+ Account' True -> compare (Down (paccount a)) (Down (paccount b))+ Date' True -> compare (Down (postingDateOrDate2 (whichDate ropts) a)) (Down (postingDateOrDate2 (whichDate ropts) b))+ Description' True -> compare (Down (getDescription a)) (Down (getDescription b))+ in + if comparison == EQ then comparePostings ropts es (a, pa) (b, pb) else comparison++-- | Sort postings by the current SortSpec.+sortPostings :: ReportOpts -> SortSpec -> [(Posting, Maybe Period)] -> [(Posting, Maybe Period)]+sortPostings ropts sspec = sortBy (comparePostings ropts sspec)++-- | Find postings matching a given query, within a given date span,+-- and also any similarly-matched postings before that date span.+-- Date restrictions and depth restrictions in the query are ignored.+-- A helper for the postings report.+matchedPostingsBeforeAndDuring :: ReportSpec -> Journal -> DateSpan -> ([Posting],[Posting])+matchedPostingsBeforeAndDuring rspec@ReportSpec{_rsReportOpts=ropts,_rsQuery=q} j reportspan =+ dbg5 "beforeps, duringps" $ span (beforestartq `matchesPosting`) beforeandduringps+ where+ beforestartq = dbg3 "beforestartq" $ dateqtype $ DateSpan Nothing (Exact <$> spanStart reportspan)+ beforeandduringps =+ sortOn (postingDateOrDate2 (whichDate ropts)) -- sort postings by date or date2+ . (if invert_ ropts then map postingNegateMainAmount else id) -- with --invert, invert amounts+ . filter hasAmount -- omit postings with no definite amount (#2571)+ . journalPostings+ -- With most calls we will not require transaction prices past this point, and can get a big+ -- speed improvement by stripping them early. In some cases, such as in hledger-ui, we still+ -- want to keep prices around, so we can toggle between cost and no cost quickly. We can use+ -- the show_costs_ flag to be efficient when we can, and detailed when we have to.+ . (if show_costs_ ropts then id else journalMapPostingAmounts mixedAmountStripCosts)+ $ journalValueAndFilterPostings rspec{_rsQuery=beforeandduringq} j++ -- filter postings by the query, with no start date or depth limit+ beforeandduringq = dbg4 "beforeandduringq" $ And [depthless $ dateless q, beforeendq]+ where+ depthless = filterQuery (not . queryIsDepth)+ dateless = filterQuery (not . queryIsDateOrDate2)+ beforeendq = dateqtype $ DateSpan Nothing (Exact <$> spanEnd reportspan)++ dateqtype = if queryIsDate2 dateq || (queryIsDate dateq && date2_ ropts) then Date2 else Date+ where+ dateq = dbg4 "matchedPostingsBeforeAndDuring dateq" $ filterQuery queryIsDateOrDate2 $ dbg4 "matchedPostingsBeforeAndDuring q" q -- XXX confused by multiple date:/date2: ?++-- | Generate postings report line items from a list of postings or (with+-- non-Nothing periods attached) summary postings, each with its running total+-- (and its historical balance, which is not used here).+-- Postings' account names are clipped to the given depth;+-- summary postings' account names have been clipped already.+postingsReportItems :: [(Posting,Maybe Period,MixedAmount,MixedAmount)] -> (Posting,Maybe Period) -> WhichDate -> DepthSpec -> [PostingsReportItem]+postingsReportItems [] _ _ _ = []+postingsReportItems ((p,mperiod,b,_):ps) (pprev,mperiodprev) wd d =+ i:(postingsReportItems ps (p,mperiod) wd d)+ where+ i = mkpostingsReportItem showdate showdesc wd mperiod p' b+ (showdate, showdesc) | isJust mperiod = (mperiod /= mperiodprev, False)+ | otherwise = (isfirstintxn || isdifferentdate, isfirstintxn)+ isfirstintxn = ptransaction p /= ptransaction pprev+ isdifferentdate = case wd of PrimaryDate -> postingDate p /= postingDate pprev+ SecondaryDate -> postingDate2 p /= postingDate2 pprev+ -- clipping isn't idempotent (with account-specific depths), so don't clip summary postings again+ p' | isJust mperiod = p+ | otherwise = p{paccount= clipOrEllipsifyAccountName d $ paccount p}++-- | Generate one postings report line item, containing the posting,+-- the current running balance, and optionally the posting date and/or+-- the transaction description.+mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Period -> Posting -> MixedAmount -> PostingsReportItem+mkpostingsReportItem showdate showdesc wd mperiod p b =+ (if showdate then Just $ postingDateOrDate2 wd p else Nothing+ ,mperiod+ ,if showdesc then tdescription <$> ptransaction p else Nothing+ ,p+ ,b+ )++-- | Convert a list of postings into summary postings, one per interval,+-- aggregated to the specified depth if any.+-- Each summary posting will have a non-Nothing interval end date.+summarisePostingsByInterval :: WhichDate -> DepthSpec -> Bool -> [DateSpan] -> [Posting] -> [SummaryPosting]+summarisePostingsByInterval wd depthspec showempty colspans =+ concatMap (\(s,ps) -> summarisePostingsInDateSpan s wd depthspec showempty ps)+ -- Group postings into their columns. We try to be efficient, since+ -- there can possibly be a very large number of intervals (cf #1683):+ -- the spans are a lazy list, consumed once, so they need not all be in memory.+ . groupByDateSpan showempty (postingDateOrDate2 wd) colspans++-- | Given a date span (representing a report interval) and a list of+-- postings within it, aggregate the postings into one summary posting per+-- account, sorted by account name. Each summary posting will have a non-Nothing interval end date.+--+-- Account names are first clipped to the given depth, so postings to deeper accounts+-- are aggregated into their clipped parent. (Like the balance report, which also+-- clips each posting before aggregating.) Accounts clipped to depth 0 are named "...".+--+-- The showempty flag includes spans with no postings and also postings+-- with 0 amount.+--+summarisePostingsInDateSpan :: DateSpan -> WhichDate -> DepthSpec -> Bool -> [Posting] -> [SummaryPosting]+summarisePostingsInDateSpan spn@(DateSpan b e) wd depthspec showempty ps+ | null ps && (isNothing b || isNothing e) = []+ | null ps && showempty = [(summaryp{paccount=clip ""}, dateSpanAsPeriod spn)]+ | otherwise = summarypes+ where+ postingdate = if wd == PrimaryDate then postingDate else postingDate2+ b' = maybe (maybe nulldate postingdate $ headMay ps) fromEFDay b+ summaryp = nullposting{pdate=Just b'}+ clip = clipOrEllipsifyAccountName depthspec+ balances = M.fromListWith (flip maPlus) [(clip $ paccount p, pamount p) | p <- ps]+ summaryps = [summaryp{paccount=a, pamount=amt} | (a,amt) <- M.toAscList balances]+ summarypes = map (, dateSpanAsPeriod spn) $ (if showempty then id else filter (not . mixedAmountLooksZero . pamount)) summaryps+++-- tests++tests_PostingsReport = testGroup "PostingsReport" [++ testCase "postingsReport" $ do+ let (query, journal) `gives` n = (length $ postingsReport defreportspec{_rsQuery=query} journal) @?= n+ -- with the query specified explicitly+ (Any, nulljournal) `gives` 0+ (Any, samplejournal) `gives` 13+ -- register --depth just clips account names+ (Depth 2, samplejournal) `gives` 13+ (And [Depth 1, StatusQ Cleared, Acct (toRegex' "expenses")], samplejournal) `gives` 2+ (And [And [Depth 1, StatusQ Cleared], Acct (toRegex' "expenses")], samplejournal) `gives` 2+ -- with query and/or command-line options+ (length $ postingsReport defreportspec samplejournal) @?= 13+ (length $ postingsReport defreportspec{_rsReportOpts=defreportopts{interval_=Months 1}} samplejournal) @?= 11+ (length $ postingsReport defreportspec{_rsReportOpts=defreportopts{interval_=Months 1, empty_=True}} samplejournal) @?= 20+ (length $ postingsReport defreportspec{_rsQuery=Acct $ toRegex' "assets:bank:checking"} samplejournal) @?= 5++ -- (defreportopts, And [Acct "a a", Acct "'b"], samplejournal2) `gives` 0+ -- [(Just (fromGregorian 2008 01 01,"income"),assets:bank:checking $1,$1)+ -- ,(Nothing,income:salary $-1,0)+ -- ,(Just (2008-06-01,"gift"),assets:bank:checking $1,$1)+ -- ,(Nothing,income:gifts $-1,0)+ -- ,(Just (2008-06-02,"save"),assets:bank:saving $1,$1)+ -- ,(Nothing,assets:bank:checking $-1,0)+ -- ,(Just (2008-06-03,"eat & shop"),expenses:food $1,$1)+ -- ,(Nothing,expenses:supplies $1,$2)+ -- ,(Nothing,assets:cash $-2,0)+ -- ,(Just (2008-12-31,"pay off"),liabilities:debts $1,$1)+ -- ,(Nothing,assets:bank:checking $-1,0)++ {-+ let opts = defreportopts+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) 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"+ ]++ ,"postings report with cleared option" ~:+ do+ let opts = defreportopts{cleared_=True}+ j <- readJournal'' sample_journal_str+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) 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"+ ]++ ,"postings report with uncleared option" ~:+ do+ let opts = defreportopts{uncleared_=True}+ j <- readJournal'' sample_journal_str+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) 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"+ ]++ ,"postings 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 (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/02/02"]++ ,"postings report with account pattern" ~:+ do+ j <- samplejournal+ let opts = defreportopts{patterns_=["cash"]}+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines+ ["2008/06/03 eat & shop assets:cash $-2 $-2"+ ]++ ,"postings report with account pattern, case insensitive" ~:+ do+ j <- samplejournal+ let opts = defreportopts{patterns_=["cAsH"]}+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` unlines+ ["2008/06/03 eat & shop assets:cash $-2 $-2"+ ]++ ,"postings report with display expression" ~:+ do+ j <- samplejournal+ let gives displayexpr =+ (registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is`)+ where opts = defreportopts+ "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"]++ ,"postings report with period expression" ~:+ do+ j <- samplejournal+ let periodexpr `gives` dates = do+ j' <- samplejournal+ registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j') `is` dates+ where opts = defreportopts{period_=Just $ parsePeriodExpr' 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_=Just $ parsePeriodExpr' date1 "yearly"}+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) 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_=Just $ parsePeriodExpr' date1 "quarterly"}+ registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/04/01","2008/10/01"]+ let opts = defreportopts{period_=Just $ parsePeriodExpr' date1 "quarterly",empty_=True}+ registerdates (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) j) `is` ["2008/01/01","2008/04/01","2008/07/01","2008/10/01"]++ ]++ , "postings report with depth arg" ~:+ do+ j <- samplejournal+ let opts = defreportopts{depth_=Just 2}+ (postingsReportAsText opts $ postingsReport opts (queryFromOpts date1 opts) 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"+ ]++ -}++ ,testCase "summarisePostingsByInterval" $+ summarisePostingsByInterval PrimaryDate mempty False [] [] @?= []++ -- ,tests_summarisePostingsInDateSpan = [+ -- "summarisePostingsInDateSpan" ~: do+ -- let gives (b,e,depth,showempty,ps) =+ -- (summarisePostingsInDateSpan (DateSpan b e) depth showempty ps `is`)+ -- let ps =+ -- [+ -- nullposting{lpdescription="desc",lpaccount="expenses:food:groceries",lpamount=mixedAmount (usd 1)}+ -- ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining", lpamount=mixedAmount (usd 2)}+ -- ,nullposting{lpdescription="desc",lpaccount="expenses:food", lpamount=mixedAmount (usd 4)}+ -- ,nullposting{lpdescription="desc",lpaccount="expenses:food:dining", lpamount=mixedAmount (usd 8)}+ -- ]+ -- ("2008/01/01","2009/01/01",0,9999,False,[]) `gives`+ -- []+ -- ("2008/01/01","2009/01/01",0,9999,True,[]) `gives`+ -- [+ -- nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31"}+ -- ]+ -- ("2008/01/01","2009/01/01",0,9999,False,ts) `gives`+ -- [+ -- nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="expenses:food", lpamount=mixedAmount (usd 4)}+ -- ,nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="expenses:food:dining", lpamount=mixedAmount (usd 10)}+ -- ,nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="expenses:food:groceries",lpamount=mixedAmount (usd 1)}+ -- ]+ -- ("2008/01/01","2009/01/01",0,2,False,ts) `gives`+ -- [+ -- nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="expenses:food",lpamount=mixedAmount (usd 15)}+ -- ]+ -- ("2008/01/01","2009/01/01",0,1,False,ts) `gives`+ -- [+ -- nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="expenses",lpamount=mixedAmount (usd 15)}+ -- ]+ -- ("2008/01/01","2009/01/01",0,0,False,ts) `gives`+ -- [+ -- nullposting{lpdate=fromGregorian 2008 01 01,lpdescription="- 2008/12/31",lpaccount="",lpamount=mixedAmount (usd 15)}+ -- ]++ ]
+ Hledger/Reports/ReportOptions.hs view
@@ -0,0 +1,1159 @@+{-|++Options common to most hledger reports.++-}++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++module Hledger.Reports.ReportOptions (+ ReportOpts(..),+ HasReportOptsNoUpdate(..),+ HasReportOpts(..),+ ReportSpec(..),+ HasReportSpec(..),+ SortField(..),+ SortSpec,+ sortKeysDescription,+ overEither,+ setEither,+ BalanceCalculation(..),+ balanceCalcIsCount,+ BalanceAccumulation(..),+ AccountListMode(..),+ ValuationType(..),+ Layout(..),+ PeriodTitles(..),+ effectiveTitle,+ defreportopts,+ rawOptsToReportOpts,+ defreportspec,+ defsortspec,+ setDefaultConversionOp,+ reportOptsToSpec,+ updateReportSpec,+ updateReportSpecWith,+ rawOptsToReportSpec,+ balanceAccumulationOverride,+ flat_,+ tree_,+ reportOptsToggleStatus,+ simplifyStatuses,+ whichDate,+ journalValueAndFilterPostings,+ journalValueAndFilterPostingsWith,+ journalApplyValuationFromOpts,+ journalApplyValuationFromOptsWith,+ mixedAmountApplyValuationAfterSumFromOptsWith,+ valuationAfterSum,+ requiresHistorical,+ intervalFromRawOpts,+ intervalFromQueryOpts,+ queryFromFlags,+ transactionDateFn,+ postingDateFn,+ reportSpan,+ reportSpanBothDates,+ reportSpanLazy,+ reportSpanBothDatesLazy,+ reportStartDate,+ reportEndDate,+ reportPeriodStart,+ reportPeriodOrJournalStart,+ reportPeriodLastDay,+ reportPeriodOrJournalLastDay,+ reportPeriodName+)+where++import Prelude hiding (Applicative(..))+import Control.Applicative (Applicative(..), Const(..), (<|>))+import Control.Monad (guard, join)+import Data.Char (toLower)+import Data.Either (fromRight)+import Data.Either.Extra (eitherToMaybe)+import Data.Functor.Identity (Identity(..))+import Data.List (partition)+import Data.List.Extra (find, isPrefixOf, nubSort, stripPrefix, stripSuffix)+import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe)+import Data.Text qualified as T+import Data.Time.Calendar (Day, addDays)+import Data.Default (Default(..))+import Safe (lastDef, lastMay, maximumMay, readMay)++import Hledger.Utils.I18n (Translations, noTranslations, trTimeLocale)+import Hledger.Data+import Hledger.Query+import Hledger.Utils+import Data.Function ((&))++-- | What to calculate for each cell in a balance report.+-- "Balance report types -> Calculation type" in the hledger manual.+data BalanceCalculation =+ CalcChange -- ^ Sum of posting amounts in the period.+ | CalcBudget -- ^ Sum of posting amounts and the goal for the period.+ | CalcValueChange -- ^ Change from previous period's historical end value to this period's historical end value.+ | CalcGain -- ^ Change from previous period's gain, i.e. valuation minus cost basis.+ | CalcPostingsCount -- ^ Number of postings in the period.+ | CalcTransactionsCount -- ^ Number of transactions in the period (exact only for a single account row, eg at depth 0).+ deriving (Eq, Show)++instance Default BalanceCalculation where def = CalcChange++-- | Does this calculation count postings or transactions, rather than summing amounts ?+balanceCalcIsCount :: BalanceCalculation -> Bool+balanceCalcIsCount c = c == CalcPostingsCount || c == CalcTransactionsCount++-- | How to accumulate calculated values across periods (columns) in a balance report.+-- "Balance report types -> Accumulation type" in the hledger manual.+data BalanceAccumulation =+ PerPeriod -- ^ No accumulation. Eg, shows the change of balance in each period.+ | Cumulative -- ^ Accumulate changes across periods, starting from zero at report start.+ | Historical -- ^ Accumulate changes across periods, including any from before report start.+ -- Eg, shows the historical end balance of each period.+ deriving (Eq,Show)++instance Default BalanceAccumulation where def = PerPeriod++-- | Should accounts be displayed: in the command's default style, hierarchically, or as a flat list ?+data AccountListMode = ALFlat | ALTree deriving (Eq, Show)++instance Default AccountListMode where def = ALFlat++data Layout = LayoutWide (Maybe Int)+ | LayoutTall+ | LayoutBare+ | LayoutBareWide+ | LayoutTidy+ deriving (Eq, Show)++-- | How to render period column headings in periodic reports.+data PeriodTitles = PTCompact | PTDates deriving (Eq, Show)++instance Default PeriodTitles where def = PTCompact++-- | Standard options for customising report filtering and output.+-- Most of these correspond to standard hledger command-line options+-- or query arguments, but not all. Some are used only by certain+-- commands, as noted below.+data ReportOpts = ReportOpts {+ -- for most reports:+ period_ :: Period+ ,interval_ :: Interval+ ,statuses_ :: [Status] -- ^ Zero, one, or two statuses to be matched+ ,conversionop_ :: Maybe ConversionOp -- ^ Which operation should we apply to conversion transactions?+ ,value_ :: Maybe ValuationType -- ^ What value should amounts be converted to ?+ ,infer_prices_ :: Bool -- ^ Infer market prices from transactions ?+ ,depth_ :: DepthSpec -- ^ --depth: clip the report to this depth (overall, or per account), removing+ -- deeper accounts and summing their amounts into their parents.+ -- Reports read it from their query, where queryFromFlags puts it.+ ,fold_depth_ :: Maybe Int -- ^ Unlike the CLI, where a depth limit (depth_) clips the tree before its rows+ -- are laid out, in hledger-web's tree mode a depth limit only sets the depth+ -- at which accounts are folded by default; the user can still open or close+ -- individual accounts to show more or less depth. So there the rows are laid+ -- out for the whole tree, and some are hidden. But folding can only hide whole+ -- rows; a boring parent account squashed into its subaccount's row, like+ -- "assets:bank", could not easily be folded to depth 1.+ -- So fold_depth_ holds a folding UI's default fold depth, and we take care+ -- not to squash accounts across this depth. Eg with fold depth 1, instead of+ -- "assets:bank", we'll display "assets" and "bank" on separate rows.+ -- (It's like no_elide_, but at this depth only.)+ -- Note, hledger-web's balance reports and sidebar fold in this way, but not its+ -- holdings report, where clipping merges positions by commodity, which folding+ -- can't show; so it does depth-clipping, like the CLI holdings report.+ ,no_elide_ :: Bool -- ^ --no-elide: in tree mode, don't ever squash boring parent accounts into+ -- their subaccount's row; in list mode, with -E, also show parent accounts.+ ,date2_ :: Bool+ ,empty_ :: Bool+ ,full_names_ :: Bool+ ,real_ :: Bool+ ,format_ :: StringFormat+ ,balance_base_url_ :: Maybe T.Text+ ,pretty_ :: Bool+ ,querystring_ :: [T.Text]+ --+ ,average_ :: Bool+ -- for posting reports (register)+ ,related_ :: Bool+ -- for sorting reports (register)+ ,sortspec_ :: SortSpec+ -- for account transactions reports (aregister)+ ,txn_dates_ :: Bool+ -- for balance reports (bal, bs, cf, is)+ ,balancecalc_ :: BalanceCalculation -- ^ What to calculate in balance report cells+ ,balanceaccum_ :: BalanceAccumulation -- ^ How to accumulate balance report values over time+ ,budgetpat_ :: Maybe T.Text -- ^ A case-insensitive description substring+ -- to select periodic transactions for budget reports.+ -- (Not a regexp, nor a full hledger query, for now.)+ ,accountlistmode_ :: AccountListMode+ ,drop_ :: Int+ ,declared_ :: Bool -- ^ Include accounts declared but not yet posted to ?+ ,row_total_ :: Bool+ ,no_total_ :: Bool+ ,summary_only_ :: Bool+ ,show_costs_ :: Bool -- ^ Show costs for reports which normally don't show them ?+ ,sort_amount_ :: Bool+ ,percent_ :: Bool+ ,invert_ :: Bool -- ^ Flip all amount signs in reports ?+ ,normalbalance_ :: Maybe NormalSign+ -- ^ This can be set when running balance reports on a set of accounts+ -- with the same normal balance type (eg all assets, or all incomes).+ -- - It helps --sort-amount know how to sort negative numbers+ -- (eg in the income section of an income statement)+ -- - It helps compound balance report commands (is, bs etc.) do+ -- sign normalisation, converting normally negative subreports to+ -- normally positive for a more conventional display.+ ,color_ :: Bool+ -- ^ Whether to use ANSI color codes in text output.+ -- Influenced by the --color/colour flag (cf CliOptions),+ -- whether stdout is an interactive terminal, and the value of+ -- TERM and existence of NO_COLOR environment variables.+ ,transpose_ :: Bool+ ,layout_ :: Layout+ ,period_titles_ :: PeriodTitles+ -- | Explicit --title value if given (possibly empty to+ -- suppress); otherwise Nothing, in which case each report falls+ -- back to its own default heading. Resolved via effectiveTitle.+ ,title_ :: Maybe T.Text+ -- | Explicit --subreport-titles value, a |-separated list of+ -- subreport titles to use in compound reports. An empty string+ -- means "suppress all default subreport titles".+ ,subreport_titles_ :: Maybe T.Text+ -- | Translations for the report's structural text (titles, headings,+ -- month names), selected by --lang. English by default.+ ,translations_ :: Translations+ } deriving (Show)++instance Default ReportOpts where def = defreportopts++defreportopts :: ReportOpts+defreportopts = ReportOpts+ { period_ = PeriodAll+ , interval_ = NoInterval+ , statuses_ = []+ , conversionop_ = Nothing+ , value_ = Nothing+ , infer_prices_ = False+ , depth_ = DepthSpec Nothing []+ , fold_depth_ = Nothing+ , no_elide_ = False+ , date2_ = False+ , empty_ = False+ , full_names_ = False+ , real_ = False+ , format_ = def+ , balance_base_url_ = Nothing+ , pretty_ = False+ , querystring_ = []+ , average_ = False+ , related_ = False+ , sortspec_ = defsortspec + , txn_dates_ = False+ , balancecalc_ = def+ , balanceaccum_ = def+ , budgetpat_ = Nothing+ , accountlistmode_ = ALFlat+ , drop_ = 0+ , declared_ = False+ , row_total_ = False+ , no_total_ = False+ , summary_only_ = False+ , show_costs_ = False+ , sort_amount_ = False+ , percent_ = False+ , invert_ = False+ , normalbalance_ = Nothing+ , color_ = False+ , transpose_ = False+ , layout_ = LayoutWide Nothing+ , period_titles_ = PTCompact+ , title_ = Nothing+ , subreport_titles_ = Nothing+ , translations_ = noTranslations+ }++-- | Generate a ReportOpts from raw command-line input, given a day and whether to use ANSI colour/styles in standard output.+-- This will fail with a usage error if it is passed+-- - an invalid --format argument,+-- - an invalid --value argument,+-- - if --valuechange is called with a valuation type other than -V/--value=end.+-- - an invalid --pretty argument,+rawOptsToReportOpts :: Day -> Bool -> RawOpts -> ReportOpts+rawOptsToReportOpts d usecoloronstdout rawopts =++ -- Bang-let-bind the results of every option parser that can call usageError.+ -- This forces validation eagerly, so a malformed argument is rejected even+ -- when the current command would not otherwise read the corresponding field.+ -- Note: layoutopt is intentionally left lazy because the print command+ -- defines its own --layout flag with different semantics (column number or+ -- "hledger1"), reusing the same raw "layout" key.+ let formatstring = T.pack <$> maybestringopt "format" rawopts+ querystring = map T.pack $ listofstringopt "args" rawopts -- doesn't handle an arg like "" right++ !format = case parseStringFormat <$> formatstring of+ Nothing -> defaultBalanceLineFormat+ Just (Right x) -> x+ Just (Left err) -> usageError $ "could not parse format option: " ++ err+ !pretty = fromMaybe False $ ynopt "pretty" rawopts+ !period = periodFromRawOpts d rawopts+ !interval = intervalFromRawOpts rawopts+ !conversionop = conversionOpFromRawOpts rawopts+ !value = valuationTypeFromRawOpts rawopts+ !depth = depthFromRawOpts rawopts+ !sortspec = getSortSpec rawopts+ !drop_n = posintopt "drop" rawopts+ !periodTitles = periodTitlesOpt rawopts++ in defreportopts+ {period_ = period+ ,interval_ = interval+ ,statuses_ = statusesFromRawOpts rawopts+ ,conversionop_ = conversionop+ ,value_ = value+ ,infer_prices_ = boolopt "infer-market-prices" rawopts+ ,depth_ = depth+ ,no_elide_ = boolopt "no-elide" rawopts+ ,date2_ = boolopt "date2" rawopts+ ,empty_ = boolopt "empty" rawopts+ ,full_names_ = boolopt "full-names" rawopts+ ,real_ = boolopt "real" rawopts+ ,format_ = format+ ,balance_base_url_ = T.pack <$> maybestringopt "base-url" rawopts+ ,querystring_ = querystring+ ,average_ = boolopt "average" rawopts+ ,related_ = boolopt "related" rawopts+ ,sortspec_ = sortspec+ ,txn_dates_ = boolopt "txn-dates" rawopts+ ,balancecalc_ = balancecalcopt rawopts+ ,balanceaccum_ = balanceaccumopt rawopts+ ,budgetpat_ = maybebudgetpatternopt rawopts+ ,accountlistmode_ = accountlistmodeopt rawopts+ ,drop_ = drop_n+ ,declared_ = boolopt "declared" rawopts+ ,row_total_ = boolopt "row-total" rawopts+ ,no_total_ = boolopt "no-total" rawopts+ ,summary_only_ = boolopt "summary-only" rawopts+ ,show_costs_ = boolopt "show-costs" rawopts+ ,sort_amount_ = boolopt "sort-amount" rawopts+ ,percent_ = boolopt "percent" rawopts+ ,invert_ = boolopt "invert" rawopts+ ,pretty_ = pretty+ ,color_ = usecoloronstdout+ ,transpose_ = toggleopt "transpose" rawopts+ ,layout_ = layoutopt rawopts+ ,period_titles_ = periodTitles+ ,title_ = unescapeNewlines . T.pack <$> maybestringopt "title" rawopts+ ,subreport_titles_ = unescapeNewlines . T.pack <$> maybestringopt "subreport-titles" rawopts+ }++-- | A fully-determined set of report parameters +-- (report options with all partial values made total, eg the begin and end+-- dates are known, avoiding date/regex errors; plus the reporting date),+-- and the query successfully calculated from them.+--+-- If you change the report options or date in one of these, you should+-- use `reportOptsToSpec` to regenerate the whole thing, avoiding inconsistency.+--+data ReportSpec = ReportSpec+ { _rsReportOpts :: ReportOpts -- ^ The underlying ReportOpts used to generate this ReportSpec+ , _rsDay :: Day -- ^ The Day this ReportSpec is generated for+ , _rsQuery :: Query -- ^ The generated Query for the given day, except for any change:/balance: terms+ , _rsRowQuery :: Query -- ^ The query's change: and balance: terms, which reports test against their rows'+ -- (or entries') summed amounts, after aggregating; Any if there are none. See 'querySplitRowTerms'.+ , _rsQueryOpts :: [QueryOpt] -- ^ A list of QueryOpts for the given day+ } deriving (Show)++instance Default ReportSpec where def = defreportspec++defreportspec :: ReportSpec+defreportspec = ReportSpec+ { _rsReportOpts = def+ , _rsDay = nulldate+ , _rsQuery = Any+ , _rsRowQuery = Any+ , _rsQueryOpts = []+ }++-- | Set the default ConversionOp.+setDefaultConversionOp :: ConversionOp -> ReportSpec -> ReportSpec+setDefaultConversionOp defop rspec@ReportSpec{_rsReportOpts=ropts} =+ rspec{_rsReportOpts=ropts{conversionop_=conversionop_ ropts <|> Just defop}}++accountlistmodeopt :: RawOpts -> AccountListMode+accountlistmodeopt =+ fromMaybe ALFlat . choiceopt parse where+ parse = \case+ "tree" -> Just ALTree+ "flat" -> Just ALFlat+ _ -> Nothing++periodTitlesOpt :: RawOpts -> PeriodTitles+periodTitlesOpt rawopts = case maybestringopt "period-titles" rawopts of+ Nothing -> PTCompact+ Just "compact" -> PTCompact+ Just "dates" -> PTDates+ Just s -> usageError $ "--period-titles's argument should be \"compact\" or \"dates\", not " ++ show s++-- | Resolve the effective report heading: if --title was given+-- on the command line, use that value (which may be empty to suppress+-- the heading); otherwise return the supplied per-report default.+effectiveTitle :: ReportOpts -> T.Text -> T.Text+effectiveTitle ropts dflt = fromMaybe dflt (title_ ropts)++-- | Replace the literal two-character sequence "\n" with a real newline.+unescapeNewlines :: T.Text -> T.Text+unescapeNewlines = T.replace "\\n" "\n"++-- Get the argument of the --budget option if any, or the empty string.+maybebudgetpatternopt :: RawOpts -> Maybe T.Text+maybebudgetpatternopt = fmap T.pack . maybestringopt "budget"++balancecalcopt :: RawOpts -> BalanceCalculation+balancecalcopt =+ fromMaybe CalcChange . choiceopt parse where+ parse = \case+ "sum" -> Just CalcChange+ "valuechange" -> Just CalcValueChange+ "gain" -> Just CalcGain+ "budget" -> Just CalcBudget+ "count" -> Just CalcPostingsCount+ _ -> Nothing++balanceaccumopt :: RawOpts -> BalanceAccumulation+balanceaccumopt = fromMaybe PerPeriod . balanceAccumulationOverride++ynopt :: String -> RawOpts -> Maybe Bool+ynopt opt rawopts = case maybestringopt opt rawopts of+ Just "always" -> Just True+ Just "yes" -> Just True+ Just "y" -> Just True+ Just "never" -> Just False+ Just "no" -> Just False+ Just "n" -> Just False+ Just _ -> usageError "this argument should be one of y, yes, n, no"+ _ -> Nothing++balanceAccumulationOverride :: RawOpts -> Maybe BalanceAccumulation+balanceAccumulationOverride rawopts = choiceopt parse rawopts <|> reportbal+ where+ parse = \case+ "historical" -> Just Historical+ "cumulative" -> Just Cumulative+ "change" -> Just PerPeriod+ _ -> Nothing+ reportbal = case balancecalcopt rawopts of+ CalcValueChange -> Just PerPeriod+ _ -> Nothing++layoutopt :: RawOpts -> Layout+layoutopt rawopts = fromMaybe (LayoutWide Nothing) $ layout <|> column+ where+ layout = parse <$> maybestringopt "layout" rawopts+ column = LayoutBare <$ guard (boolopt "commodity-column" rawopts)++ parse opt = maybe err snd $ guard (not $ null s) *> find (isPrefixOf s . fst) checkNames+ where+ checkNames = [ ("wide", LayoutWide w)+ , ("tall", LayoutTall)+ , ("bare", LayoutBare)+ , ("tidy", LayoutTidy)+ , ("barewide", LayoutBareWide)+ ]+ -- For `--layout=elided,n`, elide to the given width+ (s,n) = break (==',') $ map toLower opt+ w = case drop 1 n of+ "" -> Nothing+ c | Just w' <- readMay c -> Just w'+ _ -> usageError "width in --layout=wide,WIDTH must be an integer"++ err = usageError "--layout's argument should be \"wide[,WIDTH]\", \"tall\", \"bare\", \"barewide\", or \"tidy\""++-- Get the period specified by any -b/--begin, -e/--end and/or -p/--period+-- options appearing in the command line.+-- Its bounds are the rightmost begin date specified by a -b or -p, and+-- the rightmost end date specified by a -e or -p. Cf #1011.+-- Today's date is provided to help interpret any relative dates.+periodFromRawOpts :: Day -> RawOpts -> Period+periodFromRawOpts d rawopts =+ case (mlastb, mlaste) of+ (Nothing, Nothing) -> PeriodAll+ (Just b, Nothing) -> PeriodFrom b+ (Nothing, Just e) -> PeriodTo e+ (Just b, Just e) -> simplifyPeriod $ PeriodBetween b e+ where+ mlastb = case beginDatesFromRawOpts d rawopts of+ [] -> Nothing+ bs -> Just $ fromEFDay $ last bs+ mlaste = case endDatesFromRawOpts d rawopts of+ [] -> Nothing+ es -> Just $ fromEFDay $ last es++-- Get all begin dates specified by -b/--begin or -p/--period options, in order,+-- using the given date to interpret relative date expressions.+beginDatesFromRawOpts :: Day -> RawOpts -> [EFDay]+beginDatesFromRawOpts d = collectopts (begindatefromrawopt d)+ where+ begindatefromrawopt d' (n,v)+ | n == "begin" =+ either (\e -> usageError $ "could not parse "++n++" date: "++customErrorBundlePretty e) Just $+ fixSmartDateStrEither' d' (T.pack v)+ | n == "period" =+ case+ either (\e -> usageError $ "could not parse period option: "++customErrorBundlePretty e) id $+ parsePeriodExpr d' (textStripQuotes $ T.pack v)+ of+ (_, DateSpan (Just b) _) -> Just b+ _ -> Nothing+ | otherwise = Nothing++-- Get all end dates specified by -e/--end or -p/--period options, in order,+-- using the given date to interpret relative date expressions.+endDatesFromRawOpts :: Day -> RawOpts -> [EFDay]+endDatesFromRawOpts d = collectopts (enddatefromrawopt d)+ where+ enddatefromrawopt d' (n,v)+ | n == "end" =+ either (\e -> usageError $ "could not parse "++n++" date: "++customErrorBundlePretty e) Just $+ fixSmartDateStrEither' d' (T.pack v)+ | n == "period" =+ case+ either (\e -> usageError $ "could not parse period option: "++customErrorBundlePretty e) id $+ parsePeriodExpr d' (textStripQuotes $ T.pack v)+ of+ (_, DateSpan _ (Just e)) -> Just e+ _ -> Nothing+ | otherwise = Nothing++-- | Get the report interval, if any, specified by the last of -p/--period,+-- -D/--daily, -W/--weekly, -M/--monthly etc. options.+-- An interval from --period counts only if it is explicitly defined.+intervalFromRawOpts :: RawOpts -> Interval+intervalFromRawOpts = lastDef NoInterval . collectopts intervalfromrawopt+ where+ intervalfromrawopt (n,v)+ | n == "period" =+ either+ (\e -> usageError $ "could not parse period option: "++customErrorBundlePretty e)+ extractIntervalOrNothing $+ parsePeriodExpr+ (error' "intervalFromRawOpts: did not expect to need today's date here") -- PARTIAL: should not happen; we are just getting the interval, which does not use the reference date+ (textStripQuotes $ T.pack v)+ | n == "daily" = Just $ Days 1+ | n == "weekly" = Just $ Weeks 1+ | n == "monthly" = Just $ Months 1+ | n == "quarterly" = Just $ Quarters 1+ | n == "yearly" = Just $ Years 1+ | otherwise = Nothing++-- | Extract the interval from the parsed -p/--period expression.+-- Return Nothing if an interval is not explicitly defined.+extractIntervalOrNothing :: (Interval, DateSpan) -> Maybe Interval+extractIntervalOrNothing (NoInterval, _) = Nothing+extractIntervalOrNothing (interval, _) = Just interval++-- | Get the last interval specified in query opts, if any.+-- date: queries can specify a reporting interval.+intervalFromQueryOpts :: [QueryOpt] -> Maybe Interval+intervalFromQueryOpts = lastMay . mapMaybe getInterval+ where+ getInterval (QueryOptInterval i) = Just i+ getInterval _ = Nothing++-- | Get any statuses to be matched, as specified by -U/--unmarked,+-- -P/--pending, -C/--cleared flags. -UPC is equivalent to no flags,+-- so this returns a list of 0-2 unique statuses.+statusesFromRawOpts :: RawOpts -> [Status]+statusesFromRawOpts = simplifyStatuses . collectopts statusfromrawopt+ where+ statusfromrawopt (n,_)+ | n == "unmarked" = Just Unmarked+ | n == "pending" = Just Pending+ | n == "cleared" = Just Cleared+ | otherwise = Nothing++-- | Reduce a list of statuses to just one of each status,+-- and if all statuses are present return the empty list.+simplifyStatuses l+ | length l' >= numstatuses = []+ | otherwise = l'+ where+ l' = nubSort l+ numstatuses = length [minBound .. maxBound :: Status]++-- | Add/remove this status from the status list. Used by hledger-ui.+reportOptsToggleStatus s ropts@ReportOpts{statuses_=ss}+ | s `elem` ss = ropts{statuses_=filter (/= s) ss}+ | otherwise = ropts{statuses_=simplifyStatuses (s:ss)}++-- | Parse the type of valuation to be performed, if any, specified by -V,+-- -X/--exchange, or --value flags. If there's more than one valuation type,+-- the rightmost flag wins. This will fail with a usage error if an invalid+-- argument is passed to --value, or if --valuechange is called with a+-- valuation type other than -V/--value=end.+valuationTypeFromRawOpts :: RawOpts -> Maybe ValuationType+valuationTypeFromRawOpts rawopts = case (balancecalcopt rawopts, directval) of+ (CalcValueChange, Nothing ) -> Just $ AtEnd Nothing -- If no valuation requested for valuechange, use AtEnd+ (CalcValueChange, Just (AtEnd _)) -> directval -- If AtEnd valuation requested, use it+ (CalcValueChange, _ ) -> usageError "--valuechange only produces sensible results with --value=end"+ (CalcGain, Nothing ) -> Just $ AtEnd Nothing -- If no valuation requested for gain, use AtEnd+ (_, _ ) -> directval -- Otherwise, use requested valuation+ where+ directval = lastMay $ collectopts valuationfromrawopt rawopts+ valuationfromrawopt (n,v) -- option name, value+ | n == "V" = Just $ AtEnd Nothing+ | n == "X" = Just $ AtEnd (Just $ commodityarg v)+ | n == "value" = valueopt v+ | otherwise = Nothing+ valueopt v+ | t `elem` ["cost","c","transacted"] = AtEnd . Just <$> mc -- keep supporting --value=cost,COMM for now+ | t `elem` ["then" ,"t"] = Just $ AtThen mc+ | t `elem` ["end" ,"e"] = Just $ AtEnd mc+ | t `elem` ["now" ,"n"] = Just $ AtNow mc+ | otherwise = case parsedate t of+ Just d -> Just $ AtDate d mc+ Nothing -> usageError $ "could not parse \""++t++"\" as valuation type, should be: cost|transacted|then|end|now|c|t|e|n|YYYY-MM-DD"+ where+ -- parse --value's value: TYPE[,COMM]. A comma with nothing after it selects the no-symbol commodity.+ (t,c') = break (==',') v+ mc = case c' of+ "" -> Nothing+ c -> Just $ commodityarg $ drop 1 c+ -- A commodity symbol may be written in double quotes, as in journals; "" is the no-symbol commodity.+ commodityarg s = T.pack $ fromMaybe s $ stripPrefix "\"" s >>= stripSuffix "\""++-- | Parse the type of costing to be performed, if any, specified by -B/--cost+-- or --value flags. If there's more than one costing type, the rightmost flag+-- wins. This will fail with a usage error if an invalid argument is passed to+-- --cost or if a costing type is requested with --gain.+conversionOpFromRawOpts :: RawOpts -> Maybe ConversionOp+conversionOpFromRawOpts rawopts+ | isJust costFlag && balancecalcopt rawopts == CalcGain = usageError "--gain cannot be combined with --cost"+ | otherwise = costFlag+ where+ costFlag = lastMay $ collectopts conversionopfromrawopt rawopts+ conversionopfromrawopt (n,v) -- option name, value+ | n == "B" = Just ToCost+ | n == "value", takeWhile (/=',') v `elem` ["cost", "c"] = Just ToCost -- keep supporting --value=cost for now+ | n == "value", takeWhile (/=',') v == "transacted" = Just ToTransactedCost+ | otherwise = Nothing++-- | Parse the depth arguments. This can be either a flat depth that applies to+-- all accounts, or a regular expression and depth, which only matches certain+-- accounts. If an account name is matched by a regular expression, then the+-- smallest depth is used. Otherwise, if no regular expressions match, then the+-- flat depth is used. If more than one flat depth is supplied, use only the+-- last one.+depthFromRawOpts :: RawOpts -> DepthSpec+depthFromRawOpts rawopts = lastDef mempty flats <> mconcat regexps+ where+ (flats, regexps) = partition (\(DepthSpec f rs) -> isJust f && null rs) depthSpecs+ depthSpecs = case mapM (parseDepthSpec . T.pack) depths of+ Right d -> d+ Left err -> usageError err+ depths = listofstringopt "depth" rawopts++-- | Select the Transaction date accessor based on --date2.+transactionDateFn :: ReportOpts -> (Transaction -> Day)+transactionDateFn ReportOpts{..} = if date2_ then transactionDate2 else tdate++-- | Select the Posting date accessor based on --date2.+postingDateFn :: ReportOpts -> (Posting -> Day)+postingDateFn ReportOpts{..} = if date2_ then postingDate2 else postingDate++-- | Report which date we will report on based on --date2.+whichDate :: ReportOpts -> WhichDate+whichDate ReportOpts{..} = if date2_ then SecondaryDate else PrimaryDate++-- | Legacy-compatible convenience aliases for accountlistmode_.+tree_ :: ReportOpts -> Bool+tree_ ReportOpts{accountlistmode_ = ALTree} = True+tree_ ReportOpts{accountlistmode_ = ALFlat} = False++flat_ :: ReportOpts -> Bool+flat_ = not . tree_++-- depthFromOpts :: ReportOpts -> Int+-- depthFromOpts opts = min (fromMaybe 99999 $ depth_ opts) (queryDepth $ queryFromOpts nulldate opts)++-- | Convert a 'Journal''s amounts to cost and/or to value (see+-- 'journalApplyValuationFromOpts'), and filter by the 'ReportSpec' 'Query'.+--+-- We make sure to first filter by amt: and cur: terms, then value the+-- 'Journal', then filter by the remaining terms.+journalValueAndFilterPostings :: ReportSpec -> Journal -> Journal+journalValueAndFilterPostings rspec j =+ -- dbg4With (\j2 -> "valuedfilteredj" <> pshow (jtxns j2)) $+ journalValueAndFilterPostingsWith rspec j priceoracle+ where priceoracle = journalPriceOracle (infer_prices_ $ _rsReportOpts rspec) j++{- [Querying before valuation]+This helper is used by multiBalanceReport (all balance reports).+Previously, at least since #1625 (2021), it was filtering with the cur:/amt: parts+of the query before valuation, and with the other parts after valuation.+Now, since #2387 (2025), it does all filtering before valuation.+This avoids breaking boolean queries (#2371), avoids a strictness bug (#2385),+is simpler, and we think it's otherwise equivalent.+-}+-- | Like 'journalValueAndFilterPostings', but takes a 'PriceOracle' as an argument.+journalValueAndFilterPostingsWith :: ReportSpec -> Journal -> PriceOracle -> Journal+journalValueAndFilterPostingsWith = _journalValueAndFilterPostingsWith1431++-- 1.42+-- #2371 This goes wrong with complex boolean queries, splitting them apart in a lossy way.+-- _journalValueAndFilterPostingsWith142 rspec@ReportSpec{_rsQuery=q, _rsReportOpts=ropts} j =+-- -- Third, filter by the non amt:/cur: parts of the query+-- filterJournalPostings' reportq+-- -- Second, apply valuation and costing+-- . journalApplyValuationFromOptsWith rspec+-- -- First, filter by the amt:/cur: parts of the query, so they match pre-valuation amounts+-- (if queryIsNull amtsymq then j else filterJournalAmounts amtsymq j)+-- where+-- -- with -r, replace each posting with its sibling postings+-- filterJournalPostings' = if related_ ropts then filterJournalRelatedPostings else filterJournalPostings+-- amtsymq = dbg1 "amtsymq" $ filterQuery queryIsAmtOrCur q+-- reportq = dbg1 "reportq" $ filterQuery (not . queryIsAmtOrCur) q++-- 1.43+-- XXX #2396 This goes wrong with cur:. filterJournal*Postings keep all postings containing the matched commodity,+-- but do not remove the unmatched commodities from multicommodity postings, as filterJournalAmounts would.+-- _journalValueAndFilterPostingsWith143 rspec@ReportSpec{_rsQuery = q, _rsReportOpts = ropts} =+-- journalApplyValuationFromOptsWith rspec .+-- dbg1With (\j1 -> "j1" <> pshow (jtxns j1)) .+-- (if related_ ropts then filterJournalRelatedPostings else filterJournalPostings) q++-- 1.43.1+_journalValueAndFilterPostingsWith1431 rspec@ReportSpec{_rsQuery = q, _rsReportOpts = ropts} =+ journalApplyValuationFromOptsWith rspec . filterjournal q+ where+ filterjournal q2 =+ filterJournalAmounts (filterQuery queryIsAmtOrCur q2) . -- an extra amount filtering pass for #2396+ (if related_ ropts then filterJournalRelatedPostings q2 else filterJournalPostings q2)++-- | Convert this journal's postings' amounts to cost and/or to value, if specified+-- by options (-B/--cost/-V/-X/--value etc.). Strip prices if not needed. This+-- should be the main stop for performing costing and valuation. The exception is+-- whenever you need to perform valuation _after_ summing up amounts, as in a+-- historical balance report with --value=end. valuationAfterSum will check for this+-- condition.+journalApplyValuationFromOpts :: ReportSpec -> Journal -> Journal+journalApplyValuationFromOpts rspec j =+ journalApplyValuationFromOptsWith rspec j priceoracle+ where priceoracle = journalPriceOracle (infer_prices_ $ _rsReportOpts rspec) j++-- | Like journalApplyValuationFromOpts, but takes PriceOracle as an argument.+journalApplyValuationFromOptsWith :: ReportSpec -> Journal -> PriceOracle -> Journal+journalApplyValuationFromOptsWith rspec@ReportSpec{_rsReportOpts=ropts} j priceoracle =+ costfn j+ & journalMapPostings (\p -> p+ & dbg9With (lbl "before calc".showMixedAmountOneLine.pamount)+ & postingTransformAmount (calcfn p)+ & dbg9With (lbl (show calc).showMixedAmountOneLine.pamount)+ )+ where+ lbl = lbl_ "journalApplyValuationFromOptsWith"+ -- Which custom calculation to do for balance reports. For all other reports, it will be CalcChange.+ calc = balancecalc_ ropts+ calcfn = case calc of+ CalcGain -> \p -> maybe id (mixedAmountApplyGain priceoracle styles (postingperiodend p) (_rsDay rspec) (postingDate p)) (value_ ropts)+ _ -> \p -> maybe id (mixedAmountApplyValuation priceoracle styles (postingperiodend p) (_rsDay rspec) (postingDate p)) (value_ ropts)+ costfn = case calc of+ CalcGain -> id+ _ -> journalToCost costop where costop = fromMaybe NoConversionOp $ conversionop_ ropts++ -- Find the "end" valuation date for this posting.+ -- With a report interval, this is the last day of the report subperiod containing this posting;+ -- with no interval it's the last date of the overall report period+ -- (which for an end value report may have been extended to include the latest non-future P directive).+ -- To get the period's last day, we subtract one from the (exclusive) period end date.+ postingperiodend = postingPeriodEnd . postingDateOrDate2 (whichDate ropts)+ where+ postingPeriodEnd d = fromMaybe err $ case interval_ ropts of+ NoInterval -> fmap (snd . dayPartitionStartEnd) mwholespan+ _ -> fmap (snd . dayPartitionFind d) mspans+ -- The report spans scan the journal, and this function runs per+ -- posting, so compute them once here: in an unoptimized build+ -- nothing floats them out of the lambda, and valuing a large+ -- journal becomes quadratic (eg hledger-web built with --fast).+ mwholespan = snd $ reportSpan j rspec+ mspans = snd $ reportSpanBothDates j rspec+ -- Should never happen, because there are only invalid dayPartitions+ -- when there are no transactions, in which case this function is never called+ err = error' "journalApplyValuationFromOpts: expected all spans to have an end date"+++ styles = journalCommodityStyles j++-- | Select the Account valuation functions required for performing valuation after summing+-- amounts. Used in MultiBalanceReport to value historical and similar reports.+mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle+ -> (Day -> MixedAmount -> MixedAmount)+mixedAmountApplyValuationAfterSumFromOptsWith ropts j priceoracle =+ case valuationAfterSum ropts of+ Nothing -> const id+ Just mc -> case balancecalc_ ropts of+ CalcGain -> mixedAmountGainAtDate priceoracle styles mc+ _ -> mixedAmountValueAtDate priceoracle styles mc+ where styles = journalCommodityStyles j++-- | If the ReportOpts specify that we are performing valuation after summing amounts,+-- return Just of the commodity symbol we're converting to, Just Nothing for the default,+-- and otherwise return Nothing.+-- Used for example with historical reports with --value=end.+valuationAfterSum :: ReportOpts -> Maybe (Maybe CommoditySymbol)+valuationAfterSum ropts = case value_ ropts of+ Just (AtEnd mc) | requiresHistorical ropts -> Just mc+ _ -> Nothing++-- | If the ReportOpts specify that we will need to consider historical+-- postings, either because this is a historical report, or because the+-- valuation strategy requires historical amounts.+requiresHistorical :: ReportOpts -> Bool+requiresHistorical ReportOpts{balanceaccum_ = accum, balancecalc_ = calc} =+ accum == Historical || calc == CalcValueChange || calc == CalcGain++-- | Convert report options to a query, ignoring any non-flag command line arguments.+queryFromFlags :: ReportOpts -> Query+queryFromFlags ReportOpts{..} = simplifyQuery $ And flagsq+ where+ flagsq = consIf Real real_+ . consJust Depth flatDepth+ $ map (uncurry DepthAcct) regexpDepths+ ++ [ (if date2_ then Date2 else Date) $ periodAsDateSpan period_+ , Or $ map StatusQ statuses_+ ]+ consIf f b = if b then (f True:) else id+ DepthSpec flatDepth regexpDepths = depth_+ consJust f = maybe id ((:) . f)++-- Methods/types needed for --sort argument++-- Possible arguments taken by the --sort command+-- Each of these takes a bool, which shows if it has been inverted+-- (True -> has been inverted, reverse the order)+data SortField+ = AbsAmount' Bool+ | Account' Bool+ | Amount' Bool+ | Date' Bool+ | Description' Bool+ deriving (Show, Eq)+type SortSpec = [SortField]++-- By default, sort by date in ascending order+defsortspec :: SortSpec+defsortspec = [Date' False]++-- Load a SortSpec from the argument given to --sort+-- If there is no spec given, then sort by [Date' False] by default+getSortSpec :: RawOpts -> SortSpec+getSortSpec opts = + let opt = maybestringopt "sort" opts+ optParser s = + let terms = map strip $ splitAtElement ',' s + termParser t = case trimmed of+ "date" -> Date' isNegated+ "desc" -> Description' isNegated+ "description" -> Description' isNegated+ "account" -> Account' isNegated+ "amount" -> Amount' isNegated+ "absamount" -> AbsAmount' isNegated+ _ -> error' $ "unknown --sort key " ++ t ++ ". Supported keys are: " <> sortKeysDescription <> "."+ where isNegated = isPrefixOf "-" t+ trimmed = fromMaybe t (stripPrefix "-" t)+ in map termParser terms+ in maybe defsortspec optParser opt ++-- for option's help and parse error message+sortKeysDescription = "date, desc, account, amount, absamount" -- 'description' is also accepted++-- Report dates.++-- | The effective report span is the start and end dates requested by options or queries.+-- If the start date is unspecified, the earliest transaction or posting date is used.+-- If the end date is unspecified, the latest transaction or posting date+-- (or non-future market price date, when doing an end value report) is used.+-- If none of these things are present, the null date span is returned.+-- The report sub-periods caused by a report interval, if any, are also returned.+reportSpan :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)+reportSpan = reportSpanHelper False+-- Note: In end value reports, the report end date and valuation date are the same.+-- If valuation date ever needs to be different, journalApplyValuationFromOptsWith is the place.++-- | Like reportSpan, but considers both primary and secondary dates, not just one or the other.+reportSpanBothDates :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)+reportSpanBothDates = reportSpanHelper True++reportSpanHelper :: Bool -> Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)+reportSpanHelper bothdates j rspec@ReportSpec{_rsReportOpts=ropts} =+ (enlargedreportspan, intervalspans)+ where+ (reportspan, adjust) = reportSpanAndAdjust bothdates j rspec++ -- The list of interval spans enclosing the requested span.+ -- This list can be empty if the journal was empty,+ -- or if hledger-ui has added its special date:-tomorrow to the query+ -- and all txns are in the future.+ intervalspans = dbg3 "intervalspans" $ splitSpan adjust (interval_ ropts) reportspan++ -- The requested span enlarged to enclose a whole number of intervals.+ -- This can be the null span if there were no intervals.+ enlargedreportspan = dbg3 "enlargedreportspan" $+ maybe (DateSpan Nothing Nothing) (mkSpan . dayPartitionStartEnd) intervalspans+ where mkSpan (s, e) = DateSpan (Just $ Exact s) (Just . Exact $ addDays 1 e)++-- | Like 'reportSpan', but returns the report periods as a lazily generated list+-- of 'DateSpan's rather than a 'DayPartition', so that a report which traverses them once+-- uses constant memory however many periods there are (#1683).+-- The list is a single unbounded span if there are no periods, like 'maybeDayPartitionToDateSpans'.+reportSpanLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])+reportSpanLazy = reportSpanHelperLazy False++-- | Like 'reportSpanLazy', but considers both primary and secondary dates. Used by the postings report.+reportSpanBothDatesLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])+reportSpanBothDatesLazy = reportSpanHelperLazy True++reportSpanHelperLazy :: Bool -> Journal -> ReportSpec -> (DateSpan, [DateSpan])+reportSpanHelperLazy bothdates j rspec@ReportSpec{_rsReportOpts=ropts} =+ (enlargedreportspan, intervalspans)+ where+ (reportspan, adjust) = reportSpanAndAdjust bothdates j rspec+ intervalspans = case splitSpanToDateSpans adjust (interval_ ropts) reportspan of+ [] -> [DateSpan Nothing Nothing]+ ss -> ss+ -- Found with a separate traversal of the periods, so the list above need not be kept in memory.+ enlargedreportspan = dbg3 "enlargedreportspan" $+ maybe (DateSpan Nothing Nothing) mkSpan $ splitSpanStartEnd adjust (interval_ ropts) reportspan+ where mkSpan (s, e) = DateSpan (Just $ Exact s) (Just $ Exact e)++-- | The report span before enlarging it to whole intervals, filled in with defaults from the journal,+-- and whether the report periods should be adjusted back to natural interval boundaries.+reportSpanAndAdjust :: Bool -> Journal -> ReportSpec -> (DateSpan, Bool)+reportSpanAndAdjust bothdates j ReportSpec{_rsQuery=query, _rsReportOpts=ropts, _rsDay=today} =+ (reportspan, adjust)+ where+ -- The date span specified by -b/-e/-p options and query args if any.+ requestedspan = dbg3 "requestedspan" $+ if bothdates then queryDateSpan' query else queryDateSpan (date2_ ropts) query++ -- If the requested span has open ends, fill them with defaults.+ reportspan = dbg3 "reportspan" $ requestedspan `spanValidDefaultsFrom` txnsorpricespan+ where+ txnsorpricespan = dbg3 "txnsorpricespan" $ DateSpan mfirsttxn mlatesttxnorprice+ where+ DateSpan mfirsttxn mlasttxn = dbg3 "txnsspan" $+ if bothdates then journalDateSpanBothDates j else journalDateSpan (date2_ ropts) j+ mlatesttxnorprice =+ case value_ ropts of+ Just (AtEnd _) -> mlasttxn `max` mlatestnonfutureprice+ _ -> mlasttxn+ where+ mlatestnonfutureprice = dbg3 "latestnonfutureprice" $ -- #2445+ fmap (Exact . addDays 1) . maximumMay . filter (not . (> today)) . map pddate $ jpricedirectives j++ -- When calculating report periods, we will adjust the start date back to the nearest interval boundary+ -- unless a start date was specified explicitly.+ adjust = isNothing $ spanStart requestedspan++reportStartDate :: Journal -> ReportSpec -> Maybe Day+reportStartDate j = spanStart . fst . reportSpan j++reportEndDate :: Journal -> ReportSpec -> Maybe Day+reportEndDate j = spanEnd . fst . reportSpan j++-- Some pure alternatives to the above. XXX review/clean up++-- Get the report's start date.+-- If no report period is specified, will be Nothing.+reportPeriodStart :: ReportSpec -> Maybe Day+reportPeriodStart = queryStartDate False . _rsQuery++-- Get the report's start date, or if no report period is specified,+-- the journal's start date (the earliest posting date). If there's no+-- report period and nothing in the journal, will be Nothing.+reportPeriodOrJournalStart :: ReportSpec -> Journal -> Maybe Day+reportPeriodOrJournalStart rspec j =+ reportPeriodStart rspec <|> journalStartDate False j++-- Get the last day of the overall report period.+-- This the inclusive end date (one day before the+-- more commonly used, exclusive, report end date).+-- If no report period is specified, will be Nothing.+reportPeriodLastDay :: ReportSpec -> Maybe Day+reportPeriodLastDay = fmap (addDays (-1)) . queryEndDate False . _rsQuery++-- Get the last day of the overall report period, or if no report+-- period is specified, the last day of the journal (ie the latest+-- posting date). If we're doing period-end valuation, include price+-- directive dates. If there's no report period and nothing in the+-- journal, will be Nothing.+reportPeriodOrJournalLastDay :: ReportSpec -> Journal -> Maybe Day+reportPeriodOrJournalLastDay rspec j = reportPeriodLastDay rspec <|> journalOrPriceEnd+ where+ journalOrPriceEnd = case value_ $ _rsReportOpts rspec of+ Just (AtEnd _) -> max (journalLastDay False j) lastPriceDirective+ _ -> journalLastDay False j+ lastPriceDirective = fmap (addDays 1) . maximumMay . map pddate $ jpricedirectives j++-- | Make a name for the given period in a multiperiod report, given+-- the type of balance being reported and the full set of report+-- periods. This will be used as a column heading (or row heading, in+-- a register summary report). We try to pick a useful name as follows:+--+-- - ending-balance reports: the period's end date+--+-- - balance change reports where the periods are months and all in the same year:+-- the short month name, translated according to --lang+--+-- - all other balance change reports: a description of the datespan,+-- abbreviated to compact form if possible (see showDateSpan).+reportPeriodName :: ReportOpts -> [DateSpan] -> DateSpan -> T.Text+reportPeriodName ReportOpts{period_titles_, balanceaccum_, translations_} spans =+ case balanceaccum_ of+ PerPeriod -> case period_titles_ of+ PTDates -> showDateSpanFull+ PTCompact -> if multiyear then showDateSpan else showDateSpanAbbrevWith (trTimeLocale translations_)+ where+ multiyear = (>1) $ length $ nubSort $ map spanStartYear spans+ _ -> maybe "" (showDate . prevday) . spanEnd++-- lenses++-- Reportable functors are so that we can create special lenses which can fail+-- and report on their failure.+class Functor f => Reportable f e where+ report :: a -> f (Either e a) -> f a++instance Reportable (Const r) e where+ report _ (Const x) = Const x++instance Reportable Identity e where+ report a (Identity i) = Identity $ fromRight a i++instance Reportable Maybe e where+ report _ = (eitherToMaybe =<<)++instance (e ~ a) => Reportable (Either a) e where+ report _ = join++-- | Apply a function over a lens, but report on failure.+overEither :: ((a -> Either e b) -> s -> Either e t) -> (a -> b) -> s -> Either e t+overEither l f = l (pure . f)++-- | Set a field using a lens, but report on failure.+setEither :: ((a -> Either e b) -> s -> Either e t) -> b -> s -> Either e t+setEither l = overEither l . const++type ReportableLens' s a = forall f. Reportable f String => (a -> f a) -> s -> f s++-- | Lenses for ReportOpts.++-- Implement HasReportOptsNoUpdate, the basic lenses for ReportOpts.+makeHledgerClassyLenses ''ReportOpts+makeHledgerClassyLenses ''ReportSpec++-- | Special lenses for ReportOpts which also update the Query and QueryOpts in ReportSpec.+-- Note that these are not true lenses, as they have a further restriction on+-- the functor. This will work as a normal lens for all common uses, but since they+-- don't obey the lens laws for some fancy cases, they may fail in some exotic circumstances.+--+-- Note that setEither/overEither should only be necessary with+-- querystring and reportOpts: the other lenses should never fail.+--+-- === Examples:+-- >>> import Lens.Micro (set)+-- >>> _rsQuery <$> setEither querystring ["assets"] defreportspec+-- Right (Acct (RegexpCI "assets"))+-- >>> _rsQuery <$> setEither querystring ["(assets"] defreportspec+-- Left "This regular expression is invalid or unsupported, please correct it: (assets"+-- >>> _rsQuery $ set querystring ["assets"] defreportspec+-- Acct (RegexpCI "assets")+-- >>> _rsQuery $ set period (MonthPeriod 2021 08) defreportspec+-- Date DateSpan 2021-08+--+-- XXX testing error output isn't working since adding color to it:+-- > import System.Environment+-- > setEnv "NO_COLOR" "1" >> return (_rsQuery $ set querystring ["(assets"] defreportspec)+-- *** Exception: Error: Updating ReportSpec failed: try using overEither instead of over or setEither instead of set+class HasReportOptsNoUpdate a => HasReportOpts a where+ reportOpts :: ReportableLens' a ReportOpts+ reportOpts = reportOptsNoUpdate+ {-# INLINE reportOpts #-}++ -- XXX these names are a bit clashy++ period :: ReportableLens' a Period+ period = reportOpts.periodNoUpdate+ {-# INLINE period #-}++ statuses :: ReportableLens' a [Status]+ statuses = reportOpts.statusesNoUpdate+ {-# INLINE statuses #-}++ depth :: ReportableLens' a DepthSpec+ depth = reportOpts.depthNoUpdate+ {-# INLINE depth #-}++ date2 :: ReportableLens' a Bool+ date2 = reportOpts.date2NoUpdate+ {-# INLINE date2 #-}++ real :: ReportableLens' a Bool+ real = reportOpts.realNoUpdate+ {-# INLINE real #-}++ querystring :: ReportableLens' a [T.Text]+ querystring = reportOpts.querystringNoUpdate+ {-# INLINE querystring #-}++instance HasReportOpts ReportOpts++instance HasReportOptsNoUpdate ReportSpec where+ reportOptsNoUpdate = rsReportOpts++instance HasReportOpts ReportSpec where+ reportOpts f rspec = report (error' "Updating ReportSpec failed: try using overEither instead of over or setEither instead of set") $ -- PARTIAL:+ reportOptsToSpec (_rsDay rspec) <$> f (_rsReportOpts rspec)+ {-# INLINE reportOpts #-}++-- | Generate a ReportSpec from a set of ReportOpts on a given day.+reportOptsToSpec :: Day -> ReportOpts -> Either String ReportSpec+reportOptsToSpec day ropts = do+ (argsquery, queryopts) <- parseQueryList day $ querystring_ ropts+ -- If there's an interval in the query opts, it overrides the interval from -p/--period/etc+ let ropts' = case intervalFromQueryOpts queryopts of+ Just i -> ropts{interval_=i}+ Nothing -> ropts+ (rowq, query) <- querySplitRowTerms $ And [queryFromFlags ropts', argsquery]+ return ReportSpec+ { _rsReportOpts = ropts'+ , _rsDay = day+ , _rsQuery = query+ , _rsRowQuery = rowq+ , _rsQueryOpts = queryopts+ }++-- | Update the ReportOpts and the fields derived from it in a ReportSpec,+-- or return an error message if there is a problem such as missing or+-- unparseable options data. This is the safe way to change a ReportSpec,+-- ensuring that all fields (_rsQuery, _rsReportOpts, querystring_, etc.) are in sync.+updateReportSpec :: ReportOpts -> ReportSpec -> Either String ReportSpec+updateReportSpec = setEither reportOpts++-- | Like updateReportSpec, but takes a ReportOpts-modifying function.+updateReportSpecWith :: (ReportOpts -> ReportOpts) -> ReportSpec -> Either String ReportSpec+updateReportSpecWith = overEither reportOpts++-- | Generate a ReportSpec from RawOpts and a provided day, or return an error+-- string if there are regular expression errors.+rawOptsToReportSpec :: Day -> Bool -> RawOpts -> Either String ReportSpec+rawOptsToReportSpec day coloronstdout = reportOptsToSpec day . rawOptsToReportOpts day coloronstdout
+ Hledger/Reports/ReportTypes.hs view
@@ -0,0 +1,249 @@+{- |+New common report types, used by the BudgetReport for now, perhaps all reports later.+-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Reports.ReportTypes+( PeriodicReport(..)+, PeriodicReportRow(..)++, Percentage+, Change+, Balance+, Total+, Average++, periodicReportSpan+, prMapName+, prMapMaybeName++, CompoundPeriodicReport(..)+, CBCSubreportSpec(..)++, DisplayName(..)+, flatDisplayName+, treeDisplayName++, prrShowDebug+, prrFullName+, prrDisplayName+, prrIndent+, prrAdd+) where++import Data.Aeson (ToJSON(..))+import Data.Bifunctor (Bifunctor(..))+import Data.Decimal (Decimal)+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import GHC.Generics (Generic)++import Hledger.Data+import Hledger.Query (Query)+import Hledger.Reports.ReportOptions (ReportOpts)+import Data.Text qualified as T+import Data.List (intercalate)++type Percentage = Decimal++type Change = MixedAmount -- ^ A change in balance during a certain period.+type Balance = MixedAmount -- ^ An ending balance as of some date.+type Total = MixedAmount -- ^ The sum of 'Change's in a report or a report row. Does not make sense for 'Balance's.+type Average = MixedAmount -- ^ The average of 'Change's or 'Balance's in a report or report row.++-- | A periodic report is a generic tabular report, where each row corresponds+-- to some label (usually an account name) and each column to a date period.+-- The column periods are usually consecutive subperiods formed by splitting+-- the overall report period by some report interval (daily, weekly, etc.).+-- It has:+--+-- 1. a list of each column's period (date span)+--+-- 2. a list of rows, each containing:+--+-- * an account label+--+-- * the account's depth+--+-- * A list of amounts, one for each column. Depending on the value type,+-- these can represent balance changes, ending balances, budget+-- performance, etc. (for example, see 'BalanceAccumulation' and+-- "Hledger.Cli.Commands.Balance").+--+-- * the total of the row's amounts for a periodic report,+-- or zero for cumulative/historical reports (since summing+-- end balances generally doesn't make sense).+--+-- * the average of the row's amounts+--+-- 3. the column totals, and the overall grand total (or zero for+-- cumulative/historical reports) and grand average.++data PeriodicReport a b =+ PeriodicReport+ { prDates :: [DateSpan] -- The subperiods formed by splitting the overall+ -- report period by the report interval. For+ -- ending-balance reports, only the end date is+ -- significant. Usually displayed as report columns.+ , prRows :: [PeriodicReportRow a b] -- One row per account in the report.+ , prTotals :: PeriodicReportRow () b -- The grand totals row.+ } deriving (Show, Functor, Generic, ToJSON)++instance Bifunctor PeriodicReport where+ bimap f g pr = pr{prRows = map (bimap f g) $ prRows pr, prTotals = g <$> prTotals pr}++instance HasAmounts b => HasAmounts (PeriodicReport a b) where+ styleAmounts styles r@PeriodicReport{prRows,prTotals} =+ r{prRows=styleAmounts styles prRows, prTotals=styleAmounts styles prTotals}++data PeriodicReportRow a b =+ PeriodicReportRow+ { prrName :: a -- An account name.+ , prrAmounts :: [b] -- The data value for each subperiod.+ , prrTotal :: b -- The total of this row's values.+ , prrAverage :: b -- The average of this row's values.+ } deriving (Show, Functor, Generic, ToJSON)++instance Bifunctor PeriodicReportRow where+ first f prr = prr{prrName = f $ prrName prr}+ second = fmap++instance Semigroup b => Semigroup (PeriodicReportRow a b) where+ (<>) = prrAdd++instance HasAmounts b => HasAmounts (PeriodicReportRow a b) where+ styleAmounts styles r =+ r{prrAmounts=styleAmounts styles $ prrAmounts r+ ,prrTotal =styleAmounts styles $ prrTotal r+ ,prrAverage=styleAmounts styles $ prrAverage r+ }++prrShowDebug :: PeriodicReportRow DisplayName MixedAmount -> String+prrShowDebug (PeriodicReportRow dname amts _tot _avg) =+ unwords [+ T.unpack $ displayFull dname,+ "",+ intercalate " | " $ map showMixedAmount amts+ ]++-- | Add two 'PeriodicReportRows', preserving the name of the first.+prrAdd :: Semigroup b => PeriodicReportRow a b -> PeriodicReportRow a b -> PeriodicReportRow a b+prrAdd (PeriodicReportRow n1 amts1 t1 a1) (PeriodicReportRow _ amts2 t2 a2) =+ PeriodicReportRow n1 (zipWithPadded (<>) amts1 amts2) (t1 <> t2) (a1 <> a2)++-- | Version of 'zipWith' which will not end on the shortest list, but will copy the rest of the longer list.+zipWithPadded :: (a -> a -> a) -> [a] -> [a] -> [a]+zipWithPadded f (a:as) (b:bs) = f a b : zipWithPadded f as bs+zipWithPadded _ as [] = as+zipWithPadded _ [] bs = bs++-- | Figure out the overall date span of a PeriodicReport+periodicReportSpan :: PeriodicReport a b -> DateSpan+periodicReportSpan (PeriodicReport colspans _ _) =+ case colspans of+ [] -> DateSpan Nothing Nothing+ s:_ -> DateSpan (Exact <$> spanStart s) (Exact <$> spanEnd (last colspans))++-- | Map a function over the row names.+prMapName :: (a -> b) -> PeriodicReport a c -> PeriodicReport b c+prMapName f report = report{prRows = map (prrMapName f) $ prRows report}++-- | Map a function over the row names, possibly discarding some.+prMapMaybeName :: (a -> Maybe b) -> PeriodicReport a c -> PeriodicReport b c+prMapMaybeName f report = report{prRows = mapMaybe (prrMapMaybeName f) $ prRows report}++-- | Map a function over the row names of the PeriodicReportRow.+prrMapName :: (a -> b) -> PeriodicReportRow a c -> PeriodicReportRow b c+prrMapName f row = row{prrName = f $ prrName row}++-- | Map maybe a function over the row names of the PeriodicReportRow.+prrMapMaybeName :: (a -> Maybe b) -> PeriodicReportRow a c -> Maybe (PeriodicReportRow b c)+prrMapMaybeName f row = case f $ prrName row of+ Nothing -> Nothing+ Just a -> Just row{prrName = a}+++-- | A compound balance report has:+--+-- * an overall title+--+-- * the period (date span) of each column+--+-- * one or more named, normal-positive multi balance reports,+-- with columns corresponding to the above, and a flag indicating+-- whether they increased or decreased the overall totals+--+-- * a list of overall totals for each column, and their grand total and average+--+-- It is used in compound balance report commands like balancesheet,+-- cashflow and incomestatement.+data CompoundPeriodicReport a b = CompoundPeriodicReport+ { cbrTitle :: Text+ , cbrDates :: [DateSpan]+ , cbrSubreports :: [(Text, PeriodicReport a b, Bool)]+ , cbrTotals :: PeriodicReportRow () b+ } deriving (Show, Functor, Generic, ToJSON)++instance HasAmounts b => HasAmounts (CompoundPeriodicReport a b) where+ styleAmounts styles cpr@CompoundPeriodicReport{cbrSubreports, cbrTotals} =+ cpr{+ cbrSubreports = styleAmounts styles cbrSubreports+ , cbrTotals = styleAmounts styles cbrTotals+ }++instance HasAmounts b => HasAmounts (Text, PeriodicReport a b, Bool) where+ styleAmounts styles (a,b,c) = (a,styleAmounts styles b,c)++-- | Description of one subreport within a compound balance report.+-- Part of a "CompoundBalanceCommandSpec", but also used in hledger-lib.+data CBCSubreportSpec a = CBCSubreportSpec+ { cbcsubreporttitle :: Text -- ^ The title to use for the subreport+ , cbcsubreportquery :: Query -- ^ The Query to use for the subreport+ , cbcsubreportoptions :: ReportOpts -> ReportOpts -- ^ A function to transform the ReportOpts used to produce the subreport+ , cbcsubreporttransform :: PeriodicReport DisplayName MixedAmount -> PeriodicReport a MixedAmount -- ^ A function to transform the result of the subreport+ , cbcsubreportincreasestotal :: Bool -- ^ Whether the subreport and overall report total are of the same sign (e.g. Assets are normally+ -- positive in a balance sheet report, as is the overall total. Liabilities are normally of the+ -- opposite sign.)+ }+++-- | The number of indentation steps with which to display a report item.+-- 0 means no indentation. 1 means one indent step, which is normally rendered+-- as two spaces in text output, or two no-break spaces in csv/html output.+type NumberOfIndents = Int++-- | A full name, display name, and indent level for an account.+data DisplayName = DisplayName+ { displayFull :: AccountName+ , displayName :: AccountName+ , displayIndent :: NumberOfIndents+ } deriving (Show, Eq, Ord)++instance ToJSON DisplayName where+ toJSON = toJSON . displayFull+ toEncoding = toEncoding . displayFull++-- | Construct a display name for a list report, where full names are shown unindented.+flatDisplayName :: AccountName -> DisplayName+flatDisplayName a = DisplayName a a 0++-- | Construct a display name for a tree report, where leaf names (possibly prefixed by+-- boring parents) are shown indented).+treeDisplayName :: AccountName -> DisplayName+treeDisplayName a = DisplayName a (accountLeafName a) (accountNameLevel a)++-- | Get the full canonical account name from a PeriodicReportRow containing a DisplayName.+prrFullName :: PeriodicReportRow DisplayName a -> AccountName+prrFullName = displayFull . prrName++-- | Get the account display name from a PeriodicReportRow containing a DisplayName.+prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName+prrDisplayName = displayName . prrName++-- | Get the indent level from a PeriodicReportRow containing a DisplayName.+prrIndent :: PeriodicReportRow DisplayName a -> Int+prrIndent = displayIndent . prrName
Hledger/Utils.hs view
@@ -1,427 +1,335 @@ {-|--Standard imports and utilities which are useful everywhere, or needed low-in the module hierarchy. This is the bottom of hledger's module graph.-+Utilities used throughout hledger, or needed low in the module hierarchy.+These are the bottom of hledger's module graph. -} -module Hledger.Utils (---- provide these frequently used modules - or not, for clearer api:- -- module Control.Monad,- -- module Data.List,- -- module Data.Maybe,- -- module Data.Time.Calendar,- -- module Data.Time.Clock,- -- module Data.Time.LocalTime,- -- module Data.Tree,- -- module Debug.Trace,- -- module Text.RegexPR,- -- module Test.HUnit,- -- module Text.Printf,- ---- all of this one:- module Hledger.Utils,- Debug.Trace.trace- ---- and this for i18n - needs to be done in each module I think:- -- module Hledger.Utils.UTF8- )-where-import Codec.Binary.UTF8.String as UTF8 (decodeString, encodeString, isUTF8Encoded)-import Data.Char-import Data.List-import Data.Maybe-import Data.Time.Clock-import Data.Time.LocalTime-import Data.Tree-import Debug.Trace-import System.Info (os)-import Test.HUnit-import Text.ParserCombinators.Parsec-import Text.Printf-import Text.RegexPR--- import qualified Data.Map as Map--- --- import Prelude hiding (readFile,writeFile,getContents,putStr,putStrLn)--- import Hledger.Utils.UTF8+{-# LANGUAGE CPP #-} --- strings+module Hledger.Utils ( -lowercase = map toLower-uppercase = map toUpper+ -- * Functions+ applyN,+ mapM',+ sequence',+ curry2,+ uncurry2,+ curry3,+ uncurry3,+ curry4,+ uncurry4, -strip = lstrip . rstrip-lstrip = dropWhile (`elem` " \t")-rstrip = reverse . lstrip . reverse+ divideSafe, -elideLeft width s =- if length s > width then ".." ++ reverse (take (width - 2) $ reverse s) else s+ -- * Lists+ maximum',+ maximumStrict,+ minimumStrict,+ splitAtElement,+ sumStrict,+ all1,+ takeUntilFails,+ takeUntilFailsNE, -elideRight width s =- if length s > width then take (width - 2) s ++ ".." else s+ -- * Trees+ treeLeaves, -underline :: String -> String-underline s = s' ++ replicate (length s) '-' ++ "\n"- where s'- | last s == '\n' = s- | otherwise = s ++ "\n"+ -- * Tuples+ first3,+ second3,+ third3,+ first4,+ second4,+ third4,+ fourth4,+ first5,+ second5,+ third5,+ fourth5,+ fifth5,+ first6,+ second6,+ third6,+ fourth6,+ fifth6,+ sixth6, --- | Wrap a string in single quotes, and \-prefix any embedded single--- quotes, if it contains whitespace and is not already single- or--- double-quoted.-quoteIfSpaced :: String -> String-quoteIfSpaced s | isSingleQuoted s || isDoubleQuoted s = s- | not $ any (`elem` s) whitespacechars = s- | otherwise = "'"++escapeSingleQuotes s++"'"- where escapeSingleQuotes = regexReplace "'" "\'"+ -- * Misc+ multicol,+ numDigitsInt,+ numDigitsInteger,+ makeHledgerClassyLenses, --- | Quote-aware version of words - don't split on spaces which are inside quotes.--- NB correctly handles "a'b" but not "''a''".-words' :: String -> [String]-words' = map stripquotes . fromparse . parsewith p- where- p = do ss <- (quotedPattern <|> pattern) `sepBy` many1 spacenonewline- -- eof- return ss- pattern = many (noneOf whitespacechars)- quotedPattern = between (oneOf "'\"") (oneOf "'\"") $ many $ noneOf "'\""+ -- * Other+ module Hledger.Utils.Debug,+ module Hledger.Utils.Parse,+ module Hledger.Utils.IO,+ module Hledger.Utils.Regex,+ module Hledger.Utils.String,+ module Hledger.Utils.Text, --- | Quote-aware version of unwords - single-quote strings which contain whitespace-unwords' :: [String] -> String-unwords' = unwords . map singleQuoteIfNeeded+ -- * Tests+ tests_Utils,+ module Hledger.Utils.Test, -singleQuoteIfNeeded s | any (`elem` s) whitespacechars = "'"++s++"'"- | otherwise = s+)+where -whitespacechars = " \t\n\r"+import Data.Char (toLower)+import Data.List (intersperse)+import Data.List.Extra (chunksOf, foldl1', uncons, unsnoc)+import qualified Data.List.NonEmpty as NE+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Set qualified as Set+import Data.Text qualified as T (pack, unpack)+import Data.Tree (foldTree, Tree (Node, subForest))+import Language.Haskell.TH (DecsQ, Name, mkName, nameBase)+import Lens.Micro ((&), (.~))+import Lens.Micro.TH (DefName(TopName), lensClass, lensField, makeLensesWith, classyRules) --- | Strip one matching pair of single or double quotes on the ends of a string.-stripquotes :: String -> String-stripquotes s = if isSingleQuoted s || isDoubleQuoted s then init $ tail s else s+import Hledger.Utils.Debug+import Hledger.Utils.I18n (tests_I18n)+import Hledger.Utils.Parse+import Hledger.Utils.IO+import Hledger.Utils.Regex+import Hledger.Utils.String+import Hledger.Utils.Text+import Hledger.Utils.Test -isSingleQuoted s@(_:_:_) = head s == '\'' && last s == '\''-isSingleQuoted _ = False -isDoubleQuoted s@(_:_:_) = head s == '"' && last s == '"'-isDoubleQuoted _ = False--unbracket :: String -> String-unbracket s- | (head s == '[' && last s == ']') || (head s == '(' && last s == ')') = init $ tail s- | otherwise = s---- | Join multi-line strings as side-by-side rectangular strings of the same height, top-padded.-concatTopPadded :: [String] -> String-concatTopPadded strs = intercalate "\n" $ map concat $ transpose padded- where- lss = map lines strs- h = maximum $ map length lss- ypad ls = replicate (difforzero h (length ls)) "" ++ ls- xpad ls = map (padleft w) ls where w | null ls = 0- | otherwise = maximum $ map length ls- padded = map (xpad . ypad) lss---- | Join multi-line strings as side-by-side rectangular strings of the same height, bottom-padded.-concatBottomPadded :: [String] -> String-concatBottomPadded strs = intercalate "\n" $ map concat $ transpose padded- where- lss = map lines strs- h = maximum $ map length lss- ypad ls = ls ++ replicate (difforzero h (length ls)) ""- xpad ls = map (padleft w) ls where w | null ls = 0- | otherwise = maximum $ map length ls- padded = map (xpad . ypad) lss---- | Compose strings vertically and right-aligned.-vConcatRightAligned :: [String] -> String-vConcatRightAligned ss = intercalate "\n" $ map showfixedwidth ss- where- showfixedwidth = printf (printf "%%%ds" width)- width = maximum $ map length ss---- | Convert a multi-line string to a rectangular string top-padded to the specified height.-padtop :: Int -> String -> String-padtop h s = intercalate "\n" xpadded- where- ls = lines s- sh = length ls- sw | null ls = 0- | otherwise = maximum $ map length ls- ypadded = replicate (difforzero h sh) "" ++ ls- xpadded = map (padleft sw) ypadded---- | Convert a multi-line string to a rectangular string bottom-padded to the specified height.-padbottom :: Int -> String -> String-padbottom h s = intercalate "\n" xpadded- where- ls = lines s- sh = length ls- sw | null ls = 0- | otherwise = maximum $ map length ls- ypadded = ls ++ replicate (difforzero h sh) ""- xpadded = map (padleft sw) ypadded---- | Convert a multi-line string to a rectangular string left-padded to the specified width.-padleft :: Int -> String -> String-padleft w "" = concat $ replicate w " "-padleft w s = intercalate "\n" $ map (printf (printf "%%%ds" w)) $ lines s---- | Convert a multi-line string to a rectangular string right-padded to the specified width.-padright :: Int -> String -> String-padright w "" = concat $ replicate w " "-padright w s = intercalate "\n" $ map (printf (printf "%%-%ds" w)) $ lines s---- | Clip a multi-line string to the specified width and height from the top left.-cliptopleft :: Int -> Int -> String -> String-cliptopleft w h = intercalate "\n" . take h . map (take w) . lines---- | Clip and pad a multi-line string to fill the specified width and height.-fitto :: Int -> Int -> String -> String-fitto w h s = intercalate "\n" $ take h $ rows ++ repeat blankline- where- rows = map (fit w) $ lines s- fit w = take w . (++ repeat ' ')- blankline = replicate w ' '---- encoded platform strings---- | A platform string is a string value from or for the operating system,--- such as a file path or command-line argument (or environment variable's--- name or value ?). On some platforms (such as unix) these are not real--- unicode strings but have some encoding such as UTF-8. This alias does--- no type enforcement but aids code clarity.-type PlatformString = String---- | Convert a possibly encoded platform string to a real unicode string.--- We decode the UTF-8 encoding recommended for unix systems--- (cf http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)--- and leave anything else unchanged.-fromPlatformString :: PlatformString -> String-fromPlatformString s = if UTF8.isUTF8Encoded s then UTF8.decodeString s else s---- | Convert a unicode string to a possibly encoded platform string.--- On unix we encode with the recommended UTF-8--- (cf http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)--- and elsewhere we leave it unchanged.-toPlatformString :: String -> PlatformString-toPlatformString = case os of- "unix" -> UTF8.encodeString- "linux" -> UTF8.encodeString- "darwin" -> UTF8.encodeString- _ -> id---- | A version of error that's better at displaying unicode.-error' :: String -> a-error' = error . toPlatformString+-- Functions --- | A version of userError that's better at displaying unicode.-userError' :: String -> IOError-userError' = userError . toPlatformString+-- | Apply a function the specified number of times,+-- which should be > 0 (otherwise does nothing).+-- Possibly uses O(n) stack ?+applyN :: Int -> (a -> a) -> a -> a+applyN n f | n < 1 = id+ | otherwise = (!! n) . iterate f+-- from protolude, compare+-- applyN :: Int -> (a -> a) -> a -> a+-- applyN n f = X.foldr (.) identity (X.replicate n f) --- math+-- | Like mapM but uses sequence'.+{-# INLINABLE mapM' #-}+mapM' :: Monad f => (a -> f b) -> [a] -> f [b]+mapM' f = sequence' . map f -difforzero :: (Num a, Ord a) => a -> a -> a-difforzero a b = maximum [(a - b), 0]+-- | This is a version of sequence based on difference lists. It is+-- slightly faster but we mostly use it because it uses the heap+-- instead of the stack. This has the advantage that Neil Mitchell’s+-- trick of limiting the stack size to discover space leaks doesn’t+-- show this as a false positive.+{-# INLINABLE sequence' #-}+sequence' :: Monad f => [f a] -> f [a]+sequence' ms = do+ h <- go id ms+ return (h [])+ where+ go h [] = return h+ go h (m:ms') = do+ x <- m+ go (h . (x :)) ms' --- regexps+curry2 :: ((a, b) -> c) -> a -> b -> c+curry2 f x y = f (x, y) --- regexMatch :: String -> String -> MatchFun Maybe-regexMatch r s = matchRegexPR r s+uncurry2 :: (a -> b -> c) -> (a, b) -> c+uncurry2 f (x, y) = f x y --- regexMatchCI :: String -> String -> MatchFun Maybe-regexMatchCI r s = regexMatch (regexToCaseInsensitive r) s+curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d+curry3 f x y z = f (x, y, z) -regexMatches :: String -> String -> Bool-regexMatches r s = isJust $ matchRegexPR r s+uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d+uncurry3 f (x, y, z) = f x y z -regexMatchesCI :: String -> String -> Bool-regexMatchesCI r s = regexMatches (regexToCaseInsensitive r) s+curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e+curry4 f w x y z = f (w, x, y, z) -containsRegex = regexMatchesCI+uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e+uncurry4 f (w, x, y, z) = f w x y z -regexReplace :: String -> String -> String -> String-regexReplace r repl s = gsubRegexPR r repl s+-- | Division, returning 0 when the denominator is 0.+divideSafe :: (Eq a, Fractional a) => a -> a -> a+divideSafe _ 0 = 0+divideSafe a b = a / b -regexReplaceCI :: String -> String -> String -> String-regexReplaceCI r s = regexReplace (regexToCaseInsensitive r) s+-- Lists -regexReplaceBy :: String -> (String -> String) -> String -> String-regexReplaceBy r replfn s = gsubRegexPRBy r replfn s+-- | Total version of maximum, for integral types, giving 0 for an empty list.+maximum' :: Integral a => [a] -> a+maximum' [] = 0+maximum' xs = maximumStrict xs -regexToCaseInsensitive :: String -> String-regexToCaseInsensitive r = "(?i)"++ r+-- | Strict version of maximum that doesn’t leak space+{-# INLINABLE maximumStrict #-}+maximumStrict :: Ord a => [a] -> a+maximumStrict = foldl1' max --- lists+-- | Strict version of minimum that doesn’t leak space+{-# INLINABLE minimumStrict #-}+minimumStrict :: Ord a => [a] -> a+minimumStrict = foldl1' min splitAtElement :: Eq a => a -> [a] -> [[a]]-splitAtElement e l = - case dropWhile (e==) l of- [] -> []- l' -> first : splitAtElement e rest- where- (first,rest) = break (e==) l'---- trees--root = rootLabel-subs = subForest-branches = subForest---- | List just the leaf nodes of a tree-leaves :: Tree a -> [a]-leaves (Node v []) = [v]-leaves (Node _ branches) = concatMap leaves branches---- | get the sub-tree rooted at the first (left-most, depth-first) occurrence--- of the specified node value-subtreeat :: Eq a => a -> Tree a -> Maybe (Tree a)-subtreeat v t- | root t == v = Just t- | otherwise = subtreeinforest v $ subs t---- | get the sub-tree for the specified node value in the first tree in--- forest in which it occurs.-subtreeinforest :: Eq a => a -> [Tree a] -> Maybe (Tree a)-subtreeinforest _ [] = Nothing-subtreeinforest v (t:ts) = case (subtreeat v t) of- Just t' -> Just t'- Nothing -> subtreeinforest v ts- --- | remove all nodes past a certain depth-treeprune :: Int -> Tree a -> Tree a-treeprune 0 t = Node (root t) []-treeprune d t = Node (root t) (map (treeprune $ d-1) $ branches t)---- | apply f to all tree nodes-treemap :: (a -> b) -> Tree a -> Tree b-treemap f t = Node (f $ root t) (map (treemap f) $ branches t)---- | remove all subtrees whose nodes do not fulfill predicate-treefilter :: (a -> Bool) -> Tree a -> Tree a-treefilter f t = Node - (root t) - (map (treefilter f) $ filter (treeany f) $ branches t)- --- | is predicate true in any node of tree ?-treeany :: (a -> Bool) -> Tree a -> Bool-treeany f t = f (root t) || any (treeany f) (branches t)- --- treedrop -- remove the leaves which do fulfill predicate. --- treedropall -- do this repeatedly.---- | show a compact ascii representation of a tree-showtree :: Show a => Tree a -> String-showtree = unlines . filter (regexMatches "[^ \\|]") . lines . drawTree . treemap show---- | show a compact ascii representation of a forest-showforest :: Show a => Forest a -> String-showforest = concatMap showtree---- debugging---- | trace (print on stdout at runtime) a showable expression--- (for easily tracing in the middle of a complex expression)-strace :: Show a => a -> a-strace a = trace (show a) a---- | labelled trace - like strace, with a label prepended-ltrace :: Show a => String -> a -> a-ltrace l a = trace (l ++ ": " ++ show a) a---- | monadic trace - like strace, but works as a standalone line in a monad-mtrace :: (Monad m, Show a) => a -> m a-mtrace a = strace a `seq` return a---- | trace an expression using a custom show function-tracewith :: (a -> String) -> a -> a-tracewith f e = trace (f e) e---- parsing---- | Backtracking choice, use this when alternatives share a prefix.--- Consumes no input if all choices fail.-choice' :: [GenParser tok st a] -> GenParser tok st a-choice' = choice . map Text.ParserCombinators.Parsec.try--parsewith :: Parser a -> String -> Either ParseError a-parsewith p = parse p ""--parseWithCtx :: b -> GenParser Char b a -> String -> Either ParseError a-parseWithCtx ctx p = runParser p ctx ""--fromparse :: Either ParseError a -> a-fromparse = either parseerror id--parseerror :: ParseError -> a-parseerror e = error' $ showParseError e+splitAtElement x l =+ case l of+ [] -> []+ e:es | e==x -> split es+ es -> split es+ where+ split es = let (first,rest) = break (x==) es+ in first : splitAtElement x rest -showParseError :: ParseError -> String-showParseError e = "parse error at " ++ show e+-- | Strict version of sum that doesn’t leak space+{-# INLINABLE sumStrict #-}+sumStrict :: Num a => [a] -> a+sumStrict = foldl' (+) 0 -showDateParseError :: ParseError -> String-showDateParseError e = printf "date parse error (%s)" (intercalate ", " $ tail $ lines $ show e)+-- | Version of all that fails on an empty list.+{-# INLINABLE all1 #-}+all1 :: (a -> Bool) -> [a] -> Bool+all1 _ [] = False+all1 p as = all p as -nonspace :: GenParser Char st Char-nonspace = satisfy (not . isSpace)+-- | Take elements from a non-empty list until a predicate fails, and then keep+-- the first failing element as well.+takeUntilFailsNE :: (a -> Bool) -> NE.NonEmpty a -> NE.NonEmpty a+takeUntilFailsNE p = NE.fromList . takeUntilFails p . NE.toList -- Result guaranteed to be non-empty -spacenonewline :: GenParser Char st Char-spacenonewline = satisfy (`elem` " \v\f\t")+-- | Take elements from a list until a predicate fails, and then keep the first+-- failing element as well.+takeUntilFails :: (a -> Bool) -> [a] -> [a]+takeUntilFails p = foldr (\x -> if p x then (x :) else const [x]) [] -restofline :: GenParser Char st String-restofline = anyChar `manyTill` newline+-- Trees --- time+-- | Get the leaves of this tree as a list. +-- The topmost node ("root" in hledger account trees) is not counted as a leaf.+treeLeaves :: Tree a -> [a]+treeLeaves Node{subForest=[]} = []+treeLeaves t = foldTree (\a bs -> (if null bs then (a:) else id) $ concat bs) t -getCurrentLocalTime :: IO LocalTime-getCurrentLocalTime = do- t <- getCurrentTime- tz <- getCurrentTimeZone- return $ utcToLocalTime tz t+-- Tuples --- testing+first3 (x,_,_) = x+second3 (_,x,_) = x+third3 (_,_,x) = x --- | Get a Test's label, or the empty string.-tname :: Test -> String-tname (TestLabel n _) = n-tname _ = ""+first4 (x,_,_,_) = x+second4 (_,x,_,_) = x+third4 (_,_,x,_) = x+fourth4 (_,_,_,x) = x --- | Flatten a Test containing TestLists into a list of single tests.-tflatten :: Test -> [Test]-tflatten (TestLabel _ t@(TestList _)) = tflatten t-tflatten (TestList ts) = concatMap tflatten ts-tflatten t = [t]+first5 (x,_,_,_,_) = x+second5 (_,x,_,_,_) = x+third5 (_,_,x,_,_) = x+fourth5 (_,_,_,x,_) = x+fifth5 (_,_,_,_,x) = x --- | Filter TestLists in a Test, recursively, preserving the structure.-tfilter :: (Test -> Bool) -> Test -> Test-tfilter p (TestLabel l ts) = TestLabel l (tfilter p ts)-tfilter p (TestList ts) = TestList $ filter (any p . tflatten) $ map (tfilter p) ts-tfilter _ t = t+first6 (x,_,_,_,_,_) = x+second6 (_,x,_,_,_,_) = x+third6 (_,_,x,_,_,_) = x+fourth6 (_,_,_,x,_,_) = x+fifth6 (_,_,_,_,x,_) = x+sixth6 (_,_,_,_,_,x) = x --- | Simple way to assert something is some expected value, with no label.-is :: (Eq a, Show a) => a -> a -> Assertion-a `is` e = assertEqual "" e a+-- Misc --- | Assert a parse result is successful, printing the parse error on failure.-assertParse :: (Either ParseError a) -> Assertion-assertParse parse = either (assertFailure.show) (const (return ())) parse+-- | Convert a list of strings to a multi-line multi-column list+-- fitting within the given width. Not wide character aware.+multicol :: Int -> [String] -> String+multicol _ [] = []+multicol width strs =+ let+ maxwidth = maximum' $ map length strs+ numcols = min (length strs) (width `div` (maxwidth+2))+ itemspercol = length strs `div` numcols+ colitems = chunksOf itemspercol strs+ cols = map unlines colitems+ sep = " "+ in+ T.unpack $ textConcatBottomPadded $ map T.pack $ intersperse sep cols --- | Assert a parse result is successful, printing the parse error on failure.-assertParseFailure :: (Either ParseError a) -> Assertion-assertParseFailure parse = either (const $ return ()) (const $ assertFailure "parse should not have succeeded") parse+-- | Find the number of digits of an 'Int'.+{-# INLINE numDigitsInt #-}+numDigitsInt :: Integral a => Int -> a+numDigitsInt n+ | n == minBound = 19 -- negate minBound is out of the range of Int+ | n < 0 = go (negate n)+ | otherwise = go n+ where+ go a | a < 10 = 1+ | a < 100 = 2+ | a < 1000 = 3+ | a < 10000 = 4+ | a >= 10000000000000000 = 16 + go (a `quot` 10000000000000000)+ | a >= 100000000 = 8 + go (a `quot` 100000000)+ | otherwise = 4 + go (a `quot` 10000) --- | Assert a parse result is some expected value, printing the parse error on failure.-assertParseEqual :: (Show a, Eq a) => (Either ParseError a) -> a -> Assertion-assertParseEqual parse expected = either (assertFailure.show) (`is` expected) parse+-- | Find the number of digits of an Integer.+-- The integer should not have more digits than an Int can count.+-- This is probably inefficient.+numDigitsInteger :: Integer -> Int+numDigitsInteger = length . dropWhile (=='-') . show -printParseError :: (Show a) => a -> IO ()-printParseError e = do putStr "parse error at "; print e+-- | Make classy lenses for Hledger options fields.+-- This is intended to be used with BalancingOpts, InputOpt, ReportOpts,+-- ReportSpec, and CliOpts.+-- When run on X, it will create a typeclass named HasX (except for ReportOpts,+-- which will be named HasReportOptsNoUpdate) containing all the lenses for that type.+-- If the field name starts with an underscore, the lens name will be created+-- by stripping the underscore from the front on the name. If the field name ends with+-- an underscore, the field name ends with an underscore, the lens name will be+-- mostly created by stripping the underscore, but a few names for which this+-- would create too many conflicts instead have a second underscore appended.+-- ReportOpts fields for which updating them requires updating the query in+-- ReportSpec are instead names by dropping the trailing underscore and+-- appending NoUpdate to the name, e.g. querystring_ -> querystringNoUpdate.+--+-- There are a few reasons for the complicated rules.+-- - We have some legacy field names ending in an underscore (e.g. value_)+-- which we want to temporarily accommodate, before eventually switching to+-- a more modern style (e.g. _rsReportOpts)+-- - Certain fields in ReportOpts need to update the enclosing ReportSpec when+-- they are updated, and it is a common programming error to forget to do+-- this. We append NoUpdate to those lenses which will not update the+-- enclosing field, and reserve the shorter name for manually define lenses+-- (or at least something lens-like) which will update the ReportSpec.+-- cf. the lengthy discussion here and in surrounding comments:+-- https://github.com/hledgerorg/hledger/pull/1545#issuecomment-881974554+makeHledgerClassyLenses :: Name -> DecsQ+makeHledgerClassyLenses x = flip makeLensesWith x $ classyRules+ & lensField .~ (\_ _ n -> fieldName $ nameBase n)+ & lensClass .~ (className . nameBase)+ where+ fieldName n | Just ('_', name) <- uncons n = [TopName (mkName name)]+ | Just (name, '_') <- unsnoc n,+ name `Set.member` queryFields = [TopName (mkName $ name ++ "NoUpdate")]+ | Just (name, '_') <- unsnoc n,+ name `Set.member` commonFields = [TopName (mkName $ name ++ "__")]+ | Just (name, '_') <- unsnoc n = [TopName (mkName name)]+ | otherwise = [] --- misc+ -- Fields which would cause too many conflicts if we exposed lenses with these names.+ commonFields = Set.fromList+ [ "empty", "drop", "color", "transpose", "title" -- ReportOpts+ , "anon", "new", "auto" -- InputOpts+ , "rawopts", "file", "debug", "width" -- CliOpts+ ] -isLeft :: Either a b -> Bool-isLeft (Left _) = True-isLeft _ = False+ -- When updating some fields of ReportOpts within a ReportSpec, we need to+ -- update the rsQuery term as well. To do this we implement a special+ -- HasReportOpts class with some special behaviour. We therefore give the+ -- basic lenses a special NoUpdate name to avoid conflicts.+ className "ReportOpts" = Just (mkName "HasReportOptsNoUpdate", mkName "reportOptsNoUpdate")+ className (x':xs) = Just (mkName ("Has" ++ x':xs), mkName (toLower x' : xs))+ className [] = Nothing -isRight :: Either a b -> Bool-isRight = not . isLeft+ -- Fields of ReportOpts which need to update the Query when they are updated.+ queryFields = Set.fromList ["period", "statuses", "depth", "date2", "real", "querystring"] --- | Apply a function the specified number of times. Possibly uses O(n) stack ?-applyN :: Int -> (a -> a) -> a -> a-applyN n f = (!! n) . iterate f+tests_Utils = testGroup "Utils" [+ tests_I18n,+ tests_Text+ ]
+ Hledger/Utils/Debug.hs view
@@ -0,0 +1,718 @@+{- | ++Here are debug tracing/logging helpers built on Debug.Trace, extracted from the hledger project.+Features:++- they can be built in to your program permanently, and activated by a --debug [LEVEL] option+- they can optionally log to a file instead of stderr (for TUI apps)+- they can be used in IO, pure, or startup code+- values are printed with a label, and pretty-printed (using pretty-simple)+- ANSI colour is used when appropriate.++Insert these @dbg*@ helpers at points of interest in your code,+either temporarily while debugging,+or permanently in production code, and activate them with @--debug [1-9]@ on the command line+(@--debug@ with no value means level 1).+For example, this expression:++> dbg4 "foo" foo++will pretty-print foo with a "foo:" label when it is evaluated, but only if --debug's value is 4 or greater.+In other words: use dbg1 for the most useful debug output, dbg9 for the most specialised/verbose.++They are intended to be easy to use and to find in your code, with a consistent naming scheme:++> dbg<LEVEL>Msg STR VAL -- trace/log a string in pure code+> dbg<LEVEL>MsgIO STR -- trace/log a string in IO+>+> dbg<LEVEL> STR VAL -- trace/log a showable value in pure code+> dbg<LEVEL>IO STR VAL -- trace/log a showable value in IO+>+> dbg<LEVEL>With SHOWFN VAL -- trace/log any value++Or if you prefer you can ignore the numbered variants and write an extra argument:++> dbgMsg LEVEL STR VAL+> dbgMsgIO LEVEL STR+>+> dbg LEVEL STR VAL+> dbgIO LEVEL STR VAL+>+> dbgWith LEVEL SHOWFN VAL+>+> dbgTime LEVEL STR VAL -- trace/log a phase timing: STR, and the time and memory allocated since the previous one, after deep-forcing VAL+> dbgTimeIO LEVEL STR VAL -- the same, in IO++Haskell values will be pretty-printed by default, using pretty-simple.++ANSI color will also be used if appropriate,+respecting output capabilities, @NO_COLOR@, and/or a @--color [YNA]@ (or @--colour@) command line option.++These helpers normally print output on stderr, but can automatically log to a file instead,+which can be useful for TUI apps which are redrawing the screen.+To enable this logging mode, use @withProgName@ to add a ".log" suffix to the program name:++> main = withProgName "PROGRAM.log" $ do ...++Now all dbg calls will log to @PROGRAM.log@ in the current directory.++Logging, and reading the command line\/program name\/output context use unsafePerformIO,+so that these can be used anywhere, including early in your program before command line parsing is complete.+As a consequence, if you are testing in GHCI and want to change the debug level, you'll need to reload this module.++The @dbg@ function name clashes with the one in Text.Megaparsec.Debug, unfortunately; sorry about that.+If you are also using that, use qualified imports, or our @dbg_@ alias, to avoid the clash.++The meaning of debug levels is up to you. Eg hledger uses them as follows:++@+Debug level: What to show:+------------ ---------------------------------------------------------+0 normal program output only+1 useful warnings, most common troubleshooting info, phase timings+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 / more in-depth info+@++It's not yet possible to select debug output by topic; that would be useful.++-}++-- Disabled until 0.1.2.0 is released with windows support:+-- This module also exports Debug.Trace and the breakpoint package's Debug.Breakpoint.++-- more:+-- http://hackage.haskell.org/packages/archive/TraceUtils/0.1.0.2/doc/html/Debug-TraceUtils.html+-- http://hackage.haskell.org/packages/archive/trace-call/0.1/doc/html/Debug-TraceCall.html+-- http://hackage.haskell.org/packages/archive/htrace/0.1/doc/html/Debug-HTrace.html+-- http://hackage.haskell.org/packages/archive/traced/2009.7.20/doc/html/Debug-Traced.html+-- https://hackage.haskell.org/package/debug++-- internal helpers, currently not exported:++-- * Tracing to stderr+-- These print to stderr.+-- This output will be interleaved with the program's normal output,+-- which can be helpful for understanding code execution.+--+-- ,traceWith+-- ,traceAt+-- ,traceAtWith+-- ,ptrace+-- ,ptraceAt+-- ,ptraceAtIO++-- * Logging to a log file+-- These append to a PROGRAM.log file in the current directory.+-- PROGRAM is normally the name of the executable, but it can change+-- eg when running in GHCI. So when using these, you should call+-- @withProgName@ to ensure a stable program name.+-- Eg: @main = withProgName "PROGRAM" $ do ...@.+--+-- ,log'+-- ,logAt+-- ,logIO+-- ,logAtIO+-- ,logWith+-- ,logAtWith+-- ,plogAt+-- ,plogAtIO++{-# LANGUAGE CPP #-}+{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}++module Hledger.Utils.Debug (++ -- * Debug level+ debugLevel++ -- * Trace/log a string+ ,dbgMsg+ ,dbg0Msg+ ,dbg1Msg+ ,dbg2Msg+ ,dbg3Msg+ ,dbg4Msg+ ,dbg5Msg+ ,dbg6Msg+ ,dbg7Msg+ ,dbg8Msg+ ,dbg9Msg++ -- * Trace/log a string in IO+ ,dbgMsgIO+ ,dbg0MsgIO+ ,dbg1MsgIO+ ,dbg2MsgIO+ ,dbg3MsgIO+ ,dbg4MsgIO+ ,dbg5MsgIO+ ,dbg6MsgIO+ ,dbg7MsgIO+ ,dbg8MsgIO+ ,dbg9MsgIO++ -- * Trace/log a value+ ,dbg+ ,dbg_+ ,dbg0+ ,dbg1+ ,dbg2+ ,dbg3+ ,dbg4+ ,dbg5+ ,dbg6+ ,dbg7+ ,dbg8+ ,dbg9++ -- * Trace/log a value in IO+ ,dbgIO+ ,dbg0IO+ ,dbg1IO+ ,dbg2IO+ ,dbg3IO+ ,dbg4IO+ ,dbg5IO+ ,dbg6IO+ ,dbg7IO+ ,dbg8IO+ ,dbg9IO++ -- * Trace/log a value with a show function+ ,dbgWith+ ,dbg0With+ ,dbg1With+ ,dbg2With+ ,dbg3With+ ,dbg4With+ ,dbg5With+ ,dbg6With+ ,dbg7With+ ,dbg8With+ ,dbg9With++ -- * Trace/log phase timings+ ,dbgTime+ ,dbgTimeIO+ ,dbgTimeResetIO++ -- * Utilities+ ,lbl_+ ,progName++ -- * ghc-debug helpers+ ,ghcDebugSupportedInLib+ ,GhcDebugMode(..)+ ,ghcDebugMode+ ,withGhcDebug'+ ,ghcDebugPause'++ -- * Re-exports: Debug.Trace+ -- ,module Debug.Breakpoint+ ,module Debug.Trace++ )+where++import Control.DeepSeq (NFData, force)+import Control.Exception (evaluate)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Int (Int64)+import Data.List hiding (uncons)+import Debug.Trace (trace, traceIO, traceShowId)+import GHC.Clock (getMonotonicTime)+import GHC.Conc (getAllocationCounter)+#ifdef GHCDEBUG+import GHC.Debug.Stub (pause, withGhcDebug)+#endif+import Safe (readDef)+import System.Environment (getProgName)+-- import System.Exit (exitFailure)+import System.IO.Unsafe (unsafePerformIO)+import Text.Printf (printf)++import Hledger.Utils.IO (progArgs, pshow, pshow')+++-- | The program name as returned by @getProgName@.+-- It's best to set this explicitly at program startup with @withProgName@,+-- otherwise when running in GHCI (eg) it will change to "<interactive>".+-- Setting it with a ".log" suffix causes some functions below+-- to log instead of trace.+{-# NOINLINE modifiedProgName #-}+modifiedProgName :: String+modifiedProgName = unsafePerformIO getProgName++-- | The progam name, with any ".log" suffix removed.+progName :: String+progName =+ if ".log" `isSuffixOf` modifiedProgName+ then reverse $ drop 4 $ reverse modifiedProgName+ else modifiedProgName++-- | The program's debug output verbosity, from 0 to 9.+-- The default is 0 meaning no debug output.+-- This can be overridden by running the program with a --debug [1-9] command line option;+-- a --debug flag with no value means 1.+-- Uses unsafePerformIO to read the command line.+-- When running in GHCI, changing this requires reloading this module.+debugLevel :: Int+debugLevel = case dropWhile (/="--debug") progArgs of+ ["--debug"] -> 1+ "--debug":n:_ -> readDef 1 n+ _ ->+ case take 1 $ filter ("--debug" `isPrefixOf`) progArgs of+ ['-':'-':'d':'e':'b':'u':'g':'=':v] -> readDef 1 v+ _ -> 0++-- | Trace (print to stderr) a string if the program debug level is at+-- or above the specified level. At level 0, always prints. Otherwise,+-- uses unsafePerformIO.+traceAt :: Int -> String -> a -> a+traceAt level+ | level > 0 && debugLevel < level = const id+ | otherwise = trace++-- | Like traceAt, but sequences properly in IO.+traceAtIO :: (MonadIO m) => Int -> String -> m ()+traceAtIO level msg =+ if level > 0 && debugLevel < level+ then return ()+ else liftIO $ traceIO msg++-- -- | Trace a value with the given show function before returning it.+-- traceWith :: (a -> String) -> a -> a+-- traceWith f a = trace (f a) a++-- | Trace (print to stderr) a showable value using a custom show function,+-- if the program debug level is at or above the specified level.+-- At level 0, always prints. Otherwise, uses unsafePerformIO.+traceAtWith :: Int -> (a -> String) -> a -> a+traceAtWith level f a = traceAt level (f a) a++-- -- | Pretty-trace a showable value before returning it.+-- -- Like Debug.Trace.traceShowId, but pretty-printing and easier to type.+-- ptrace :: Show a => a -> a+-- ptrace = traceWith pshow++-- | Pretty-print a label and a showable value to the console+-- if the program debug level is at or above the specified level.+-- At level 0, always prints. Otherwise, uses unsafePerformIO.+ptraceAt :: Show a => Int -> String -> a -> a+ptraceAt level+ | level > 0 && debugLevel < level = const id+ | otherwise = \lbl a -> trace (labelledPretty True lbl a) a++-- Pretty-print a showable value with a label, with or without allowing ANSI color.+labelledPretty :: Show a => Bool -> String -> a -> String+labelledPretty allowcolour lbl a = lbl ++ ":" ++ nlorspace ++ intercalate "\n" ls'+ where+ ls = lines $ (if allowcolour then pshow else pshow') a+ nlorspace | length ls > 1 = "\n"+ | otherwise = replicate (max 1 $ 11 - length lbl) ' '+ ls' | length ls > 1 = map (' ':) ls+ | otherwise = ls++-- | Like ptraceAt, but sequences properly in IO.+ptraceAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()+ptraceAtIO level label a =+ if level > 0 && debugLevel < level+ then return ()+ else liftIO $ traceIO (labelledPretty True label a)+++-- | The debug log file: PROGNAME.log in the current directory.+-- See modifiedProgName.+debugLogFile :: FilePath+debugLogFile = progName ++ ".log"++-- | Log a string to the debug log before returning the second argument.+-- Uses unsafePerformIO.+log' :: String -> a -> a+log' s x = unsafePerformIO $ do+ evaluate (force s) -- to complete any previous logging before we attempt more+ appendFile debugLogFile (s ++ "\n")+ return x++-- | Log a string to the debug log before returning the second argument,+-- if the program debug level is at or above the specified level.+-- At level 0, always logs. Otherwise, uses unsafePerformIO.+logAt :: Int -> String -> a -> a+logAt level str+ | level > 0 && debugLevel < level = id+ | otherwise = log' str++-- | Like log' but sequences properly in IO.+logIO :: MonadIO m => String -> m ()+logIO s = do+ liftIO $ evaluate (force s) -- to complete any previous logging before we attempt more+ liftIO $ appendFile debugLogFile (s ++ "\n")++-- | Like logAt, but convenient to use in IO.+logAtIO :: (MonadIO m) => Int -> String -> m ()+logAtIO level str+ | level > 0 && debugLevel < level = return ()+ | otherwise = logIO str++-- -- | Log a value to the debug log with the given show function before returning it.+-- logWith :: (a -> String) -> a -> a+-- logWith f a = log' (f a) a++-- | Log a string to the debug log before returning the second argument,+-- if the program debug level is at or above the specified level.+-- At level 0, always logs. Otherwise, uses unsafePerformIO.+logAtWith :: Int -> (a -> String) -> a -> a+logAtWith level f a = logAt level (f a) a++-- | Pretty-log a label and showable value to the debug log,+-- if the program debug level is at or above the specified level. +-- At level 0, always prints. Otherwise, uses unsafePerformIO.+plogAt :: (Show a) => Int -> String -> a -> a+plogAt level+ | level > 0 && debugLevel < level = const id+ | otherwise = \lbl a -> log' (labelledPretty False lbl a) a++-- | Like ptraceAt, but sequences properly in IO.+plogAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()+plogAtIO level label a =+ if level > 0 && debugLevel < level+ then return ()+ else logIO (labelledPretty False label a)+++-- | Should dbg* log to a file instead of tracing to stderr ?+-- True if the (internal) program name ends with ".log".+shouldLog :: Bool+shouldLog = ".log" `isSuffixOf` modifiedProgName+++-- | Trace or log a string if the program debug level is at or above the specified level,+-- then return the second argument.+dbgMsg :: Int -> String -> a -> a+dbgMsg = if shouldLog then logAt else traceAt++dbg0Msg :: String -> a -> a+dbg0Msg = dbgMsg 0++dbg1Msg :: String -> a -> a+dbg1Msg = dbgMsg 1++dbg2Msg :: String -> a -> a+dbg2Msg = dbgMsg 2++dbg3Msg :: String -> a -> a+dbg3Msg = dbgMsg 3++dbg4Msg :: String -> a -> a+dbg4Msg = dbgMsg 4++dbg5Msg :: String -> a -> a+dbg5Msg = dbgMsg 5++dbg6Msg :: String -> a -> a+dbg6Msg = dbgMsg 6++dbg7Msg :: String -> a -> a+dbg7Msg = dbgMsg 7++dbg8Msg :: String -> a -> a+dbg8Msg = dbgMsg 8++dbg9Msg :: String -> a -> a+dbg9Msg = dbgMsg 9+++-- | Like dbgMsg, but sequences properly in IO.+dbgMsgIO :: (MonadIO m) => Int -> String -> m ()+dbgMsgIO = if shouldLog then logAtIO else traceAtIO++dbg0MsgIO :: (MonadIO m) => String -> m ()+dbg0MsgIO = dbgMsgIO 0++dbg1MsgIO :: (MonadIO m) => String -> m ()+dbg1MsgIO = dbgMsgIO 1++dbg2MsgIO :: (MonadIO m) => String -> m ()+dbg2MsgIO = dbgMsgIO 2++dbg3MsgIO :: (MonadIO m) => String -> m ()+dbg3MsgIO = dbgMsgIO 3++dbg4MsgIO :: (MonadIO m) => String -> m ()+dbg4MsgIO = dbgMsgIO 4++dbg5MsgIO :: (MonadIO m) => String -> m ()+dbg5MsgIO = dbgMsgIO 5++dbg6MsgIO :: (MonadIO m) => String -> m ()+dbg6MsgIO = dbgMsgIO 6++dbg7MsgIO :: (MonadIO m) => String -> m ()+dbg7MsgIO = dbgMsgIO 7++dbg8MsgIO :: (MonadIO m) => String -> m ()+dbg8MsgIO = dbgMsgIO 8++dbg9MsgIO :: (MonadIO m) => String -> m ()+dbg9MsgIO = dbgMsgIO 9+++-- | Trace or log a label and showable value, pretty-printed,+-- if the program debug level is at or above the specified level;+-- then return the value.+dbg :: (Show a) => Int -> String -> a -> a+dbg = if shouldLog then plogAt else ptraceAt++-- | Alias for dbg, can be used to avoid namespace clashes.+dbg_ :: (Show a) => Int -> String -> a -> a+dbg_ = dbg++dbg0 :: Show a => String -> a -> a+dbg0 = dbg 0++dbg1 :: Show a => String -> a -> a+dbg1 = dbg 1++dbg2 :: Show a => String -> a -> a+dbg2 = dbg 2++dbg3 :: Show a => String -> a -> a+dbg3 = dbg 3++dbg4 :: Show a => String -> a -> a+dbg4 = dbg 4++dbg5 :: Show a => String -> a -> a+dbg5 = dbg 5++dbg6 :: Show a => String -> a -> a+dbg6 = dbg 6++dbg7 :: Show a => String -> a -> a+dbg7 = dbg 7++dbg8 :: Show a => String -> a -> a+dbg8 = dbg 8++dbg9 :: Show a => String -> a -> a+dbg9 = dbg 9+++-- | Like dbg, but sequences properly in IO.+dbgIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()+dbgIO = if shouldLog then plogAtIO else ptraceAtIO++dbg0IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg0IO = dbgIO 0++dbg1IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg1IO = dbgIO 1++dbg2IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg2IO = dbgIO 2++dbg3IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg3IO = dbgIO 3++dbg4IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg4IO = dbgIO 4++dbg5IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg5IO = dbgIO 5++dbg6IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg6IO = dbgIO 6++dbg7IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg7IO = dbgIO 7++dbg8IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg8IO = dbgIO 8++dbg9IO :: (MonadIO m, Show a) => String -> a -> m ()+dbg9IO = dbgIO 9+++-- | Like dbg, but with a custom show function.+dbgWith :: Int -> (a -> String) -> a -> a+dbgWith = if shouldLog then logAtWith else traceAtWith++dbg0With :: (a -> String) -> a -> a+dbg0With = dbgWith 0++dbg1With :: (a -> String) -> a -> a+dbg1With = dbgWith 1++dbg2With :: (a -> String) -> a -> a+dbg2With = dbgWith 2++dbg3With :: (a -> String) -> a -> a+dbg3With = dbgWith 3++dbg4With :: (a -> String) -> a -> a+dbg4With = dbgWith 4++dbg5With :: (a -> String) -> a -> a+dbg5With = dbgWith 5++dbg6With :: (a -> String) -> a -> a+dbg6With = dbgWith 6++dbg7With :: (a -> String) -> a -> a+dbg7With = dbgWith 7++dbg8With :: (a -> String) -> a -> a+dbg8With = dbgWith 8++dbg9With :: (a -> String) -> a -> a+dbg9With = dbgWith 9+++-- | Wall clock seconds (from a monotonic clock), and the current thread's allocation counter+-- (which counts downwards, so bytes allocated = earlier reading - later reading).+type TimeReadings = (Double, Int64)++timeReadings :: IO TimeReadings+timeReadings = (,) <$> getMonotonicTime <*> getAllocationCounter++-- | The sum of the phase times reported so far (since program start, or the last dbgTimeResetIO),+-- and the readings taken at the most recent phase timing (or at first use).+{-# NOINLINE dbgTimeState #-}+dbgTimeState :: IORef (Double, TimeReadings)+dbgTimeState = unsafePerformIO $ timeReadings >>= \r -> newIORef (0, r)++-- | Reset the baseline for phase timings (see dbgTime) to now.+-- hledger calls this at program start, so that the first timing line includes startup time.+dbgTimeResetIO :: MonadIO m => m ()+dbgTimeResetIO = liftIO $ timeReadings >>= \r -> writeIORef dbgTimeState (0, r)++-- | Trace or log a phase timing line, if the program debug level is at or above the specified level:+-- the label, the wall clock time and megabytes allocated since the previous phase timing+-- (or since program start), and the sum of the phase times reported so far; then return the value.+-- The value is deep-forced first, so that the work of producing it is charged to this phase;+-- the cost of the deep-forcing itself (traversing the whole value) is measured and excluded.+-- When the debug level is lower, the value is returned unforced.+-- Uses unsafePerformIO; in IO code, prefer dbgTimeIO.+dbgTime :: NFData a => Int -> String -> a -> a+dbgTime level lbl x+ | level > 0 && debugLevel < level = x+ | otherwise = unsafePerformIO $ dbgTimeIO level lbl x+{-# NOINLINE dbgTime #-}++-- | Like dbgTime, but sequences properly in IO.+dbgTimeIO :: (MonadIO m, NFData a) => Int -> String -> a -> m a+dbgTimeIO level lbl x+ | level > 0 && debugLevel < level = return x+ | otherwise = liftIO $ do+ _ <- readIORef dbgTimeState -- initialise the baseline now, if this is the first use+ x' <- evaluate (force x)+ (total, (tprev, aprev)) <- readIORef dbgTimeState -- (the latest timing may have happened during the forcing)+ (t1, a1) <- timeReadings+ -- Deep-forcing a large value costs something even when it is already evaluated;+ -- measure that by traversing it once more, and exclude it from this phase's figures.+ _ <- evaluate (force x')+ (t2, a2) <- timeReadings+ let dt = max 0 $ (t1 - tprev) - (t2 - t1)+ da = max 0 $ (aprev - a1) - (a1 - a2)+ total' = total + dt+ writeIORef dbgTimeState (total', (t2, a2))+ dbgMsgIO level $ printf "%-44s %7.3fs %9.1f MB (%.3fs so far)" lbl dt (fromIntegral da / 1e6 :: Double) total'+ return x'++-- | Helper for producing debug messages:+-- concatenates a name (eg a function name),+-- short description of the value being logged,+-- and string representation of the value.+--+-- Eg: @let lbl = lbl_ "print"@,+-- @dbg1With (lbl "part 1".show) ...@.+--+lbl_ :: String -> String -> String -> String+lbl_ name desc val = name <> ": " <> desc <> ":" <> " " <> val++-- XXX the resulting function is constrained to only one value type+-- -- | A helper for defining a local "dbg" function.+-- -- Given a debug level and a topic string (eg, a function name),+-- -- it generates a function which takes+-- -- - a description string,+-- -- - a value-to-string show function,+-- -- - and a value to be inspected,+-- -- debug-logs the topic, description and result of calling the show function on the value,+-- -- formatted nicely, at the specified debug level or above,+-- -- then returns the value.+-- dbg_ :: forall a. Int -> String -> (String -> (a -> String) -> a -> a)+-- dbg_ level topic =+-- \desc showfn val ->+-- dbgWith level (lbl_ topic desc . showfn) val+-- {-# HLINT ignore "Redundant lambda" #-}+++-- | Whether ghc-debug support is included in this build, and if so, how it will behave.+-- When hledger is built with the @ghcdebug@ cabal flag (off by default, because of extra deps),+-- it can listen (on unix ?) for connections from ghc-debug clients like ghc-debug-brick,+-- for pausing/resuming the program and inspecting memory usage and profile information.+--+-- With a ghc-debug-supporting build, ghc-debug can be enabled by running hledger with+-- a negative --debug level. There are three different modes:+-- --debug=-1 - run normally (can be paused/resumed by a ghc-debug client),+-- --debug=-2 - pause and await client commands at program start (not useful currently),+-- --debug=-3 - pause and await client commands at program end.+data GhcDebugMode =+ GDNotSupported+ | GDDisabled+ | GDNoPause+ | GDPauseAtStart+ | GDPauseAtEnd+ -- keep synced with ghcDebugMode+ deriving (Eq,Ord,Show)++-- | Is the hledger-lib package built with ghc-debug support ?+ghcDebugSupportedInLib :: Bool+ghcDebugSupportedInLib =+#ifdef GHCDEBUG+ True+#else+ False+#endif++-- | Should the program open a socket allowing control by ghc-debug-brick or similar ghc-debug client ?+-- See GhcDebugMode.+ghcDebugMode :: GhcDebugMode+ghcDebugMode =+#ifdef GHCDEBUG+ case debugLevel of+ _ | not ghcDebugSupportedInLib -> GDNotSupported+ (-1) -> GDNoPause+ (-2) -> GDPauseAtStart+ (-3) -> GDPauseAtEnd+ _ -> GDDisabled+ -- keep synced with GhcDebugMode+#else+ GDNotSupported+#endif++-- | When ghc-debug support has been built into the program and enabled at runtime with --debug=-N,+-- this calls ghc-debug's withGhcDebug; otherwise it's a no-op.+withGhcDebug' =+#ifdef GHCDEBUG+ if ghcDebugMode > GDDisabled then withGhcDebug else id+#else+ id+#endif++-- | When ghc-debug support has been built into the program, this calls ghc-debug's pause, otherwise it's a no-op.+ghcDebugPause' :: IO ()+ghcDebugPause' =+#ifdef GHCDEBUG+ pause+#else+ return ()+#endif
+ Hledger/Utils/I18n.hs view
@@ -0,0 +1,1020 @@+{-|+Internationalization support for hledger's user-facing output.++Translations live in catalogs in the gettext PO file format, which the+usual translator tools (Poedit, Weblate, Lokalize) understand. Built-in+catalogs are embedded in the executables; a user can override one, or add+a language, with a file in their hledger config directory (see+'translationsOverrideDir'). Lookups are pure functions of a 'Translations'+value, so there is no process-global locale state, and hledger-web can+serve a different language to each request.++Conventions:++- The msgid is the English text. A missing or empty translation falls+ back to it, and 'noTranslations' is the identity, so English output is+ unaffected by this machinery.++- Parameters are @{name}@ placeholders substituted after lookup ('trf'),+ never printf formats: a translation can not crash the program.++- Short words used in more than one sense carry a context ('trc').++- Use 'tr' (or 'trc', 'trf') where text is displayed and a 'Translations'+ value is at hand, usually from the report options. Use 'i18n' (or+ 'i18nc') only to mark a literal that is stored earlier, in data such as+ a report spec or a menu item, before any catalog is available; it is+ then translated with 'tr' at display time. Both forms are what the+ catalog extraction tool looks for.++- A malformed catalog is reported as a warning and ignored.++This module is experimental and its API may change.+-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Utils.I18n (+ -- * Translations+ Translations(..),+ PluralForms(..),+ noTranslations,+ tr,+ trc,+ trf,+ trn,+ i18n,+ i18nc,+ trTimeLocale,+ translationsForLangOption,+ substitutePlaceholders,+ placeholders,+ -- * Catalogs+ parsePo,+ mergeTranslations,+ builtinTranslations,+ builtinLanguages,+ availableLanguages,+ loadTranslations,+ loadAllTranslations,+ translationsOverrideDir,+ startingCatalog,+ writeStartingCatalog,+ -- * Language tags+ isValidLangTag,+ normalizeLangTag,+ langTagCandidates,+ shortLangTag,+ resolveLang,+ langPrefsFromEnv,+ -- * Plural forms+ parsePluralForms,+ -- * Tests+ tests_I18n,+) where++import Control.Monad (unless, void, when)+import Control.Monad.Combinators.Expr (Operator(..), makeExprParser)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Char (chr, isAlpha, isAlphaNum, isAscii, isHexDigit, toLower)+import Data.Either (isLeft, rights)+import Data.List (inits, intercalate, partition, sort, sortOn)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as M+import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)+import Data.Set (Set)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)+import Data.Time.Format (TimeLocale(..), defaultTimeLocale)+import Data.Void (Void)+import Numeric (readHex, readOct)+import System.Directory (XdgDirectory(..), createDirectoryIfMissing, doesDirectoryExist, getFileSize, getXdgDirectory, listDirectory)+import System.Environment (getEnvironment)+import System.FilePath ((</>), dropExtension, takeExtension)+import Text.Megaparsec+import Text.Megaparsec.Char+import Text.Megaparsec.Char.Lexer qualified as L+import Text.Printf (printf)+import Text.Read (readMaybe)++import Hledger.Utils.Debug (debugLevel, dbg1MsgIO)+import Hledger.Utils.IO (embedFileRelativeBytes, usageError, warnIO)+import Hledger.Utils.Test++-- * Translations++-- | A set of translations for one language, looked up by English text+-- (optionally qualified by a context, see 'trc').+data Translations = Translations+ { trLang :: Text -- ^ language tag, eg "de", "pt-BR", "zh-Hans"+ , trMessages :: Map Text Text -- ^ msgid (or "context\x04msgid") -> translation+ , trPlurals :: Map Text [Text] -- ^ singular msgid -> one translation per plural form+ , trPluralForms :: Maybe PluralForms -- ^ this language's plural rule, from the catalog header+ }++-- | A language's plural rule: how many forms it has, and which form a+-- count selects.+data PluralForms = PluralForms+ { pfCount :: Int+ , pfRule :: Int -> Int+ }++-- | Shows only the language, so that option dumps stay readable.+instance Show Translations where+ show t = "Translations " ++ show (trLang t)++-- | English: every lookup returns its argument.+noTranslations :: Translations+noTranslations = Translations "en" M.empty M.empty Nothing++-- | Translate this English text, or return it unchanged if there is no translation.+tr :: Translations -> Text -> Text+tr t s = fromMaybe s $ M.lookup s (trMessages t)++-- | Like 'tr', but for a short text that is used in more than one sense.+-- The context (eg "column heading") disambiguates it in the catalog.+trc :: Translations -> Text -> Text -> Text+trc t ctx s = fromMaybe s $ M.lookup (msgKey (Just ctx) s) (trMessages t)++-- | Translate this English template, then fill in its @{name}@ placeholders.+-- Placeholders that are not given stay as they are. Values are inserted+-- verbatim, without being scanned for placeholders themselves.+trf :: Translations -> Text -> [(Text, Text)] -> Text+trf t s params = substitutePlaceholders params (tr t s)++-- | Translate a count phrase, choosing the plural form this language uses+-- for the count, then fill in the @{n}@ placeholder. The two English forms+-- are the msgid and msgid_plural; without a translation, the singular is+-- used for 1 and the plural otherwise.+trn :: Translations -> Int -> Text -> Text -> Text+trn t n singular plural = substitutePlaceholders [("n", T.pack (show n))] form+ where+ form = fromMaybe english $ do+ forms <- M.lookup singular (trPlurals t)+ let i = maybe (\k -> if k == 1 then 0 else 1) pfRule (trPluralForms t) n+ f <- if i >= 0 && i < length forms then Just (forms !! i) else Nothing+ if T.null f then Nothing else Just f+ english = if n == 1 then singular else plural++-- | Mark an English literal that is stored now, in data such as a report+-- spec or a menu item, and translated later by 'tr' at the point where it+-- is displayed. This is the identity; its purpose is to make the catalog+-- extraction tool collect the literal. (Like gettext's N_.) Where a+-- 'Translations' value is already at hand, use 'tr' directly instead.+i18n :: Text -> Text+i18n = id++-- | Like 'i18n', for a literal that will be translated with a context by 'trc'.+i18nc :: Text -> Text -> Text+i18nc _ctx s = s++-- | The default time locale with month names translated, for formatting+-- dates. The names are looked up with contexts "month" (full name) and+-- "month abbrev" (short name, used as a column heading).+trTimeLocale :: Translations -> TimeLocale+trTimeLocale t = defaultTimeLocale{ months = zipWith (\f a -> (name "month" f, name "month abbrev" a)) fulls abbrevs }+ where+ name ctx = T.unpack . trc t ctx+ -- TRANSLATORS: stand-alone (nominative) month names, as used in a column heading.+ fulls =+ [ i18nc "month" "January", i18nc "month" "February", i18nc "month" "March"+ , i18nc "month" "April", i18nc "month" "May", i18nc "month" "June"+ , i18nc "month" "July", i18nc "month" "August", i18nc "month" "September"+ , i18nc "month" "October", i18nc "month" "November", i18nc "month" "December"+ ]+ -- TRANSLATORS: short stand-alone month names, as used in a column heading.+ abbrevs =+ [ i18nc "month abbrev" "Jan", i18nc "month abbrev" "Feb", i18nc "month abbrev" "Mar"+ , i18nc "month abbrev" "Apr", i18nc "month abbrev" "May", i18nc "month abbrev" "Jun"+ , i18nc "month abbrev" "Jul", i18nc "month abbrev" "Aug", i18nc "month abbrev" "Sep"+ , i18nc "month abbrev" "Oct", i18nc "month abbrev" "Nov", i18nc "month abbrev" "Dec"+ ]++-- | Choose translations according to the value of a --lang option.+-- No option means English, without reading any files. "auto" follows the+-- LANGUAGE, LC_ALL, LC_MESSAGES and LANG environment variables (see+-- 'langPrefsFromEnv'), falling back to English. Anything else is a+-- language tag, which must have a catalog, built-in or in+-- 'translationsOverrideDir'; otherwise a usage error is raised.+translationsForLangOption :: Maybe String -> IO Translations+translationsForLangOption Nothing = return noTranslations+translationsForLangOption (Just "auto") = do+ available <- availableLanguages+ prefs <- langPrefsFromEnv <$> getEnvironment+ maybe (return noTranslations) loadTranslations $ resolveLang available prefs+translationsForLangOption (Just s)+ | map toLower s `elem` ["c", "posix"] = return noTranslations+ | otherwise = do+ available <- availableLanguages+ case resolveLang available [T.pack s] of+ Just lang -> loadTranslations lang+ Nothing -> usageError $ "--lang: no translations are available for " ++ show s+ ++ " (available: " ++ T.unpack (T.intercalate ", " $ map shortLangTag available) ++ ")"++-- | Split a template into its literal text and its @{name}@ placeholders.+scanPlaceholders :: Text -> [Either Text Text]+scanPlaceholders s = case T.breakOn "{" s of+ (before, rest)+ | T.null rest -> [Left before | not (T.null before)]+ | otherwise ->+ let (name, rest') = T.break (\c -> c == '}' || c == '{' || not (isNameChar c)) (T.drop 1 rest)+ in case T.uncons rest' of+ Just ('}', remaining) | not (T.null name) -> Left before : Right name : scanPlaceholders remaining+ _ -> Left (before <> "{") : scanPlaceholders (T.drop 1 rest)++-- | Replace each @{name}@ in the text with the value given for that name.+-- Names not given are left in place; values are not scanned again.+substitutePlaceholders :: [(Text, Text)] -> Text -> Text+substitutePlaceholders params = T.concat . map (either id fill) . scanPlaceholders+ where fill name = fromMaybe ("{" <> name <> "}") (lookup name params)++-- | The placeholder names in a template.+placeholders :: Text -> Set Text+placeholders = S.fromList . rights . scanPlaceholders++isNameChar :: Char -> Bool+isNameChar c = isAlphaNum c || c == '_'++msgKey :: Maybe Text -> Text -> Text+msgKey mctx s = maybe s (\c -> c <> "\x04" <> s) mctx++-- * Catalogs++-- | The built-in catalogs, embedded at build time.+builtinCatalogSources :: [(Text, ByteString)]+builtinCatalogSources =+ [ ("de", $(embedFileRelativeBytes "locale/de.po"))+ , ("es", $(embedFileRelativeBytes "locale/es.po"))+ , ("fr", $(embedFileRelativeBytes "locale/fr.po"))+ , ("ga", $(embedFileRelativeBytes "locale/ga.po"))+ , ("haw", $(embedFileRelativeBytes "locale/haw.po"))+ , ("it", $(embedFileRelativeBytes "locale/it.po"))+ , ("ja", $(embedFileRelativeBytes "locale/ja.po"))+ , ("pt-BR", $(embedFileRelativeBytes "locale/pt-BR.po"))+ , ("ru", $(embedFileRelativeBytes "locale/ru.po"))+ , ("uk", $(embedFileRelativeBytes "locale/uk.po"))+ , ("zh-Hans", $(embedFileRelativeBytes "locale/zh-Hans.po"))+ ]++-- | The built-in catalogs, parsed. A catalog that fails to parse is+-- omitted; the unit tests ensure that does not happen in a release.+builtinTranslations :: Map Text Translations+builtinTranslations = M.fromList+ [ (lang, t)+ | (lang, bs) <- builtinCatalogSources+ , Right s <- [TE.decodeUtf8' bs]+ , Right t <- [parsePo ("built-in catalog " ++ T.unpack lang) lang s]+ ]++-- | The languages with a built-in catalog, plus English.+builtinLanguages :: [Text]+builtinLanguages = "en" : M.keys builtinTranslations++-- | The directory where a user can put a translation catalog named+-- LANG.po, to override a built-in one or to add a language:+-- the locale subdirectory of hledger's config directory+-- (~/.config/hledger/locale on unix, %APPDATA%\\hledger\\locale on windows).+translationsOverrideDir :: IO FilePath+translationsOverrideDir = (</> "locale") <$> getXdgDirectory XdgConfig "hledger"++-- | The template that catalogs are made from, embedded at build time.+catalogTemplate :: ByteString+catalogTemplate = $(embedFileRelativeBytes "locale/hledger.pot")++-- | The catalog to start translating a language from, for --write-lang:+-- the language's canonical tag, whether the catalog is a built-in one, and+-- its content. That is the built-in catalog for the language if there is+-- one (found as --lang finds it, so de-AT gives de), otherwise the template,+-- with its header filled in so that hledger can use it straight away.+-- English, or something that is not a language tag, gives an error message.+startingCatalog :: Text -> Either String (Text, Bool, ByteString)+startingCatalog raw = case normalizeLangTag raw of+ Nothing -> Left $ show raw ++ " is not a language tag; try eg de, fr or pt-BR"+ Just "en" -> Left "English is hledger's own language, and has no catalog"+ Just tag -> Right $ fromMaybe (tag, False, TE.encodeUtf8 $ newCatalog tag) $ do+ b <- resolveLang (map fst builtinCatalogSources) [tag]+ (\c -> (b, True, c)) <$> lookup b builtinCatalogSources+ where+ -- the template, with its header filled in as a translator tool would+ newCatalog tag =+ T.replace "# Translation template for hledger.\n"+ ("# hledger's " <> tag <> " translations, made from its translation template.\n"+ <> "# Check the Plural-Forms rule below: see https://hledger.org/TRANSLATING.html\n")+ . T.replace "#, fuzzy\nmsgid \"\"\n" "msgid \"\"\n"+ . T.replace "\"Language: \\n\"" ("\"Language: " <> tag <> "\\n\"")+ . T.replace "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"" ("\"Plural-Forms: " <> pluralFormsFor tag <> "\\n\"")+ $ TE.decodeUtf8With lenientDecode catalogTemplate++-- | The Plural-Forms rule to start a new catalog with: the language's rule+-- if it is in 'commonPluralForms' (looked up by the whole tag, then by the+-- language alone, so zh-Hant gets zh's), otherwise the most common one.+pluralFormsFor :: Text -> Text+pluralFormsFor tag = fromMaybe "nplurals=2; plural=(n != 1);" $+ lookup tag commonPluralForms <|> lookup (T.takeWhile (/= '-') tag) commonPluralForms++-- | The plural rules of languages whose rule is not the most common one,+-- as given in the GNU gettext manual.+commonPluralForms :: [(Text, Text)]+commonPluralForms =+ [ (l, "nplurals=1; plural=0;") | l <- ["id", "ja", "ko", "th", "vi", "zh"] ]+ ++ [ (l, "nplurals=2; plural=(n > 1);") | l <- ["fr", "pt-BR"] ]+ ++ [ (l, "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);")+ | l <- ["be", "bs", "hr", "ru", "sr", "uk"] ]+ ++ [ (l, "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;") | l <- ["cs", "sk"] ]+ ++ [ ("pl", "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);")+ , ("lt", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);")+ , ("lv", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);")+ , ("ro", "nplurals=3; plural=(n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);")+ , ("ga", "nplurals=3; plural=(n==1 ? 0 : n==2 ? 1 : 2);")+ , ("sl", "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);")+ , ("ar", "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);")+ ]++-- | Write the catalog to start translating a language from (see+-- 'startingCatalog') into 'translationsOverrideDir', where --lang will find+-- it, returning its path, tag and whether it is a built-in catalog.+-- If the user has a catalog for that language already, it is left alone+-- and an error message returned.+writeStartingCatalog :: Text -> IO (Either String (FilePath, Text, Bool))+writeStartingCatalog raw = case startingCatalog raw of+ Left e -> return $ Left e+ Right (tag, builtin, content) -> do+ dir <- translationsOverrideDir+ let path = dir </> T.unpack tag <> ".po"+ existing <- lookup tag <$> overrideCatalogFiles+ case existing of+ Just f -> return $ Left $ f ++ " exists already; to start afresh, move it aside first"+ Nothing -> do+ createDirectoryIfMissing True dir+ BS.writeFile path content+ return $ Right (path, tag, builtin)++-- | The largest user catalog we will read.+maxCatalogSize :: Integer+maxCatalogSize = 1024 * 1024++-- | The user's catalog files, by language tag. The tag is taken from the+-- file name and normalized, so DE.po and de.po both serve "de".+overrideCatalogFiles :: IO [(Text, FilePath)]+overrideCatalogFiles = do+ dir <- translationsOverrideDir+ exists <- doesDirectoryExist dir+ files <- if exists then listDirectory dir else return []+ return [ (tag, dir </> f) | f <- sort files, takeExtension f == ".po"+ , Just tag <- [normalizeLangTag (T.pack (dropExtension f))] ]++-- | Read the user's catalog for this language tag, if there is one and it+-- is usable, returning it with its path. Problems are reported as+-- warnings and the catalog ignored; or, for a translation whose+-- placeholders are wrong, just that translation.+readOverrideCatalog :: Text -> IO (Maybe (FilePath, Translations))+readOverrideCatalog lang = do+ files <- overrideCatalogFiles+ case lookup lang files of+ Nothing -> return Nothing+ Just f -> do+ size <- getFileSize f+ if size > maxCatalogSize+ then Nothing <$ warnIO ("ignoring translation catalog " ++ f ++ ": it is larger than 1 MiB")+ else do+ bs <- BS.readFile f+ case TE.decodeUtf8' bs of+ Left _ -> Nothing <$ warnIO ("ignoring translation catalog " ++ f ++ ": it is not valid UTF-8")+ Right t -> case parsePo f lang t of+ Left err -> Nothing <$ warnIO ("ignoring translation catalog " ++ f ++ ":\n" ++ err)+ Right c -> do+ let (c', problems) = withoutPlaceholderMismatches c+ unless (null problems) $ warnIO $+ "translation catalog " ++ f ++ ": ignoring translations whose {placeholders} differ from the English text's:\n"+ ++ intercalate "\n" (map (" " ++) problems)+ return (Just (f, c'))++-- | The language tags for which a catalog exists, built-in or in the+-- user's override directory. Always includes "en".+--+-- Listing the built-in languages parses the built-in catalogs (whichever+-- of them parse are the ones available), once per process. With --debug,+-- reports how long that took.+availableLanguages :: IO [Text]+availableLanguages = do+ t0 <- getCurrentTime+ let nbuiltin = length builtinLanguages - 1+ t1 <- nbuiltin `seq` getCurrentTime+ when (debugLevel >= 1) $+ dbg1MsgIO $ printf "translations: parsed %d built-in catalogs, %.1f ms" nbuiltin (msSince t0 t1)+ overrides <- map fst <$> overrideCatalogFiles+ return $ S.toList $ S.fromList $ builtinLanguages ++ overrides++-- | Load the translations for this language tag (which should be one+-- returned by 'availableLanguages'): the built-in catalog if any, with+-- the user's catalog merged over it if any. With --debug, reports what+-- was loaded, its size, and how long it took.+loadTranslations :: Text -> IO Translations+loadTranslations lang = do+ t0 <- getCurrentTime+ let mbuiltin = M.lookup lang builtinTranslations+ builtin = fromMaybe noTranslations{trLang = lang} mbuiltin+ moverride <- readOverrideCatalog lang+ let trs = maybe builtin (mergeTranslations builtin . snd) moverride+ when (debugLevel >= 1) $ do+ -- Force the merged catalog so that the time is real.+ let entries = M.size (trMessages trs) + M.size (trPlurals trs)+ t1 <- entries `seq` getCurrentTime+ let chars = sum (map T.length (M.keys (trMessages trs) ++ M.elems (trMessages trs)))+ + sum (map T.length (M.keys (trPlurals trs) ++ concat (M.elems (trPlurals trs))))+ let sources = [ "built-in" | isJust mbuiltin ] ++ [ f | Just (f, _) <- [moverride] ]+ dbg1MsgIO $ printf "translations: loaded %s (%s): %d entries, ~%d KB of text, %.1f ms"+ (T.unpack lang) (if null sources then "no catalog" else intercalate ", " sources) entries (chars `div` 1024) (msSince t0 t1)+ return trs++-- | Milliseconds between two times, for debug output.+msSince :: UTCTime -> UTCTime -> Double+msSince t0 t1 = realToFrac (diffUTCTime t1 t0) * 1000++-- | Load the translations for every available language.+loadAllTranslations :: IO (Map Text Translations)+loadAllTranslations = do+ langs <- availableLanguages+ M.fromList <$> mapM (\l -> (,) l <$> loadTranslations l) langs++-- | Merge two catalogs; entries in the second take precedence.+mergeTranslations :: Translations -> Translations -> Translations+mergeTranslations base override = Translations+ { trLang = trLang override+ , trMessages = M.union (trMessages override) (trMessages base)+ , trPlurals = M.union (trPlurals override) (trPlurals base)+ , trPluralForms = trPluralForms override <|> trPluralForms base+ }++-- | Remove the translations whose placeholders do not match their English+-- text's, since using them would drop filled-in values (like a report's+-- dates) or show a placeholder literally. A translation must have exactly+-- the English text's placeholders; a plural form may have only those and+-- {n}. Also returns a description of each translation removed.+withoutPlaceholderMismatches :: Translations -> (Translations, [String])+withoutPlaceholderMismatches t =+ ( t{trMessages = okmsgs, trPlurals = okplurals}+ , map describe (M.toList (badmsgs `M.difference` trPlurals t)) ++ map describePlural (M.toList badplurals) )+ where+ (okplurals, badplurals) = M.partitionWithKey (\k vs -> all (fitsPlural k) vs) (trPlurals t)+ -- A plural entry's first form is also stored as a message; it is judged,+ -- and kept or removed, as part of the plural entry.+ (okmsgs, badmsgs) = M.partitionWithKey okmsg (trMessages t)+ okmsg k v+ | k `M.member` trPlurals t = k `M.member` okplurals+ | otherwise = placeholders v == expected k+ fitsPlural k v = placeholders v `S.isSubsetOf` S.insert "n" (expected k)+ expected = placeholders . keyMsgid+ describe (k, v) =+ show (keyMsgid k) ++ ": the translation has " ++ showPlaceholders (placeholders v)+ ++ ", but the English text has " ++ showPlaceholders (expected k)+ describePlural (k, vs) =+ show (keyMsgid k) ++ ": a plural form has " ++ showPlaceholders (S.unions [placeholders v | v <- vs, not (fitsPlural k v)])+ ++ ", but only these are allowed: " ++ showPlaceholders (S.insert "n" (expected k))+ showPlaceholders s+ | S.null s = "none"+ | otherwise = unwords ["{" ++ T.unpack p ++ "}" | p <- S.toList s]++-- | The msgid part of a catalog key, without any context.+keyMsgid :: Text -> Text+keyMsgid = T.takeWhileEnd (/= '\x04')++-- ** PO parsing++type PoParser = Parsec Void Text++data PoEntry = PoEntry+ { peFlags :: [Text]+ , peCtx :: Maybe Text+ , peId :: Text+ , peIdPlural :: Maybe Text+ , peStr :: Text+ , peStrs :: [(Int, Text)]+ }++-- | Parse a catalog in PO format. The arguments are a name for error+-- messages, the language tag to record, and the file's content.+--+-- Handles what translator tools produce: the header entry, translator and+-- extracted comments, references, flags, previous-msgid comments,+-- obsolete entries, contexts, plural forms, multi-line strings, C escapes,+-- a byte order mark and CRLF line endings. Entries flagged fuzzy are+-- skipped (except that the header's Plural-Forms is still used), and an+-- empty translation counts as untranslated. Duplicate entries and a+-- non-UTF-8 charset are errors.+parsePo :: String -> Text -> Text -> Either String Translations+parsePo name lang input = do+ entries <- first errorBundlePretty $ runParser poEntries name (cleanup input)+ buildTranslations name lang entries+ where+ cleanup = T.replace "\r\n" "\n" . T.dropWhile (== '\xFEFF')++poEntries :: PoParser [PoEntry]+poEntries = do+ space+ done <- atEnd+ if done+ then return []+ else do+ flagss <- many commentLine+ mentry <- optional entryFields+ case mentry of+ Nothing+ | null flagss -> fail "expected a comment line or a msgid"+ | otherwise -> poEntries -- comments with no entry, eg an obsolete (#~) entry+ Just e -> (e{peFlags = concat flagss} :) <$> poEntries++-- | A comment line. Returns the flags if it is a "#," flags line.+commentLine :: PoParser [Text]+commentLine = do+ _ <- char '#'+ flags <- (char ',' *> (map T.strip . T.splitOn "," <$> restOfLine)) <|> ([] <$ restOfLine)+ space+ return flags+ where restOfLine = takeWhileP Nothing (/= '\n')++entryFields :: PoParser PoEntry+entryFields = do+ ctx <- optional (keyword "msgctxt" *> strings)+ mid <- keyword "msgid" *> strings+ mpl <- optional (keyword "msgid_plural" *> strings)+ case mpl of+ Nothing -> do+ s <- keyword "msgstr" *> strings+ return PoEntry{peFlags = [], peCtx = ctx, peId = mid, peIdPlural = Nothing, peStr = s, peStrs = []}+ Just pl -> do+ ss <- some indexedMsgstr+ return PoEntry{peFlags = [], peCtx = ctx, peId = mid, peIdPlural = Just pl, peStr = "", peStrs = ss}++keyword :: Text -> PoParser ()+keyword k = void $ try (string k <* notFollowedBy (satisfy (\c -> isAlphaNum c || c == '_' || c == '[')) <* hspace)++indexedMsgstr :: PoParser (Int, Text)+indexedMsgstr = do+ _ <- try (string "msgstr[")+ n <- L.decimal+ _ <- char ']'+ hspace+ s <- strings+ return (n, s)++-- | One or more quoted strings, possibly on several lines, concatenated.+strings :: PoParser Text+strings = T.concat <$> some (quotedString <* space)++-- Runs of ordinary characters are taken as slices of the input; only+-- escapes are handled a character at a time.+quotedString :: PoParser Text+quotedString = T.concat <$> (char '"' *> manyTill piece (char '"'))+ where+ piece = takeWhile1P Nothing (\c -> c /= '"' && c /= '\\' && c /= '\n')+ <|> (T.singleton <$> (char '\\' *> escape))+ escape = choice+ [ '\n' <$ char 'n'+ , '\t' <$ char 't'+ , '\r' <$ char 'r'+ , '\\' <$ char '\\'+ , '"' <$ char '"'+ , '\a' <$ char 'a'+ , '\b' <$ char 'b'+ , '\f' <$ char 'f'+ , '\v' <$ char 'v'+ , char 'x' *> (fromCode readHex <$> takeWhile1P (Just "hex digit") isHexDigit)+ , fromCode readOct . T.pack <$> count' 1 3 octDigitChar+ , anySingle -- an unknown escape: keep the character+ ]+ fromCode reader s = case reader (T.unpack s) of+ [(n, "")] | n <= 0x10FFFF -> chr n+ _ -> '\xFFFD'++buildTranslations :: String -> Text -> [PoEntry] -> Either String Translations+buildTranslations name lang entries = do+ let (headers, rest) = partition isHeader entries+ headerFields = maybe [] (parseHeader . peStr) (listToMaybe headers)+ case lookup "content-type" headerFields >>= charsetOf of+ Just cs | cs `notElem` ["utf-8", "utf8", "charset"] ->+ Left $ name ++ ": unsupported charset " ++ T.unpack cs ++ " (translation catalogs must be UTF-8)"+ _ -> Right ()+ pf <- case lookup "plural-forms" headerFields of+ Nothing -> Right Nothing+ Just s -> maybe (Left $ name ++ ": could not parse the Plural-Forms header: " ++ T.unpack s)+ (Right . Just) (parsePluralForms s)+ let live = filter (notElem "fuzzy" . peFlags) rest+ dups = M.keys $ M.filter (> 1) $ M.fromListWith (+) [ (entryKey e, 1 :: Int) | e <- live ]+ unless (null dups) $+ Left $ name ++ ": duplicate entries for: " ++ unwords (map (show . T.replace "\x04" "|") dups)+ let msgs = M.fromList [ (entryKey e, s) | e <- live, let s = singularStr e, not (T.null s) ]+ plurals = M.fromList [ (entryKey e, forms) | e <- live, isJust (peIdPlural e)+ , let forms = map snd (sortOn fst (peStrs e)), any (not . T.null) forms ]+ return Translations{trLang = lang, trMessages = msgs, trPlurals = plurals, trPluralForms = pf}+ where+ isHeader e = T.null (peId e) && isNothing (peCtx e) && isNothing (peIdPlural e)+ entryKey e = msgKey (peCtx e) (peId e)+ singularStr e = case peIdPlural e of+ Nothing -> peStr e+ Just _ -> fromMaybe "" (lookup 0 (peStrs e))+ parseHeader s =+ [ (T.toLower (T.strip k), T.strip (T.drop 1 v))+ | l <- T.lines s, let (k, v) = T.breakOn ":" l, not (T.null v) ]+ charsetOf ct = listToMaybe+ [ T.strip (T.drop 8 p) | p <- map (T.toLower . T.strip) (T.splitOn ";" ct), "charset=" `T.isPrefixOf` p ]++-- ** Plural forms++-- | Parse a PO header's Plural-Forms value, eg+-- "nplurals=2; plural=(n != 1);". The plural expression is the C+-- expression subset gettext allows: n, integers, parentheses, !, %,+-- comparisons, &&, ||, and ?:.+parsePluralForms :: Text -> Maybe PluralForms+parsePluralForms s = do+ let fields = [ (T.strip k, T.strip (T.drop 1 v)) | p <- T.splitOn ";" s, let (k, v) = T.breakOn "=" p, not (T.null v) ]+ n <- lookup "nplurals" fields >>= readMaybe . T.unpack+ e <- lookup "plural" fields+ expr <- parseMaybe (space *> pluralExpr <* eof) e+ return PluralForms{pfCount = n, pfRule = \k -> evalPlural k expr}++data PExpr+ = PN+ | PLit Int+ | PNot PExpr+ | PBin Text PExpr PExpr+ | PCond PExpr PExpr PExpr++evalPlural :: Int -> PExpr -> Int+evalPlural n = go+ where+ go PN = n+ go (PLit i) = i+ go (PNot e) = if go e == 0 then 1 else 0+ go (PCond c a b) = if go c /= 0 then go a else go b+ go (PBin op a b) =+ let x = go a+ y = go b+ in case op of+ "%" -> if y == 0 then 0 else x `mod` y+ "<" -> fromBool (x < y)+ "<=" -> fromBool (x <= y)+ ">" -> fromBool (x > y)+ ">=" -> fromBool (x >= y)+ "==" -> fromBool (x == y)+ "!=" -> fromBool (x /= y)+ "&&" -> fromBool (x /= 0 && y /= 0)+ "||" -> fromBool (x /= 0 || y /= 0)+ _ -> 0+ fromBool b = if b then 1 else 0++pluralExpr :: PoParser PExpr+pluralExpr = do+ c <- binaryExpr+ (do _ <- sym "?"+ a <- pluralExpr+ _ <- sym ":"+ b <- pluralExpr+ return (PCond c a b))+ <|> return c+ where+ sym = L.symbol space+ binaryExpr = makeExprParser term table+ table =+ [ [Prefix (PNot <$ L.lexeme space (try (char '!' <* notFollowedBy (char '='))))]+ , [binary "%"]+ , [binary "<=", binary ">=", binary "<", binary ">"]+ , [binary "==", binary "!="]+ , [binary "&&"]+ , [binary "||"]+ ]+ binary op = InfixL (PBin op <$ sym op)+ term = choice+ [ PN <$ L.lexeme space (try (char 'n' <* notFollowedBy alphaNumChar))+ , PLit <$> L.lexeme space L.decimal+ , between (sym "(") (sym ")") pluralExpr+ ]++-- * Language tags++-- | Is this a well-formed language tag, safe to use in a cookie ? Two or three letters, then optional subtags of one to eight+-- letters or digits, separated by hyphens.+isValidLangTag :: Text -> Bool+isValidLangTag t = case T.splitOn "-" t of+ (l : subs) -> T.length l `elem` [2, 3] && T.all isAsciiAlpha l && all okSub subs && T.length t <= 35+ _ -> False+ where+ okSub s = not (T.null s) && T.length s <= 8 && T.all (\c -> isAscii c && isAlphaNum c) s+ isAsciiAlpha c = isAscii c && isAlpha c++-- | Convert a language tag as found in the environment or an HTTP header+-- to canonical form, or Nothing if it does not name a language.+--+-- Handles POSIX locale names (de_DE.UTF-8\@euro becomes de-DE; C, POSIX+-- and an empty value become Nothing), Accept-Language quality suffixes,+-- and letter case (pt-br becomes pt-BR). Chinese region tags map to the+-- script tags zh-Hans and zh-Hant, and Norwegian's no to nb.+normalizeLangTag :: Text -> Maybe Text+normalizeLangTag raw+ | T.null base || isC = Nothing+ | otherwise = do+ let parts = filter (not . T.null) $ T.splitOn "-" $ T.replace "_" "-" base+ tag <- case parts of+ (l : rest) | T.length l `elem` [2, 3] && T.all isAlpha l ->+ Just $ T.intercalate "-" (T.toLower l : modifierSubtag ++ map canonSub rest)+ _ -> Nothing+ let tag' = alias tag+ if isValidLangTag tag' then Just tag' else Nothing+ where+ value = T.strip $ T.takeWhile (/= ';') raw+ (base, suffix) = T.break (\c -> c == '.' || c == '@') value+ modifier = T.drop 1 $ T.dropWhile (/= '@') suffix+ modifierSubtag = case T.toLower modifier of+ "latin" -> ["Latn"]+ "cyrillic" -> ["Cyrl"]+ _ -> []+ isC = T.toLower base `elem` ["c", "posix"]+ canonSub s+ | T.length s == 4 && T.all isAlpha s = T.toTitle s -- script+ | T.length s == 2 && T.all isAlpha s = T.toUpper s -- region+ | otherwise = s+ alias t = case T.toLower t of+ "zh" -> "zh-Hans"+ "zh-cn" -> "zh-Hans"+ "zh-sg" -> "zh-Hans"+ "zh-hans" -> "zh-Hans"+ "zh-tw" -> "zh-Hant"+ "zh-hk" -> "zh-Hant"+ "zh-mo" -> "zh-Hant"+ "zh-hant" -> "zh-Hant"+ "no" -> "nb"+ "no-no" -> "nb"+ _ -> t++-- | The tags to try for a language tag, most specific first:+-- the tag itself, then with subtags dropped from the right.+langTagCandidates :: Text -> [Text]+langTagCandidates t = map (T.intercalate "-") $ reverse $ drop 1 $ inits $ T.splitOn "-" t++-- | The shortest spelling of a language tag that selects it, for showing to+-- users: the tag with subtags dropped from the right, as far as the result+-- still normalizes to the tag. Eg zh-Hans is shown as zh, since zh means+-- zh-Hans; but pt-BR stays pt-BR, since pt is a different language tag.+shortLangTag :: Text -> Text+shortLangTag t = fromMaybe t $ listToMaybe+ [ c | c <- reverse (langTagCandidates t), normalizeLangTag c == Just t ]++-- | Given the available language tags and a list of preferred tags in+-- order of preference (raw, as from the environment or a browser),+-- choose the first available one. Each preference is tried with its+-- subtags dropped from the right before moving on to the next, so that+-- de-CH followed by en chooses de over en when only de is available.+resolveLang :: [Text] -> [Text] -> Maybe Text+resolveLang available prefs = listToMaybe+ [ a+ | p <- mapMaybe normalizeLangTag prefs+ , c <- langTagCandidates p+ , a <- available+ , T.toLower a == T.toLower c+ ]++-- | The languages a user prefers, in order, according to these+-- environment variables, following gettext: the effective locale is+-- LC_ALL, else LC_MESSAGES, else LANG; if that is unset or C/POSIX the+-- result is empty (English) and LANGUAGE is ignored; otherwise the+-- colon-separated LANGUAGE list is consulted first, then the locale.+langPrefsFromEnv :: [(String, String)] -> [Text]+langPrefsFromEnv env = case effective of+ Nothing -> []+ Just loc+ | isNothing (normalizeLangTag loc) -> []+ | otherwise -> mapMaybe normalizeLangTag (languageList ++ [loc])+ where+ get k = case lookup k env of+ Just v | not (null v) -> Just (T.pack v)+ _ -> Nothing+ effective = get "LC_ALL" <|> get "LC_MESSAGES" <|> get "LANG"+ languageList = maybe [] (T.splitOn ":") (get "LANGUAGE")++-- * Tests++-- i18n-extract: off++tests_I18n :: TestTree+tests_I18n = testGroup "I18n" [+ testCase "substitutePlaceholders" $ do+ substitutePlaceholders [("a", "1")] "x {a} y" @?= "x 1 y"+ substitutePlaceholders [("a", "{b}"), ("b", "2")] "{a}{b}" @?= "{b}2"+ substitutePlaceholders [] "{unknown} { }" @?= "{unknown} { }"+ substitutePlaceholders [("a", "1")] "{a}{a}" @?= "11"++ ,testCase "placeholders" $ do+ placeholders "a {x} {y_1} {bad name} { {z}" @?= S.fromList ["x", "y_1", "z"]+ placeholders "" @?= S.empty++ ,testCase "parsePo" $ do+ t <- either assertFailure return $ parsePo "sample" "de" samplePo+ trLang t @?= "de"+ tr t "Balance Sheet" @?= "Bilanz"+ tr t "Untranslated" @?= "Untranslated"+ tr t "Empty" @?= "Empty"+ tr t "Fuzzy" @?= "Fuzzy"+ tr t "Obsolete" @?= "Obsolete"+ trc t "column heading" "Total" @?= "Summe"+ tr t "Total" @?= "Total"+ tr t "Multi" @?= "line one\nline two \"quoted\" \\ \252 A"+ trn t 1 "{n} day" "{n} days" @?= "1 Tag"+ trn t 2 "{n} day" "{n} days" @?= "2 Tage"+ trn t 0 "{n} day" "{n} days" @?= "0 Tage"+ tr t "{n} day" @?= "{n} Tag"+ trf t "Balance changes in {period}:" [("period", "2024")] @?= "Saldo\228nderungen in 2024:"+ maybe (-1) pfCount (trPluralForms t) @?= 2++ ,testCase "parsePo errors" $ do+ let bad = assertBool "expected a parse failure" . isLeft . parsePo "t" "de"+ bad "msgid \"a\"\nmsgstr \"b\"\nmsgid \"a\"\nmsgstr \"c\"\n"+ bad "garbage\n"+ bad "msgid \"a\"\nmsgstr \"b\n"+ bad "msgid \"\"\nmsgstr \"Content-Type: text/plain; charset=ISO-8859-1\\n\"\n"+ bad "msgid \"\"\nmsgstr \"Plural-Forms: nplurals=2; plural=(n +);\\n\"\n"++ ,testCase "parsePo tolerates" $ do+ let ok = assertBool "expected a successful parse" . not . isLeft . parsePo "t" "de"+ ok ""+ ok "# just a comment\n"+ ok "\xFEFFmsgid \"a\"\r\nmsgstr \"b\"\r\n"+ ok "#~ msgid \"old\"\n#~ msgstr \"alt\"\n"+ ok "msgid \"\"\nmsgstr \"Content-Type: text/plain; charset=CHARSET\\n\"\n"++ ,testCase "plural rules" $ do+ let rule s = maybe (const (-1)) pfRule (parsePluralForms s)+ en = rule "nplurals=2; plural=(n != 1);"+ fr = rule "nplurals=2; plural=(n > 1);"+ ru = rule "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"+ zh = rule "nplurals=1; plural=0;"+ ar = rule "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);"+ pl = rule "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"+ map en [0, 1, 2] @?= [1, 0, 1]+ map fr [0, 1, 2] @?= [0, 0, 1]+ map ru [1, 2, 5, 11, 21, 22, 25] @?= [0, 1, 2, 2, 0, 1, 2]+ map zh [0, 1, 5] @?= [0, 0, 0]+ map ar [0, 1, 2, 3, 11, 100] @?= [0, 1, 2, 3, 4, 5]+ map pl [1, 2, 5, 12, 22] @?= [0, 1, 2, 2, 1]+ maybe 0 pfCount (parsePluralForms "nplurals=6; plural=0;") @?= 6++ ,testCase "normalizeLangTag" $ do+ normalizeLangTag "de_DE.UTF-8@euro" @?= Just "de-DE"+ normalizeLangTag "de" @?= Just "de"+ normalizeLangTag "C" @?= Nothing+ normalizeLangTag "POSIX" @?= Nothing+ normalizeLangTag "C.UTF-8" @?= Nothing+ normalizeLangTag "" @?= Nothing+ normalizeLangTag "zh_CN" @?= Just "zh-Hans"+ normalizeLangTag "zh-TW" @?= Just "zh-Hant"+ normalizeLangTag "zh-hant-tw" @?= Just "zh-Hant-TW"+ normalizeLangTag "sr_RS@latin" @?= Just "sr-Latn-RS"+ normalizeLangTag "pt-br" @?= Just "pt-BR"+ normalizeLangTag "no_NO" @?= Just "nb"+ normalizeLangTag "en-US;q=0.8" @?= Just "en-US"+ normalizeLangTag "ast" @?= Just "ast"+ normalizeLangTag "../x" @?= Nothing+ normalizeLangTag "de/../x" @?= Nothing++ ,testCase "isValidLangTag" $ do+ isValidLangTag "de" @?= True+ isValidLangTag "zh-Hant-TW" @?= True+ isValidLangTag "d" @?= False+ isValidLangTag "de-" @?= False+ isValidLangTag "../de" @?= False+ isValidLangTag "de.po" @?= False++ ,testCase "langTagCandidates" $+ langTagCandidates "zh-Hant-TW" @?= ["zh-Hant-TW", "zh-Hant", "zh"]++ ,testCase "shortLangTag" $+ map shortLangTag ["de", "zh-Hans", "zh-Hant", "pt-BR", "nb", "sr-Latn-RS"]+ @?= ["de", "zh", "zh-Hant", "pt-BR", "nb", "sr-Latn-RS"]++ ,testCase "resolveLang" $ do+ resolveLang ["en", "de"] ["de-CH", "en", "de"] @?= Just "de"+ resolveLang ["en", "de"] ["fr", "en-GB"] @?= Just "en"+ resolveLang ["en", "de"] ["fr"] @?= Nothing+ resolveLang ["en", "de"] ["../etc"] @?= Nothing+ resolveLang ["en", "de"] ["DE"] @?= Just "de"+ resolveLang ["en", "zh-Hans"] ["zh_CN"] @?= Just "zh-Hans"++ ,testCase "langPrefsFromEnv" $ do+ langPrefsFromEnv [("LANG", "de_DE.UTF-8")] @?= ["de-DE"]+ langPrefsFromEnv [("LC_ALL", "C"), ("LANGUAGE", "de"), ("LANG", "de_DE.UTF-8")] @?= []+ langPrefsFromEnv [("LANGUAGE", "fr:de"), ("LANG", "en_US.UTF-8")] @?= ["fr", "de", "en-US"]+ langPrefsFromEnv [("LC_MESSAGES", "de_AT"), ("LANG", "C")] @?= ["de-AT"]+ langPrefsFromEnv [("LC_ALL", ""), ("LANG", "de")] @?= ["de"]+ langPrefsFromEnv [] @?= []++ ,testCase "withoutPlaceholderMismatches" $ do+ t <- either assertFailure return $ parsePo "t" "de" $ T.unlines+ [ "msgid \"In {account}\"", "msgstr \"In {account}\""+ , "msgid \"{report} {dates}\"", "msgstr \"{bogus} {report}\""+ , "msgid \"Totals\"", "msgstr \"Summen {x}\""+ , "msgid \"{n} day\"", "msgid_plural \"{n} days\"", "msgstr[0] \"{n} Tag\"", "msgstr[1] \"{n} Tage\""+ , "msgid \"one {x}\"", "msgid_plural \"{n} {x}s\"", "msgstr[0] \"ein {y}\"", "msgstr[1] \"{n} {x}\""+ ]+ let (t', problems) = withoutPlaceholderMismatches t+ tr t' "In {account}" @?= "In {account}"+ tr t' "{report} {dates}" @?= "{report} {dates}"+ tr t' "Totals" @?= "Totals"+ trn t' 2 "{n} day" "{n} days" @?= "2 Tage"+ trn t' 2 "one {x}" "{n} {x}s" @?= "2 {x}s"+ tr t' "one {x}" @?= "one {x}"+ problems @?=+ [ "\"Totals\": the translation has {x}, but the English text has none"+ , "\"{report} {dates}\": the translation has {bogus} {report}, but the English text has {dates} {report}"+ , "\"one {x}\": a plural form has {y}, but only these are allowed: {n} {x}"+ ]++ ,testCase "built-in catalogs" $+ mapM_ checkBuiltin builtinCatalogSources++ ,testCase "startingCatalog" $ do+ let tagOf = fmap (\(t, b, _) -> (t, b)) . startingCatalog+ tagOf "de-AT" @?= Right ("de", True)+ tagOf "eo_XX" @?= Right ("eo-XX", False)+ assertBool "en" $ isLeft $ startingCatalog "en"+ assertBool "not a tag" $ isLeft $ startingCatalog "x"+ -- a new language's catalog, made from the template, is usable as it is+ case startingCatalog "eo" of+ Right (_, _, bs) -> do+ t <- either assertFailure return $ parsePo "eo" "eo" $ TE.decodeUtf8With lenientDecode bs+ assertBool "plural rule" $ isJust $ trPluralForms t+ Left e -> assertFailure e+ -- with the language's plural rule, if known+ case startingCatalog "uk-UA" of+ Right (_, _, bs) -> fmap (fmap pfCount . trPluralForms) (parsePo "t" "uk-UA" $ TE.decodeUtf8With lenientDecode bs) @?= Right (Just 3)+ Left e -> assertFailure e+ pluralFormsFor "zh-Hant" @?= pluralFormsFor "ja"+ assertBool "pt-BR differs from pt" $ pluralFormsFor "pt-BR" /= pluralFormsFor "pt"+ ,testCase "commonPluralForms" $+ mapM_ (\(l, r) -> case parsePluralForms r of+ Nothing -> assertFailure $ T.unpack l ++ ": could not parse " ++ T.unpack r+ Just pf -> assertBool (T.unpack l ++ ": a form number out of range") $+ all (\n -> let i = pfRule pf n in i >= 0 && i < pfCount pf) [0..1000])+ commonPluralForms+ ]+ where+ checkBuiltin (lang, bs) = do+ -- --lang values are normalized before lookup, so a tag that is not can never be selected+ assertEqual ("built-in catalog tag " ++ show lang ++ " is not normalized") (Just lang) (normalizeLangTag lang)+ s <- either (\e -> assertFailure $ T.unpack lang ++ ": not UTF-8: " ++ show e) return $ TE.decodeUtf8' bs+ t <- either assertFailure return $ parsePo (T.unpack lang) lang s+ assertEqual (T.unpack lang ++ " translations with wrong placeholders") [] (snd $ withoutPlaceholderMismatches t)++samplePo :: Text+samplePo = T.unlines+ [ "# German translations for the tests."+ , "#, fuzzy"+ , "msgid \"\""+ , "msgstr \"\""+ , "\"Project-Id-Version: hledger\\n\""+ , "\"Language: de\\n\""+ , "\"Content-Type: text/plain; charset=UTF-8\\n\""+ , "\"Plural-Forms: nplurals=2; plural=(n != 1);\\n\""+ , ""+ , "#. Report title."+ , "#: hledger/Hledger/Cli/Commands/Balancesheet.hs:23"+ , "#, python-brace-format"+ , "msgid \"Balance Sheet\""+ , "msgstr \"Bilanz\""+ , ""+ , "msgid \"Untranslated\""+ , "msgstr \"\""+ , ""+ , "msgid \"Empty\""+ , "msgstr \"\""+ , ""+ , "#, fuzzy, python-brace-format"+ , "#| msgid \"Fuzy\""+ , "msgid \"Fuzzy\""+ , "msgstr \"Unscharf\""+ , ""+ , "msgctxt \"column heading\""+ , "msgid \"Total\""+ , "msgstr \"Summe\""+ , ""+ , "msgid \"Multi\""+ , "msgstr \"\""+ , " \"line one\\n\""+ , " \"line two \\\"quoted\\\" \\\\ \\374 \\x41\""+ , ""+ , "msgid \"{n} day\""+ , "msgid_plural \"{n} days\""+ , "msgstr[0] \"{n} Tag\""+ , "msgstr[1] \"{n} Tage\""+ , ""+ , "msgid \"Balance changes in {period}:\""+ , "msgstr \"Saldo\228nderungen in {period}:\""+ , ""+ , "#~ msgid \"Obsolete\""+ , "#~ msgstr \"Veraltet\""+ ]
+ Hledger/Utils/IO.hs view
@@ -0,0 +1,1152 @@+{- | +General and hledger-specific input/output-related helpers for+pretty-printing haskell values, error reporting, time, files, command line parsing,+terminals, pager output, ANSI colour/styles, etc.+-}++{-# LANGUAGE ImplicitParams #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiWayIf #-}++module Hledger.Utils.IO (++ -- * Pretty showing/printing+ pshow,+ pshow',+ pprint,+ pprint',++ -- * Errors+ error',+ usageError,+ warn,+ warnIO,+ setWarningHandler,+ ansiFormatError,+ ansiFormatWarning,+ printError,+ exitWithErrorMessage,+ handleExit,++ -- * Time+ getCurrentLocalTime,+ getCurrentZonedTime,++ -- * Files+ dataDirName,+ rulesDirName,+ getHomeSafe,+ embedFileRelative,+ embedFileRelativeBytes,+ expandHomePath,+ expandPath,+ expandGlob,+ expandPathOrGlob,+ sortByModTime,+ openFileOrStdin,+ withFileOrStdout,+ ensureFilesystemCanAppend,+ readFileOrStdinPortably,+ readFileOrStdinPortably',+ readFileStrictly,+ readFilePortably,+ hGetContentsPortably,+ -- hereFileRelative,+ textToHandle,++ -- * Command line parsing+ progArgs,+ getFlag,+ getOpt,+ parseYN,+ parseYNA,+ YNA(..),+ -- hasOutputFile,+ -- outputFileOption,++ -- * Terminal size+ getTerminalHeightWidth,+ getTerminalHeight,+ getTerminalWidth,+ insideEmacsNotVterm,++ -- * Pager output+ findPager,+ runPager,+ lessVarValue,+ lessIsWorking,++ -- * ANSI colour/styles++ -- ** hledger-specific++ colorOption,+ useColorOnStdout,+ useColorOnStderr,+ useColorOnStdoutUnsafe,+ useColorOnStderrUnsafe,+ supportsTrueColor,+ supportsTrueColorUnsafe,+ bold',+ faint',+ black',+ red',+ green',+ yellow',+ blue',+ magenta',+ cyan',+ white',+ brightBlack',+ brightRed',+ brightGreen',+ brightYellow',+ brightBlue',+ brightMagenta',+ brightCyan',+ brightWhite',+ rgb',+ sgrresetall,+ accent,+ gradientStr,+ titleLine,+ titleAndVersionLine,++ -- ** Generic++ color,+ bgColor,+ colorB,+ bgColorB,+ -- XXX Types used with color/bgColor/colorB/bgColorB,+ -- not re-exported because clashing with UIUtils:+ -- Color(..),+ -- ColorIntensity(..),++ terminalIsLight,+ terminalLightness,+ terminalFgColor,+ terminalBgColor,++ )+where++import Control.Concurrent (forkIO)+import Control.Exception+import Control.Monad (when, forM, guard, void)+import Data.Char (toLower, isSpace)+import Data.ByteString qualified as BS+import Data.Colour.RGBSpace (RGB(RGB))+import Data.Colour.RGBSpace.HSL (lightness)+import Data.Colour.SRGB (sRGB)+import Data.Encoding (DynEncoding)+import Data.FileEmbed (makeRelativeToProject, embedFile, embedStringFile)+import Data.Functor ((<&>))+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.List hiding (uncons)+import Data.Maybe (isJust, catMaybes)+import Data.Text qualified as T+import Data.Text.Encoding.Error (UnicodeException)+import Data.Text.IO qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Time.Clock (getCurrentTime)+import Data.Time.LocalTime (LocalTime, ZonedTime, getCurrentTimeZone, utcToLocalTime, utcToZonedTime)+import Data.Word (Word16)+import Debug.Trace+import Foreign.C.Error (Errno(..), ePIPE)+import GHC.IO.Encoding (getLocaleEncoding, textEncodingName)+import GHC.IO.Exception (IOException(..), IOErrorType (ResourceVanished))+import Language.Haskell.TH.Syntax (Q, Exp)+import Safe (headMay, maximumDef)+import System.Console.ANSI (Color(..),ColorIntensity(..), ConsoleLayer(..), SGR(..), hSupportsANSIColor, setSGRCode, getLayerColor, ConsoleIntensity (..), xterm6LevelRGB)+import System.Console.Terminal.Size (Window (Window), size)+import System.Directory (getHomeDirectory, getModificationTime, findExecutable)+import System.Environment (getArgs, getEnvironment, lookupEnv, getProgName)+import System.Exit (ExitCode(ExitSuccess), exitFailure)+import System.FilePath (isRelative, (</>), takeBaseName)+import "Glob" System.FilePath.Glob (glob)+import System.Info (os)+import System.IO (Handle, IOMode (..), hClose, hGetEncoding, hIsTerminalDevice, hPutStr, hPutStrLn, hSetNewlineMode, hSetEncoding, openFile, stderr, stdin, stdout, universalNewlineMode, utf8_bom, utf8, withFile)+import System.IO.Encoding qualified as Enc+import System.IO.Temp (withTempFile)+import System.IO.Unsafe (unsafePerformIO)+import System.Process (CreateProcess(..), StdStream(CreatePipe), createPipe, proc, readCreateProcessWithExitCode, shell, waitForProcess, withCreateProcess)+import System.Timeout (timeout)+import Text.Pretty.Simple (CheckColorTty(..), OutputOptions(..), defaultOutputOptionsDarkBg, defaultOutputOptionsNoColor, pShowOpt, pPrintOpt)++import Hledger.Utils.Text (WideBuilder(WideBuilder))+import Control.Monad.IO.Class (MonadIO, liftIO)+++-- Pretty showing/printing+-- using pretty-simple++-- https://hackage.haskell.org/package/pretty-simple/docs/Text-Pretty-Simple.html#t:OutputOptions++-- | pretty-simple options with colour enabled if allowed.+prettyopts =+ (if useColorOnStderrUnsafe then defaultOutputOptionsDarkBg else defaultOutputOptionsNoColor)+ { outputOptionsIndentAmount = 2+ -- , outputOptionsCompact = True -- fills lines, but does not respect page width (https://github.com/cdepillabout/pretty-simple/issues/126)+ -- , outputOptionsPageWidth = fromMaybe 80 $ unsafePerformIO getTerminalWidth+ }++-- | pretty-simple options with colour disabled.+prettyoptsNoColor =+ defaultOutputOptionsNoColor+ { outputOptionsIndentAmount=2+ }++-- | Pretty show. An easier alias for pretty-simple's pShow.+-- This will probably show in colour if useColorOnStderrUnsafe is true.+pshow :: Show a => a -> String+pshow = TL.unpack . pShowOpt prettyopts++-- | Monochrome version of pshow. This will never show in colour.+pshow' :: Show a => a -> String+pshow' = TL.unpack . pShowOpt prettyoptsNoColor++-- | Pretty print a showable value. An easier alias for pretty-simple's pPrint.+-- This will print in colour if useColorOnStderrUnsafe is true.+pprint :: Show a => a -> IO ()+pprint = pPrintOpt (if useColorOnStderrUnsafe then CheckColorTty else NoCheckColorTty) prettyopts++-- | Monochrome version of pprint. This will never print in colour.+pprint' :: Show a => a -> IO ()+pprint' = pPrintOpt NoCheckColorTty prettyoptsNoColor++-- "Avoid using pshow, pprint, dbg* in the code below to prevent infinite loops." (?)++++-- Errors++-- | Call errorWithoutStackTrace, prepending a "Error:" label.+error' :: String -> a+error' = errorWithoutStackTrace . ("Error: "<>)++-- | Like error', but add a hint about using -h+-- (on its own line, if the message has several lines).+usageError :: String -> a+usageError msg = error' $ msg' ++ sep ++ "(use -h to see usage)"+ where+ msg' = dropWhileEnd (== '\n') msg+ sep = if '\n' `elem` msg' then "\n" else " "++-- | Apply standard ANSI SGR formatting (red, bold) suitable for console error text.+ansiFormatError :: String -> String+ansiFormatError = (<> sgrresetall) . ((sgrbrightred <> sgrbold) <>)++-- | Show a warning message on stderr before returning the given value.+-- Like trace, but prepends a "Warning:" label, and does some ANSI styling of the first line when allowed (using unsafe IO).+-- Currently we use this very sparingly in hledger; we prefer to either quietly work, or loudly raise an error.+-- Varying output can make scripting harder. But on stderr, it shouldn't cause much hassle.+warn :: String -> a -> a+warn = trace . formatWarning++-- | The action warnIO uses to emit a warning message:+-- by default, print it to stderr with a "Warning:" prefix and ANSI styling when supported.+{-# NOINLINE warningHandler #-}+warningHandler :: IORef (String -> IO ())+warningHandler = unsafePerformIO $ newIORef $ traceIO . formatWarning++-- | Replace the action warnIO uses to emit warning messages (which receives+-- the message with no "Warning:" prefix or styling). Eg TUI apps can collect+-- warnings for in-app display, instead of disrupting the terminal with stderr output.+setWarningHandler :: (String -> IO ()) -> IO ()+setWarningHandler = writeIORef warningHandler++-- | Like warn, but take extra care to sequence properly in IO.+-- Emits the warning with the current warning handler (see setWarningHandler).+warnIO :: MonadIO m => String -> m ()+warnIO msg = liftIO $ readIORef warningHandler >>= ($ msg)++formatWarning =+ (if useColorOnStderrUnsafe then modifyFirstLine ansiFormatWarning else id) .+ ("Warning: " <>)++-- | Apply standard ANSI SGR formatting (yellow, bold) suitable for console warning text.+ansiFormatWarning :: String -> String+ansiFormatWarning = (<> sgrresetall) . ((sgrbrightyellow <> sgrbold) <>)++-- Transform a string's first line.+-- Note, this won't add a trailing newline if there isn't one,+-- and it will remove one if there is one or more.+modifyFirstLine :: (String -> String) -> String -> String+modifyFirstLine f s = intercalate "\n" $ map f l <> ls where (l,ls) = splitAt 1 $ lines s -- total++-- | Print an error message to stderr, with a consistent "programname: " prefix,+-- and applying ANSI styling (bold bright red) to the first line if that is supported and allowed.+printError :: String -> IO ()+printError msg = do+ progname <- getProgName+ usecolor <- useColorOnStderr+ let+ style = if usecolor then modifyFirstLine ansiFormatError else id+ prefix =+ progname+ <> ": "+ -- error' prepends an "Error: " prefix. But that seems to have been removed when I catch the ErrorCall exception - unless I'm running in GHCI.+ -- Is it possible something in GHC or base is removing it ?+ -- Use a stupid heuristic for now: add it again unless already there.+ <> (if "Error:" `isPrefixOf` msg then "" else "Error: ")+ hPutStrLn stderr $ style $ prefix <> msg++-- | Print an error message with printError,+-- then exit the program with a non-zero exit code.+exitWithErrorMessage :: String -> IO ()+exitWithErrorMessage msg = printError msg >> exitFailure++-- | This wraps a program's main routine so as to display more consistent,+-- useful, and GHC-version-independent error output when the program exits+-- because of certain common exceptions. It+--+-- 1. disables SIGPIPE errors, which are usually harmless,+-- caused when our output is truncated in a piped command.+--+-- 2. catches these common exceptions:+--+-- - UnicodeException, caused eg by text decoding errors in pure code+--+-- - IOException, caused by I/O errors, including text decoding errors during I/O+--+-- - ErrorCall - @error@ / @errorWithoutStackTrace@ calls+--+-- 3. compensates for GHC output bugs:+--+-- - removes the trailing newlines added by some GHC 9.10.* versions+--+-- - removes "uncaught exception" output added by some GHC 9.12.* versions+--+-- - ensures a consistent "PROGNAME: " prefix+--+-- 4. applies bold bright red ANSI styling to the first line of error output,+-- if that is supported and allowed+--+-- 5. for unicode exceptions and I/O exceptions which look like they were+-- unicode-related, it adds a message (in english) explaining the problem and what to do.+--+-- Some exceptions this does not catch are ExitCode (exitSuccess/exitFailure/exitWith)+-- and UserInterrupt (control-C).+--+handleExit :: IO () -> IO ()+handleExit = flip catches [+ -- Handler (\(e::SomeException) -> error' $ pshow e), -- debug+ Handler (\(e::UnicodeException) -> exitUnicode e)+ ,Handler (\(e::IOException) -> if+ | isUnicodeError e -> exitUnicode e+ | otherwise -> exitOther e)+ ,Handler (\(e::ErrorCall) -> exitOther e)+ ] . ignoreSigPipe++ where+ -- | Ignore SIGPIPE errors.+ -- This is copied from System.Process.Internals in process 1.6.20.0+,+ -- since that version of process comes only with ghc 9.10.2+.+ ignoreSigPipe :: IO () -> IO ()+ ignoreSigPipe = handle $ \e -> case e of+ IOError { ioe_type = ResourceVanished+ , ioe_errno = Just ioe }+ | Errno ioe == ePIPE -> return ()+ _ -> throwIO e++ -- Many decoding failures do not produce a UnicodeException, unfortunately.+ -- So this fragile hack detects them from the error message.+ -- But there are many variant wordings and they probably change over time.+ -- It's not ideal.+ isUnicodeError :: Exception e => e -> Bool+ isUnicodeError ex =+ let msg = map toLower (show ex) in any (`isInfixOf` msg) [+ "illegal byte sequence"+ , "invalid byte sequence"+ , "cannot decode byte sequence"+ , "invalid character"+ , "invalid or incomplete multibyte"+ , "mkTextEncoding: invalid argument"+ ]++ exitUnicode :: Exception e => e -> IO ()+ exitUnicode ex = do+ enc <- getSystemEncoding+ let+ noencoding = map toLower enc == "ascii"+ msg = unlines $ [+ rstrip $ show ex+ , "Some text could not be decoded with the system's text encoding, " <> enc+ , "(or, the text encoding specified by CSV rules)."+ ] +++ if noencoding+ then [+ "Please configure a system locale which can decode this text."+ ]+ else [+ "Please either convert the text to this encoding,"+ , "or configure a system locale which can decode this text."+ ]+ exitWithErrorMessage msg++ exitOther :: Exception e => e -> IO ()+ exitOther = exitWithErrorMessage . rstrip . show++ rstrip = reverse . dropWhile isSpace . reverse++-- I18n++-- encoding has a similar getSystemEncoding :: IO (Maybe DynEncoding)+-- but it returns Nothing on Windows or if there's an error.++-- | Get the name of the text encoding used by the current locale, using GHC's API.+getSystemEncoding :: IO String+getSystemEncoding = do+ localeEncoding <- getLocaleEncoding+ return $ textEncodingName localeEncoding++-- -- | Get the name of the text encoding currently configured for stdout, using GHC's API.+-- getStdoutEncoding :: IO (Maybe String)+-- getStdoutEncoding = do+-- mEncoding <- hGetEncoding stdout+-- return $ fmap textEncodingName mEncoding++-- Time++getCurrentLocalTime :: IO LocalTime+getCurrentLocalTime = do+ t <- getCurrentTime+ tz <- getCurrentTimeZone+ return $ utcToLocalTime tz t++getCurrentZonedTime :: IO ZonedTime+getCurrentZonedTime = do+ t <- getCurrentTime+ tz <- getCurrentTimeZone+ return $ utcToZonedTime tz t++++-- Files++-- | Like getHomeDirectory, but in case of IO error (home directory not found, not understood, etc.), returns "".+getHomeSafe :: IO (Maybe FilePath)+getHomeSafe = fmap Just getHomeDirectory `catch` (\(_ :: IOException) -> return Nothing)++-- | Expand a single tilde (representing home directory) at the start of a file path.+-- ~username is not supported. This can raise an IO error.+expandHomePath :: FilePath -> IO FilePath+expandHomePath = \case+ "~" -> getHomeDirectory+ ('~':'/':p) -> (</> p) <$> getHomeDirectory+ ('~':'\\':p) -> (</> p) <$> getHomeDirectory+ ('~':_) -> ioError $ userError "~USERNAME in paths is not supported"+ p -> return p++-- | Given a current directory, convert a possibly relative, possibly tilde-prefixed+-- file path to an absolute one.+-- ~username is not supported.+-- If the file path is "-", it is left as-is.+-- This can an raise an IO error.+expandPath :: FilePath -> FilePath -> IO FilePath -- general type sig for use in reader parsers+expandPath _ "-" = return "-"+expandPath curdir p = (if isRelative p then (curdir </>) else id) <$> expandHomePath p -- PARTIAL:++-- | The name of the data directory used by hledger commands and rules that+-- read or write CSV files (located next to the main journal file).+-- This is where the get command saves downloaded transactions data,+-- where the CSV source rule looks for input files,+-- and where the CSV archive rule saves imported files.+dataDirName :: FilePath+dataDirName = "data"++-- | The name of the rules directory used by `hledger import`+-- (located next to the main journal file).+-- This is where import looks for .rules files when invoked with no arguments.+rulesDirName :: FilePath+rulesDirName = "rules"++-- | Like @expandPath@, but treats the expanded path as a glob, and returns+-- zero or more matched absolute file paths, alphabetically sorted.+-- Can raise an error.+-- For a more elaborate glob expander, see 'findMatchedFiles' (used by the include directive).+expandGlob :: FilePath -> FilePath -> IO [FilePath]+expandGlob curdir p = expandPath curdir p >>= glob <&> sort -- PARTIAL:++-- | Like expandPath, but if the path contains glob metacharacters (* ? [ {),+-- treats it as a glob pattern and expands it, returning the first match.+-- Raises an error if the glob pattern matches no files.+-- If the path contains no glob metacharacters, just expands ~ and returns the path,+-- even if the file doesn't exist yet.+-- This is useful for options like -f and LEDGER_FILE that should:+-- - accept non-existent files (for commands like add/import that create them)+-- - expand glob patterns and error if they don't match anything+expandPathOrGlob :: FilePath -> FilePath -> IO FilePath+expandPathOrGlob curdir p = do+ let hasGlobChars = any (`elem` p) ("*?[{" :: [Char])+ if hasGlobChars+ then do+ matches <- expandGlob curdir p `catch` (\(_::IOException) -> return [])+ case headMay matches of+ Just f -> return f+ Nothing -> error' $ "glob pattern \"" <> p <> "\" matched no files"+ else+ expandPath curdir p++-- | Given a list of existing file paths, sort them by modification time (from oldest to newest).+sortByModTime :: [FilePath] -> IO [FilePath]+sortByModTime fs = do+ ftimes <- forM fs $ \f -> do {t <- getModificationTime f; return (t,f)}+ return $ map snd $ sort ftimes++-- | Like readFilePortably, but read all of the file before proceeding.+readFileStrictly :: FilePath -> IO T.Text+readFileStrictly f = readFilePortably f >>= \t -> evaluate (T.length t) >> return t++-- | Read text from a file,+-- converting any \r\n line endings to \n,,+-- using the system locale's text encoding,+-- ignoring any utf8 BOM prefix (as seen in paypal's 2018 CSV, eg) if that encoding is utf8.+readFilePortably :: FilePath -> IO T.Text+readFilePortably f = openFile f ReadMode >>= hGetContentsPortably Nothing++-- | Like readFilePortably, but read from standard input if the path is "-".+readFileOrStdinPortably :: String -> IO T.Text+readFileOrStdinPortably = readFileOrStdinPortably' Nothing++-- | Like readFileOrStdinPortably, but take an optional converter.+readFileOrStdinPortably' :: Maybe DynEncoding -> String -> IO T.Text+readFileOrStdinPortably' c f = openFileOrStdin f >>= hGetContentsPortably c++-- | Open a file for reading, using the standard System.IO.openFile.+-- This opens the handle in text mode, using the initial system locale's text encoding.+openFileOrStdin :: String -> IO Handle+openFileOrStdin "-" = return stdin+openFileOrStdin f' = openFile f' ReadMode++-- | Run an action with a handle for writing, opening the given file path in+-- the given mode, or returning 'stdout' if the path is "-". When opening a+-- real file, the handle is closed at the end (like 'withFile'); when using+-- stdout, it is left open for the rest of the program.+withFileOrStdout :: FilePath -> IOMode -> (Handle -> IO r) -> IO r+withFileOrStdout "-" _ action = action stdout+withFileOrStdout f mode action = withFile f mode action++-- | Verify that the filesystem at 'dir' honors O_APPEND, by doing a+-- quick test with a dummy file there (.hledger-append-test*).+-- Returns True if writes opened in 'AppendMode' actually land at end-of-file,+-- False if they don't.+-- This is needed because some filesystems (FAT/exFAT, Android shared-storage+-- and some FUSE mounts) silently drop O_APPEND, so 'appendFile' actually+-- overwrites the file, potentially causing severe data loss (#2577).+ensureFilesystemCanAppend :: FilePath -> IO Bool+ensureFilesystemCanAppend dir =+ withTempFile dir ".hledger-append-test-" $ \path h -> do+ let chunk1 = "can this filesystem\n"+ chunk2 = "append ?\n"+ expected = chunk1 <> chunk2+ BS.hPut h chunk1+ hClose h+ withFile path AppendMode $ \h2 -> BS.hPut h2 chunk2+ actual <- BS.readFile path+ return (actual == expected)++-- | Read text from a handle, perhaps using a specified encoding from the encoding package.+-- Or if no encoding is specified, using the handle's current encoding,+-- changing it to UTF-8BOM if it was UTF-8, to ignore any Byte Order Mark at the start.+-- Also it converts Windows line endings to newlines.+-- If decoding fails, this throws an IOException (or possibly a UnicodeException or something else from the encoding package).+hGetContentsPortably :: Maybe DynEncoding -> Handle -> IO T.Text+hGetContentsPortably Nothing h = do+ hSetNewlineMode h universalNewlineMode+ menc <- hGetEncoding h+ when (fmap show menc == Just "UTF-8") $ hSetEncoding h utf8_bom+ T.hGetContents h+hGetContentsPortably (Just e) h =+ -- convert newlines manually, because Enc.hGetContents uses bytestring's hGetContents+ T.replace "\r\n" "\n" . T.pack <$> let ?enc = e in Enc.hGetContents h++-- | Create a handle from which the given text can be read. Its encoding will be UTF-8.+textToHandle :: T.Text -> IO Handle+textToHandle t = do+ (r, w) <- createPipe+ hSetEncoding r utf8+ hSetEncoding w utf8+ -- use a separate thread so that we don't deadlock if we can't write all of the text at once+ forkIO $ T.hPutStr w t >> hClose w+ return r++-- | Like embedFile, but takes a path relative to the package directory.+embedFileRelative :: FilePath -> Q Exp+embedFileRelative f = makeRelativeToProject f >>= embedStringFile++-- | Like embedFileRelative, but embeds the file's raw bytes as a ByteString,+-- so that its encoding does not depend on the build machine's locale.+embedFileRelativeBytes :: FilePath -> Q Exp+embedFileRelativeBytes f = makeRelativeToProject f >>= embedFile++-- -- | Like hereFile, but takes a path relative to the package directory.+-- -- Similar to embedFileRelative ?+-- hereFileRelative :: FilePath -> Q Exp+-- hereFileRelative f = makeRelativeToProject f >>= hereFileExp+-- where+-- QuasiQuoter{quoteExp=hereFileExp} = hereFile++++-- Command line parsing++-- | The program's command line arguments.+-- Uses unsafePerformIO; tends to stick in GHCI until reloaded,+-- and may or may not detect args provided by a hledger config file.+{-# NOINLINE progArgs #-}+progArgs :: [String]+progArgs = unsafePerformIO getArgs+-- XX currently this affects:+-- the enabling of orderdates and assertions checks in journalFinalise+-- a few cases involving --color (see useColorOnStdoutUnsafe)+-- --debug++-- | Given one or more long or short flag names,+-- report whether this flag is present in the command line.+-- Concatenated short flags (-a -b written as -ab) are not supported.+getFlag :: [String] -> IO Bool+getFlag names = do+ let flags = map toFlag names+ args <- getArgs+ return $ any (`elem` args) flags++-- | Given one or more long or short option names, read the rightmost value of this option from the command line arguments.+-- If the value is missing raise an error.+-- Concatenated short flags (-a -b written as -ab) are not supported.+getOpt :: [String] -> IO (Maybe String)+getOpt names = do+ rargs <- reverse . splitFlagsAndVals <$> getArgs+ let flags = map toFlag names+ return $+ case break ((`elem` flags)) rargs of+ (_,[]) -> Nothing+ ([],flag:_) -> error' $ flag <> " requires a value"+ (argsafter,_) -> Just $ last argsafter++-- | Given a list of command line arguments, split any of the form --flag=VAL or -fVAL into two list items.+-- Concatenated short flags (-a -b written as -ab) are not supported.+splitFlagsAndVals :: [String] -> [String]+splitFlagsAndVals = concatMap $+ \case+ a@('-':'-':_) | '=' `elem` a -> let (x,y) = break (=='=') a in [x, drop 1 y]+ a@('-':f:_:_) | not $ f=='-' -> [take 2 a, drop 2 a]+ a -> [a]++-- | Convert a short or long flag name to a flag with leading hyphen(s).+toFlag [c] = ['-',c]+toFlag s = '-':'-':s++-- | Parse y/yes/always or n/no/never to true or false, or return an error message.+parseYN :: String -> Either String Bool+parseYN s+ | l `elem` ["y","yes","always"] = Right True+ | l `elem` ["n","no","never"] = Right False+ | otherwise = Left $ "value should be one of " <> (intercalate ", " ["y","yes","n","no"])+ where l = map toLower s++data YNA = Yes | No | Auto deriving (Eq,Show)++-- | Parse y/yes/always or n/no/never or a/auto to a YNA choice, or return an error message.+parseYNA :: String -> Either String YNA+parseYNA s+ | l `elem` ["y","yes","always"] = Right Yes+ | l `elem` ["n","no","never"] = Right No+ | l `elem` ["a","auto"] = Right Auto+ | otherwise = Left $ "value should be one of " <> (intercalate ", " ["y","yes","n","no","a","auto"])+ where l = map toLower s++-- | Is there a --output-file or -o option in the command line arguments ?+-- Uses getOpt; sticky in GHCI until reloaded, may not always be affected by a hledger config file, etc.+hasOutputFile :: IO Bool+hasOutputFile = do+ mv <- getOpt ["output-file","o"]+ return $+ case mv of+ Nothing -> False+ Just "-" -> False+ _ -> True++-- -- | Get the -o/--output-file option's value, if any, from the command line arguments.+-- -- Uses getOpt; sticky in GHCI until reloaded, may not always be affected by a hledger config file, etc.+-- outputFileOption :: IO (Maybe String)+-- outputFileOption = getOpt ["output-file","o"]++++-- Terminal size++-- [NOTE: Alternative methods of getting the terminal size]+-- terminal-size uses the TIOCGWINSZ ioctl to get the window size on Unix+-- systems, which may not be completely portable according to people in+-- #linux@liberachat.+--+-- If this turns out to be the case, supplementary coverage can be given by+-- using the terminfo package.+--+-- Conversely, terminfo on its own is not a full solution, firstly because it+-- only works on Unix (not Windows), and secondly since in some scenarios (eg+-- stripped-down build systems) the terminfo database may be limited and lack+-- the correct entries. (A hack that sometimes works but which isn't robust+-- enough to be relied upon is to set TERM=dumb -- while this advice does appear+-- in some places, it's not guaranteed to work)+--+-- In any case, $LINES/$COLUMNS should not be used as a source for the terminal+-- size - they are not available or do not update reliably in all shells.+--+-- See #2332 for details++-- | An alternative to ansi-terminal's getTerminalSize, based on+-- the more robust-looking terminal-size package.+--+-- Tries to get stdout's terminal's current height and width.+getTerminalHeightWidth :: IO (Maybe (Int,Int))+getTerminalHeightWidth = fmap (fmap unwindow) size+ where unwindow (Window h w) = (h,w)++getTerminalHeight :: IO (Maybe Int)+getTerminalHeight = fmap fst <$> getTerminalHeightWidth++getTerminalWidth :: IO (Maybe Int)+getTerminalWidth = fmap snd <$> getTerminalHeightWidth++-- | Are we running inside an Emacs subprocess other than vterm ?+-- Terminals like Emacs's M-x shell (comint) advertise a full xterm terminal+-- but only partially emulate it (SGR colours render, but cursor movement and+-- terminal queries do not), so interactive line editing, paging and background+-- colour detection tend to misbehave there.+-- vterm is excluded because it emulates a terminal fully.+-- Emacs sets INSIDE_EMACS to eg "30.1,comint" or "30.1,vterm", so we look for a+-- "vterm" component rather than an exact match.+insideEmacsNotVterm :: IO Bool+insideEmacsNotVterm = maybe False (not . ("vterm" `isInfixOf`)) <$> lookupEnv "INSIDE_EMACS"++++-- Pager output+-- somewhat hledger-specific++-- | Try to find a pager executable robustly, safely handling various error conditions+-- like an unset PATH var or the specified pager not being found as an executable.+-- The pager can be specified by a path or program name in the PAGER environment variable.+-- If that is unset or has a problem, "less" is tried, then "more".+-- If successful, the pager's path or program name is returned.+findPager :: IO (Maybe String) -- XXX probably a ByteString in fact ?+findPager = do+ mpagervar <- lookupEnv "PAGER"+ let pagers = [p | Just p <- [mpagervar]] <> ["less", "more"]+ headMay . catMaybes <$> mapM findExecutable pagers++-- | Should a pager be used for displaying the given text on stdout, and if so, which one ?+-- Uses a pager if findPager finds one and none of the following conditions are true:+-- We're running in a native MS Windows environment like cmd or powershell.+-- Or the --pager=n|no option is in effect.+-- Or the -o/--output-file option is in effect.+-- Or INSIDE_EMACS is set, to something other than "vterm".+-- Or the terminal's current height and width can't be detected.+-- Or the output text is less wide and less tall than the terminal.+-- Throws an error if the --pager option's value could not be parsed.+maybePagerFor :: String -> IO (Maybe String)+maybePagerFor output = do+ let+ ls = lines output+ oh = length ls+ ow = maximumDef 0 $ map length ls+ windows = os == "mingw32"+ pagerno <- maybe False (not . either error' id . parseYN) <$> getOpt ["pager"]+ outputfile <- hasOutputFile+ emacsterm <- insideEmacsNotVterm+ mhw <- getTerminalHeightWidth+ mpager <- findPager+ return $ do+ guard $ not $ windows || pagerno || outputfile || emacsterm+ (th,tw) <- mhw+ guard $ oh > th || ow > tw+ mpager++-- | Display the given text on the terminal, trying to use a pager ($PAGER, less, or more)+-- when appropriate (see maybePagerFor), otherwise printing to standard output.+-- Also, if the pager is less, we modify the LESS environment variable (see lessVarValue)+-- and check for problems which could cause confusing output (see lessIsWorking).+runPager :: String -> IO ()+runPager s = do+ mpager <- maybePagerFor s+ case mpager of+ Nothing -> putStr s+ Just pager -> do++ -- If using less, customise the LESS environment variable and check if it works+ let pagerIsLess = map toLower (takeBaseName pager) == "less"+ (mCustomEnv, shouldUsePager) <- if not pagerIsLess+ then return (Nothing, True)+ else do+ mHLEDGER_LESS <- lookupEnv "HLEDGER_LESS"+ mLESS <- lookupEnv "LESS"+ usecolor <- useColorOnStdout+ let newlessvar = lessVarValue mHLEDGER_LESS mLESS usecolor+ env <- getEnvironment+ let customEnv = ("LESS", newlessvar) : filter ((/= "LESS") . fst) env+ -- Check that less --version is working (using our custom LESS) (#2544)+ lessHasError <- lessIsWorking (Just customEnv) `catch` \(_::IOException) -> return True+ when lessHasError $ warnIO $+ "less --version fails with current LESS settings; disabling. Check 'hledger setup' for details.\n"+ return (Just customEnv, not lessHasError)++ -- Run the pager, providing the text as input. Or if we found a problem already, just print.+ if not shouldUsePager+ then putStr s+ else (withCreateProcess (shell pager){std_in=CreatePipe, env=mCustomEnv} $+ \mhin _ _ p -> do+ case mhin of+ Nothing -> fail "Failed to create pipe to pager"+ Just hin -> void $ forkIO $ -- Write from another thread to avoid deadlock ? Maybe unneeded, but just in case.+ (hPutStr hin s >> hClose hin) -- Be sure to close the pipe so the pager knows we're done.+ -- If the pager quits early, we'll receive an EPIPE error; hide that.+ `catch` \(e::IOException) -> case e of+ IOError{ioe_type=ResourceVanished, ioe_errno=Just ioe, ioe_handle=Just hdl} | Errno ioe==ePIPE, hdl==hin -> return ()+ _ -> throwIO e+ void $ waitForProcess p)+ `catch` \(_::IOException) -> putStr s++-- | Test @less@, by running less --version and looking for a nonzero exit, timeout, or stderr output.+-- Uses the provided environment, containing a LESS variable, if any.+-- We do this because various LESS settings can cause some less versions to fail or cause confusing output without failing.+lessIsWorking :: Maybe [(String, String)] -> IO Bool+lessIsWorking mCustomEnv = do+ result <- timeout 300000 $ readCreateProcessWithExitCode (proc "less" ["--version"]){env=mCustomEnv} ""+ return $ case result of+ Nothing -> True -- Timeout+ Just (exitCode, _, stderrOut) -> exitCode /= ExitSuccess || not (null stderrOut)++-- | Compute the LESS environment variable value that hledger will use for the less pager.+-- This used in runPager when invoking less, and also in the setup command for display.+-- It takes the current HLEDGER_LESS and LESS env var values, and whether we are showing colour on stdout,+-- and returns the adjusted LESS value that should be used. Specifically:+--+-- - If HLEDGER_LESS is defined, we use it in place of the LESS environment variable.+--+-- - Otherwise, if LESS is defined, append some preferred options (lessOptions and maybe lessColourOptions) to it.+--+-- - Otherwise, we set LESS to just use those preferred options.+--+lessVarValue :: Maybe String -> Maybe String -> Bool -> String+lessVarValue mHLEDGER_LESS mLESS usecolor =+ let extraopts = words lessOptions <> [lessColourOptions | usecolor]+ in case (mHLEDGER_LESS, mLESS) of+ (Just hledgerlessvar, _) -> hledgerlessvar+ (_, Just lessvar) ->+ let existing = words lessvar+ new = filter (`notElem` existing) extraopts+ in if null new then lessvar else unwords (lessvar : new)+ _ -> unwords extraopts++-- keep synced: hledger.m4.md > Paging+-- | hledger's preferred less options, which it will append to the user's LESS environment variable.+-- The thinking here is: "Many people don't have their LESS optimised to get the best experience from modern less, as I didn't.+-- Also as they use hledger on different machines, LESS is likely not consistent. +-- So let's add some settings that I have found reasonably robust, compatible, and good for usability.+-- That will help provide a consistent good experience when viewing hledger's long outputs.+-- And power users can prevent this by setting exactly the options they want in HLEDGER_LESS."+-- Here's what they mean: https://manned.org/man/less#head5+--+-- Flags that might break older less versions (causing hledger to fall back to unpaged output) are avoided here.+-- Such as --mouse and --wheel-lines (less >=530, 2018) and --use-color (less >=551, 2019).+-- --hilite-unread (less >=443, 2011) is useful and considered old enough.+--+lessOptions = unwords [+ "--chop-long-lines"+ ,"--hilite-unread"+ ,"--ignore-case"+ ,"--no-init"+ ,"--quit-if-one-screen"+ ,"--shift=8"+ ,"--squeeze-blank-lines"+ ,"--use-backslash"+ ] ++-- | Additional less options to use if we are showing colour on stdout.+lessColourOptions = unwords [+ "--RAW-CONTROL-CHARS"+ ]+++-- ANSI colour/styles+-- Some of these use unsafePerformIO to read info.++-- hledger-specific:++-- | Get the value of the rightmost --color or --colour option from the program's command line arguments.+-- Throws an error if the option's value could not be parsed.+colorOption :: IO YNA+colorOption = maybe Auto (either error' id . parseYNA) <$> getOpt ["color","colour"]++-- | Should ANSI color and styles be used with this output handle ?+-- Considers the --color/--colour option, and in auto mode the NO_COLOR and TERM+-- environment variables and whether the handle is an ANSI-capable terminal.+-- In auto mode we never use colour when TERM=dumb (the conventional request for+-- plain output); otherwise we use it when ansi-terminal's hSupportsANSIColor says+-- the handle supports colour. Note hSupportsANSIColor reports colour support for an+-- Emacs subshell even on a captured pipe when TERM=dumb, which would leak escape+-- codes into redirected output (eg shelltest); the TERM=dumb check prevents that.+useColorOnHandle :: Handle -> IO Bool+useColorOnHandle h = do+ no_color <- isJust <$> lookupEnv "NO_COLOR"+ dumbterminal <- (== Just "dumb") . fmap (map toLower) <$> lookupEnv "TERM"+ supports_color <- hSupportsANSIColor h+ yna <- colorOption+ return $ yna==Yes || (yna==Auto && not no_color && not dumbterminal && supports_color)++-- | Should ANSI color and styles be used for standard output ?+-- Considers useColorOnHandle stdout and hasOutputFile.+useColorOnStdout :: IO Bool+useColorOnStdout = do+ nooutputfile <- not <$> hasOutputFile+ usecolor <- useColorOnHandle stdout+ return $ nooutputfile && usecolor++-- | Should ANSI color and styles be used for standard error output ?+-- Considers useColorOnHandle stderr; is not affected by an --output-file option.+useColorOnStderr :: IO Bool+useColorOnStderr = useColorOnHandle stderr++-- | Like useColorOnStdout, but using unsafePerformIO. Useful eg for low-level debug code.+-- Sticky in GHCI until reloaded, may not always be affected by --color in a hledger config file, etc.+useColorOnStdoutUnsafe :: Bool+useColorOnStdoutUnsafe = unsafePerformIO useColorOnStdout++-- | Like useColorOnStdoutUnsafe, but for stderr.+useColorOnStderrUnsafe :: Bool+useColorOnStderrUnsafe = unsafePerformIO useColorOnStderr++-- | Does the terminal appear to support 24-bit "true colour" ?+-- Detected from the COLORTERM environment variable being "truecolor" or "24bit",+-- the de-facto convention. This errs conservative: it can miss truecolor terminals+-- that don't set COLORTERM (eg across ssh/tmux/sudo), in which case we fall back to+-- 256-colour; and it can't help terminals that set it but don't actually render+-- truecolor. When false, 'rgb'' downgrades to the nearest xterm 256-colour.+supportsTrueColor :: IO Bool+supportsTrueColor = maybe False (`elem` ["truecolor","24bit"]) <$> lookupEnv "COLORTERM"++-- | Like 'supportsTrueColor', but using unsafePerformIO.+supportsTrueColorUnsafe :: Bool+supportsTrueColorUnsafe = unsafePerformIO supportsTrueColor++-- | Detect whether ANSI should be used on stdout using useColorOnStdoutUnsafe,+-- and if so prepend and append the given SGR codes to a string.+-- Currently used in a few places (the commands list, the recentassertions error message, add);+-- see useColorOnStdoutUnsafe's limitations.+ansiWrapUnsafe :: SGRString -> SGRString -> String -> String+ansiWrapUnsafe pre post s = if useColorOnStdoutUnsafe then pre<>s<>post else s++type SGRString = String++sgrbold = setSGRCode [SetConsoleIntensity BoldIntensity]+sgrfaint = setSGRCode [SetConsoleIntensity FaintIntensity]+sgrnormal = setSGRCode [SetConsoleIntensity NormalIntensity]+sgrresetfg = setSGRCode [SetDefaultColor Foreground]+sgrresetbg = setSGRCode [SetDefaultColor Background]+sgrresetall = sgrresetfg <> sgrresetbg <> sgrnormal+sgrblack = setSGRCode [SetColor Foreground Dull Black]+sgrred = setSGRCode [SetColor Foreground Dull Red]+sgrgreen = setSGRCode [SetColor Foreground Dull Green]+sgryellow = setSGRCode [SetColor Foreground Dull Yellow]+sgrblue = setSGRCode [SetColor Foreground Dull Blue]+sgrmagenta = setSGRCode [SetColor Foreground Dull Magenta]+sgrcyan = setSGRCode [SetColor Foreground Dull Cyan]+sgrwhite = setSGRCode [SetColor Foreground Dull White]+sgrbrightblack = setSGRCode [SetColor Foreground Vivid Black]+sgrbrightred = setSGRCode [SetColor Foreground Vivid Red]+sgrbrightgreen = setSGRCode [SetColor Foreground Vivid Green]+sgrbrightyellow = setSGRCode [SetColor Foreground Vivid Yellow]+sgrbrightblue = setSGRCode [SetColor Foreground Vivid Blue]+sgrbrightmagenta = setSGRCode [SetColor Foreground Vivid Magenta]+sgrbrightcyan = setSGRCode [SetColor Foreground Vivid Cyan]+sgrbrightwhite = setSGRCode [SetColor Foreground Vivid White]+-- Emit a 24-bit truecolor foreground code, or if the terminal doesn't advertise+-- truecolor support (see supportsTrueColorUnsafe), the nearest xterm 256-colour.+sgrrgb r g b+ | supportsTrueColorUnsafe = setSGRCode [SetRGBColor Foreground $ sRGB r g b]+ | otherwise = setSGRCode [SetPaletteColor Foreground $ xterm6LevelRGB (lvl r) (lvl g) (lvl b)]+ where lvl v = max 0 $ min 5 $ round (v * 5) -- map a 0..1 intensity to a 0..5 colour-cube level++-- | Set various ANSI styles/colours in a string, only if useColorOnStdoutUnsafe says we should.+bold' :: String -> String+bold' = ansiWrapUnsafe sgrbold sgrnormal++faint' :: String -> String+faint' = ansiWrapUnsafe sgrfaint sgrnormal++black' :: String -> String+black' = ansiWrapUnsafe sgrblack sgrresetfg++red' :: String -> String+red' = ansiWrapUnsafe sgrred sgrresetfg++green' :: String -> String+green' = ansiWrapUnsafe sgrgreen sgrresetfg++yellow' :: String -> String+yellow' = ansiWrapUnsafe sgryellow sgrresetfg++blue' :: String -> String+blue' = ansiWrapUnsafe sgrblue sgrresetfg++magenta' :: String -> String+magenta' = ansiWrapUnsafe sgrmagenta sgrresetfg++cyan' :: String -> String+cyan' = ansiWrapUnsafe sgrcyan sgrresetfg++white' :: String -> String+white' = ansiWrapUnsafe sgrwhite sgrresetfg++brightBlack' :: String -> String+brightBlack' = ansiWrapUnsafe sgrbrightblack sgrresetfg++brightRed' :: String -> String+brightRed' = ansiWrapUnsafe sgrbrightred sgrresetfg++brightGreen' :: String -> String+brightGreen' = ansiWrapUnsafe sgrbrightgreen sgrresetfg++brightYellow' :: String -> String+brightYellow' = ansiWrapUnsafe sgrbrightyellow sgrresetfg++brightBlue' :: String -> String+brightBlue' = ansiWrapUnsafe sgrbrightblue sgrresetfg++brightMagenta' :: String -> String+brightMagenta' = ansiWrapUnsafe sgrbrightmagenta sgrresetfg++brightCyan' :: String -> String+brightCyan' = ansiWrapUnsafe sgrbrightcyan sgrresetfg++brightWhite' :: String -> String+brightWhite' = ansiWrapUnsafe sgrbrightwhite sgrresetfg++rgb' :: Float -> Float -> Float -> String -> String+rgb' r g b = ansiWrapUnsafe (sgrrgb r g b) sgrresetfg++-- | Choose and apply an accent color for hledger output, if possible+-- picking one that will contrast with the current terminal background colour.+accent :: String -> String+accent+ | not useColorOnStdoutUnsafe = id -- XXX unsafe accenting the title banner - seems to work, even respecting config file+ | terminalIsLight == Just False = brightWhite'+ | terminalIsLight == Just True = brightBlack'+ | otherwise = id++-- | Colour a string with hledger's diagonal blue-to-green gradient: each+-- character's colour depends on its position (@row@, and column counting from+-- @col0@) within a grid @h@ rows tall and @w@ columns wide, fading blue at the+-- top-left to green at the bottom-right. The gradient is brighter on a dark+-- terminal background and darker on a light one. The whole string is wrapped in+-- the given intensity style (eg 'bold'' or 'faint''); the per-character colour+-- codes only touch the foreground, so the intensity is kept across the string.+-- When the background lightness can't be detected (eg inside emacs, where the+-- background-colour query doesn't work), it uses the light-background palette,+-- whose deeper shades stay legible on both light and dark backgrounds; only a+-- background known to be dark gets the brighter dark-background palette.+-- Colouring is skipped entirely only when colour is off.+gradientStr :: (String -> String) -> Int -> Int -> Int -> Int -> String -> String+gradientStr intensity h w row col0 s+ | not useColorOnStdoutUnsafe = s+ | otherwise =+ let light = terminalIsLight /= Just False -- deep palette unless the background is known dark+ (r1,g1,b1) = if light then (0.12,0.44,0.69) else (0.16,0.71,0.85) -- start (blue)+ (r2,g2,b2) = if light then (0.25,0.49,0.12) else (0.48,0.75,0.26) -- end (green)+ fullspan = fromIntegral (max 1 (h + w - 2)) :: Float+ paint c ch+ | ch == ' ' = " " -- leave gaps uncoloured, and out of the escape-code noise+ | otherwise = rgb' (mix r1 r2) (mix g1 g2) (mix b1 b2) [ch]+ where t = fromIntegral (row + c) / fullspan -- 0 at top-left, 1 at bottom-right+ mix a b = a + (b - a) * t+ in intensity $ concat $ zipWith paint [col0..] s++-- | Render a title heading coloured with hledger's blue-to-green bold gradient,+-- when colour is enabled.+titleLine :: String -> String+titleLine title = gradientStr bold' 1 (length title) 0 0 title++-- | Render a one-line heading with a title at the left and a version (or other+-- short annotation) right-aligned to the given width, both coloured with+-- hledger's blue-to-green gradient (bold title, faint version) when colour is+-- enabled.+titleAndVersionLine :: Int -> String -> String -> String+titleAndVersionLine width title version = styledtitle <> pad <> styledversion+ where+ styledtitle = gradientStr bold' 1 (length title) 0 0 title+ styledversion = gradientStr faint' 1 (length version) 0 0 version+ pad = replicate (max 1 $ width - length title - length version) ' '++-- Generic:++-- | Wrap a string in ANSI codes to set and reset foreground colour.+-- ColorIntensity is @Dull@ or @Vivid@ (ie normal and bold).+-- Color is one of @Black@, @Red@, @Green@, @Yellow@, @Blue@, @Magenta@, @Cyan@, @White@.+-- Eg: @color Dull Red "text"@.+color :: ColorIntensity -> Color -> String -> String+color int col s = setSGRCode [SetColor Foreground int col] ++ s ++ setSGRCode []++-- | Wrap a string in ANSI codes to set and reset background colour.+bgColor :: ColorIntensity -> Color -> String -> String+bgColor int col s = setSGRCode [SetColor Background int col] ++ s ++ setSGRCode []++-- | Wrap a WideBuilder in ANSI codes to set and reset foreground colour.+colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder+colorB int col (WideBuilder s w) =+ WideBuilder (TB.fromString (setSGRCode [SetColor Foreground int col]) <> s <> TB.fromString (setSGRCode [])) w++-- | Wrap a WideBuilder in ANSI codes to set and reset background colour.+bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder+bgColorB int col (WideBuilder s w) =+ WideBuilder (TB.fromString (setSGRCode [SetColor Background int col]) <> s <> TB.fromString (setSGRCode [])) w+++-- | Detect whether the terminal currently has a light background colour,+-- if possible, using unsafePerformIO.+-- If the terminal is transparent, its apparent light/darkness may be different.+terminalIsLight :: Maybe Bool+terminalIsLight = (> 0.5) <$> terminalLightness++-- | Detect the terminal's current background lightness (0..1), if possible, using unsafePerformIO.+-- If the terminal is transparent, its apparent lightness may be different.+terminalLightness :: Maybe Float+terminalLightness = lightness <$> terminalColor Background++-- | Detect the terminal's current background colour, if possible, using unsafePerformIO.+terminalBgColor :: Maybe (RGB Float)+terminalBgColor = terminalColor Background++-- | Detect the terminal's current foreground colour, if possible, using unsafePerformIO.+terminalFgColor :: Maybe (RGB Float)+terminalFgColor = terminalColor Foreground++-- | Detect the terminal's current foreground or background colour, if possible, using unsafePerformIO.+{-# NOINLINE terminalColor #-}+terminalColor :: ConsoleLayer -> Maybe (RGB Float)+terminalColor = unsafePerformIO . getLayerColor'++-- A version of ansi-terminal's getLayerColor that is less likely to leak escape sequences to output,+-- and that returns a RGB of Floats (0..1) that is more compatible with the colour package.+-- This does nothing in a non-interactive context (eg when piping stdout to another command,+-- or when stdin, where the terminal's answer is read, is not the terminal, eg with -f -),+-- inside emacs (comint shell buffers show the query's escape sequence instead of answering it,+-- and vterm doesn't answer the query at all), or in a non-colour-supporting terminal.+-- If the query fails for some other reason, the colour is unknown.+getLayerColor' :: ConsoleLayer -> IO (Maybe (RGB Float))+getLayerColor' l = do+ inemacs <- not . null <$> lookupEnv "INSIDE_EMACS"+ interactive <- (&&) <$> hIsTerminalDevice stdout <*> hIsTerminalDevice stdin+ supportscolor <- hSupportsANSIColor stdout+ if inemacs || not interactive || not supportscolor then return Nothing+ else (fmap fractionalRGB <$> getLayerColor l) `catch` \(_ :: IOException) -> return Nothing+ where+ fractionalRGB :: (Fractional a) => RGB Word16 -> RGB a+ fractionalRGB (RGB r g b) = RGB (fromIntegral r / 65535) (fromIntegral g / 65535) (fromIntegral b / 65535) -- chatgpt+
+ Hledger/Utils/Parse.hs view
@@ -0,0 +1,670 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++module Hledger.Utils.Parse (++ -- * Some basic hledger parser flavours+ SimpleStringParser,+ SimpleTextParser,+ TextParser,++ -- * SourcePos+ SourcePos(..),+ mkPos,+ unPos,+ initialPos,+ sourcePosPretty,+ sourcePosPairPretty,+ sourcePosFileLine,++ -- * Parsers and helpers+ choice',+ choiceInState,+ surroundedBy,+ parsewith,+ runTextParser,+ rtp,+ parsewithString,+ parseWithState,+ parseWithState',+ fromparse,+ parseerror,+ nonspace,+ isNewline,+ isNonNewlineSpace,+ restofline,+ eolof,+ spacenonewline,+ skipNonNewlineSpaces,+ skipNonNewlineSpaces1,+ skipNonNewlineSpaces',+ peekChar,+ peekChars2,+ peekAfterSpaces,+ manyWhile,++ -- ** Trace the state of hledger parsers+ dbgparse,++ -- * More helpers, previously in Text.Megaparsec.Custom++ -- ** Custom parse error types+ HledgerParseErrorData,+ HledgerParseErrors,++ -- ** Failing with an arbitrary source position+ parseErrorAt,+ parseErrorAtRegion,++ -- ** Re-parsing+ SourceExcerpt,+ getExcerptText,+ excerpt_,+ reparseExcerpt,++ -- ** Pretty-printing custom parse errors+ customErrorBundlePretty,+ finalizeCustomErrorBundle,++ -- ** "Final" parse errors+ FinalParseError,+ FinalParseError',+ FinalParseErrorBundle,+ FinalParseErrorBundle',++ -- *** Constructing "final" parse errors+ finalError,+ finalFancyFailure,+ finalFail,+ finalCustomFailure,+ finalMessageFailure,++ -- *** Pretty-printing "final" parse errors+ finalErrorBundlePretty,+ attachSource,++ -- *** Handling parse errors from include files with "final" parse errors+ parseIncludeFile,++)+where++import Control.Monad (MonadPlus, when)+import Data.Text qualified as T+import Text.Megaparsec+import Text.Printf+import Control.Monad.State.Strict (StateT, evalStateT)+import Data.Char+import Data.Functor (void)+import Data.Functor.Identity (Identity(..))+import Data.Text (Text)+import Text.Megaparsec.Char+-- import Text.Megaparsec.Debug (dbg)++import Control.Monad.Except (ExceptT, MonadError, catchError, throwError)+import Control.Monad.Trans.Class (lift)+import Data.List.NonEmpty qualified as NE+import Data.Monoid (Alt(..))+import Data.Set qualified as S++import Hledger.Utils.Debug (debugLevel, dbg0Msg)++-- | A parser of string to some type.+type SimpleStringParser a = Parsec HledgerParseErrorData String a++-- | A parser of strict text to some type.+type SimpleTextParser = Parsec HledgerParseErrorData Text -- XXX an "a" argument breaks the CsvRulesParser declaration somehow++-- | A parser of text that runs in some monad.+type TextParser m a = ParsecT HledgerParseErrorData Text m a++-- class (Stream s, MonadPlus m) => MonadParsec e s m +-- dbgparse :: (MonadPlus m, MonadParsec e String m) => Int -> String -> m ()++-- | Trace to stderr or log to debug log the provided label (if non-null)+-- and current parser state (position and next input),+-- if the global debug level is at or above the specified level.+-- See also: Hledger.Utils.Debug, megaparsec's dbg.+-- Uses unsafePerformIO.+-- XXX Can be hard to make this evaluate.+dbgparse :: Int -> String -> TextParser m ()+dbgparse level msg = when (level <= debugLevel) $ do+ pos <- getSourcePos+ next <- (T.take peeklength) `fmap` getInput+ let (l,c) = (sourceLine pos, sourceColumn pos)+ s = printf "at line %2d col %2d: %s" (unPos l) (unPos c) (show next) :: String+ s' = printf ("%-"++show (peeklength+30)++"s") s ++ " " ++ msg+ dbg0Msg s' $ return ()+ where+ peeklength = 30++-- | Render a pair of source positions in human-readable form, only displaying the range of lines,+-- or just the one line number if the range is a single line.+sourcePosPairPretty :: (SourcePos, SourcePos) -> String+sourcePosPairPretty (SourcePos fp l1 _, SourcePos _ l2 c2) =+ fp ++ ":" ++ show l1' ++ (if l2' > l1' then "-" ++ show l2' else "")+ where+ l1' = unPos l1+ l2' = if unPos c2 == 1 then unPos l2 - 1 else unPos l2 -- might be at end of file with a final new line++-- | Render a source position as FILE:LINE, without its column.+sourcePosFileLine :: SourcePos -> String+sourcePosFileLine (SourcePos fp l _) = fp ++ ":" ++ show (unPos l)++-- | Backtracking choice, use this when alternatives share a prefix.+-- Consumes no input if all choices fail.+choice' :: [TextParser m a] -> TextParser m a+choice' = choice . map try++-- | Backtracking choice, use this when alternatives share a prefix.+-- Consumes no input if all choices fail.+choiceInState :: [StateT s (ParsecT HledgerParseErrorData Text m) a] -> StateT s (ParsecT HledgerParseErrorData Text m) a+choiceInState = choice . map try++surroundedBy :: Applicative m => m openclose -> m a -> m a+surroundedBy p = between p p++parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a+parsewith p = runParser p ""++-- | Run a text parser in the identity monad. See also: parseWithState.+runTextParser, rtp :: TextParser Identity a -> Text -> Either HledgerParseErrors a+runTextParser = parsewith+rtp = runTextParser++parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a+parsewithString p = runParser p ""++-- | Run a stateful parser with some initial state on a text.+-- See also: runTextParser, runJournalParser.+parseWithState+ :: Monad m+ => st+ -> StateT st (ParsecT HledgerParseErrorData Text m) a+ -> Text+ -> m (Either HledgerParseErrors a)+parseWithState ctx p = runParserT (evalStateT p ctx) ""++parseWithState'+ :: (Stream s)+ => st+ -> StateT st (ParsecT e s Identity) a+ -> s+ -> (Either (ParseErrorBundle s e) a)+parseWithState' ctx p = runParser (evalStateT p ctx) ""++fromparse :: (Show t, Show (Token t), Show e) => Either (ParseErrorBundle t e) a -> a+fromparse = either parseerror id++parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a+parseerror e = errorWithoutStackTrace $ showParseError e -- PARTIAL:++showParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String+showParseError e = "parse error at " ++ show e+++isNewline :: Char -> Bool +isNewline '\n' = True+isNewline _ = False++nonspace :: TextParser m Char+nonspace = satisfy (not . isSpace)++isNonNewlineSpace :: Char -> Bool+isNonNewlineSpace c = not (isNewline c) && isSpace c++spacenonewline :: (Stream s, Char ~ Token s) => ParsecT HledgerParseErrorData s m Char+spacenonewline = satisfy isNonNewlineSpace+{-# INLINABLE spacenonewline #-}++restofline :: TextParser m String+restofline = T.unpack <$> takeWhileP Nothing (/= '\n') <* eolof++-- Skip many non-newline spaces.+skipNonNewlineSpaces :: (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()+skipNonNewlineSpaces = void $ takeWhileP Nothing isNonNewlineSpace+{-# INLINABLE skipNonNewlineSpaces #-}++-- Skip many non-newline spaces, failing if there are none.+skipNonNewlineSpaces1 :: (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()+skipNonNewlineSpaces1 = void $ takeWhile1P Nothing isNonNewlineSpace+{-# INLINABLE skipNonNewlineSpaces1 #-}++-- | Skip any non-newline whitespace, and return whether there was any.+skipNonNewlineSpaces' :: (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool+skipNonNewlineSpaces' = do+ o <- getOffset+ skipNonNewlineSpaces+ (> o) <$> getOffset+{-# INLINABLE skipNonNewlineSpaces' #-}++-- | Look at the next character of the input, if any, without consuming it.+-- Unlike a failed parse attempt this constructs no parse error, so it is a cheap+-- way to decide whether an optional or alternative parser could succeed before running it.+peekChar :: TextParser m (Maybe Char)+peekChar = fmap fst . T.uncons <$> getInput+{-# INLINABLE peekChar #-}++-- | Like peekChar, but returning the next two characters, if any.+peekChars2 :: TextParser m (Maybe Char, Maybe Char)+peekChars2 = do+ s <- getInput+ pure $ case T.uncons s of+ Nothing -> (Nothing, Nothing)+ Just (c1, s') -> (Just c1, fst <$> T.uncons s')+{-# INLINABLE peekChars2 #-}++-- | Like peekChar, but looking past any non-newline whitespace (not consuming that either).+-- Returns whether there was such whitespace, and the character following it, if any.+peekAfterSpaces :: TextParser m (Bool, Maybe Char)+peekAfterSpaces = do+ s <- getInput+ let spaced = maybe False (isNonNewlineSpace . fst) $ T.uncons s+ pure (spaced, fst <$> T.uncons (T.dropWhile isNonNewlineSpace s))+{-# INLINABLE peekAfterSpaces #-}++-- | Run a parser repeatedly, collecting the results, like many; but continue only+-- while a test (typically a cheap look at the next input, like peekChar) says it+-- could succeed, so that the end of the sequence is found without a failed parse+-- attempt. As with many, the parser failing without consuming input also ends the sequence.+manyWhile :: MonadPlus m => m Bool -> m a -> m [a]+manyWhile test p = go+ where+ go = do+ continue <- test+ if continue then ((:) <$> p <*> go) <|> pure [] else pure []+{-# INLINABLE manyWhile #-}++eolof :: TextParser m ()+eolof = void newline <|> eof++++-- A bunch of megaparsec helpers, eg for re-parsing (formerly in Text.Megaparsec.Custom).+-- I think these are generic apart from the HledgerParseError name.++--- * Custom parse error types++-- | Custom error data for hledger parsers. Specialised for a 'Text' parse stream.+-- ReparseableTextParseErrorData ?+data HledgerParseErrorData+ -- | Fail with a message at a specific source position interval. The+ -- interval must be contained within a single line.+ = ErrorFailAt Int -- Starting offset+ Int -- Ending offset+ String -- Error message+ -- | Re-throw parse errors obtained from the "re-parsing" of an excerpt+ -- of the source text.+ | ErrorReparsing+ (NE.NonEmpty (ParseError Text HledgerParseErrorData)) -- Source fragment parse errors+ deriving (Show, Eq, Ord)++-- | A specialised version of ParseErrorBundle: +-- a non-empty collection of hledger parse errors, +-- equipped with PosState to help pretty-print them.+-- Specialised for a 'Text' parse stream.+type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData++-- We require an 'Ord' instance for 'CustomError' so that they may be+-- stored in a 'Set'. The actual instance is inconsequential, so we just+-- derive it, but the derived instance requires an (orphan) instance for+-- 'ParseError'. Hopefully this does not cause any trouble.++deriving instance Ord (ParseError Text HledgerParseErrorData)++-- Note: the pretty-printing of our 'HledgerParseErrorData' type is only partally+-- defined in its 'ShowErrorComponent' instance; we perform additional+-- adjustments in 'customErrorBundlePretty'.++instance ShowErrorComponent HledgerParseErrorData where+ showErrorComponent (ErrorFailAt _ _ errMsg) = errMsg+ showErrorComponent (ErrorReparsing _) = "" -- dummy value++ errorComponentLen (ErrorFailAt startOffset endOffset _) =+ endOffset - startOffset+ errorComponentLen (ErrorReparsing _) = 1 -- dummy value+++--- * Failing with an arbitrary source position++-- | Fail at a specific source position, given by the raw offset from the+-- start of the input stream (the number of tokens processed at that+-- point).+parseErrorAt :: Int -> String -> HledgerParseErrorData+parseErrorAt offset = ErrorFailAt offset (offset+1)++-- | Fail at a specific source interval, given by the raw offsets of its+-- endpoints from the start of the input stream (the numbers of tokens+-- processed at those points).+--+-- Note that care must be taken to ensure that the specified interval does+-- not span multiple lines of the input source. This will not be checked.+parseErrorAtRegion+ :: Int -- ^ Start offset+ -> Int -- ^ End end offset+ -> String -- ^ Error message+ -> HledgerParseErrorData+parseErrorAtRegion startOffset endOffset msg =+ if startOffset < endOffset+ then ErrorFailAt startOffset endOffset msg'+ else ErrorFailAt startOffset (startOffset+1) msg'+ where+ msg' = "\n" ++ msg+++--- * Re-parsing++-- | A fragment of source suitable for "re-parsing". The purpose of this+-- data type is to preserve the content and source position of the excerpt+-- so that parse errors raised during "re-parsing" may properly reference+-- the original source.+data SourceExcerpt = SourceExcerpt Int -- Offset of beginning of excerpt+ Text -- Fragment of source file++-- | Get the raw text of a source excerpt.+getExcerptText :: SourceExcerpt -> Text+getExcerptText (SourceExcerpt _ txt) = txt++-- | 'excerpt_ p' applies the given parser 'p' and extracts the portion of+-- the source consumed by 'p', along with the source position of this+-- portion. This is the only way to create a source excerpt suitable for+-- "re-parsing" by 'reparseExcerpt'.++-- This function could be extended to return the result of 'p', but we don't+-- currently need this.++excerpt_ :: MonadParsec HledgerParseErrorData Text m => m a -> m SourceExcerpt+excerpt_ p = do+ offset <- getOffset+ (!txt, _) <- match p+ pure $ SourceExcerpt offset txt++-- | 'reparseExcerpt s p' "re-parses" the source excerpt 's' using the+-- parser 'p'. Parse errors raised by 'p' will be re-thrown at the source+-- position of the source excerpt.+--+-- In order for the correct source file to be displayed when re-throwing+-- parse errors, we must ensure that the source file during the use of+-- 'reparseExcerpt s p' is the same as that during the use of 'excerpt_'+-- that generated the source excerpt 's'. However, we can usually expect+-- this condition to be satisfied because, at the time of writing, the+-- only changes of source file in the codebase take place through include+-- files, and the parser for include files neither accepts nor returns+-- 'SourceExcerpt's.++reparseExcerpt+ :: Monad m+ => SourceExcerpt+ -> ParsecT HledgerParseErrorData Text m a+ -> ParsecT HledgerParseErrorData Text m a+reparseExcerpt (SourceExcerpt offset txt) p = do+ (_, res) <- lift $ runParserT' p (offsetInitialState offset txt)+ case res of+ Right result -> pure result+ Left errBundle -> customFailure $ ErrorReparsing $ bundleErrors errBundle++ where+ offsetInitialState :: Int -> s ->+#if MIN_VERSION_megaparsec(8,0,0)+ State s e+#else+ State s+#endif+ offsetInitialState initialOffset s = State+ { stateInput = s+ , stateOffset = initialOffset+ , statePosState = PosState+ { pstateInput = s+ , pstateOffset = initialOffset+ , pstateSourcePos = initialPos ""+ , pstateTabWidth = defaultTabWidth+ , pstateLinePrefix = ""+ }+#if MIN_VERSION_megaparsec(8,0,0)+ , stateParseErrors = []+#endif+ }++--- * Pretty-printing custom parse errors++-- | Pretty-print our custom parse errors. It is necessary to use this+-- instead of 'errorBundlePretty' when custom parse errors are thrown.+--+-- This function intercepts our custom parse errors and applies final+-- adjustments ('finalizeCustomError') before passing them to+-- 'errorBundlePretty'. These adjustments are part of the implementation+-- of the behaviour of our custom parse errors.+--+-- Note: We must ensure that the offset of the 'PosState' of the provided+-- 'ParseErrorBundle' is no larger than the offset specified by a+-- 'ErrorFailAt' constructor. This is guaranteed if this offset is set to+-- 0 (that is, the beginning of the source file), which is the+-- case for 'ParseErrorBundle's returned from 'runParserT'.++customErrorBundlePretty :: HledgerParseErrors -> String+customErrorBundlePretty = errorBundlePretty . finalizeCustomErrorBundle++-- | Apply the final adjustments to the custom parse errors in this error+-- bundle (see 'customErrorBundlePretty'), leaving errors which megaparsec's+-- standard 'errorBundlePretty' can render correctly. Exposed for callers+-- which need to adjust the bundle further before rendering it.+finalizeCustomErrorBundle :: HledgerParseErrors -> HledgerParseErrors+finalizeCustomErrorBundle errBundle =+ errBundle { bundleErrors =+ NE.sortWith errorOffset $ -- megaparsec requires that the list of errors be sorted by their offsets+ bundleErrors errBundle >>= finalizeCustomError }++ where+ finalizeCustomError+ :: ParseError Text HledgerParseErrorData -> NE.NonEmpty (ParseError Text HledgerParseErrorData)+ finalizeCustomError err = case findCustomError err of+ Nothing -> pure $ limitExpected err++ Just errFailAt@(ErrorFailAt startOffset _ _) ->+ -- Adjust the offset+ pure $ FancyError startOffset $ S.singleton $ ErrorCustom errFailAt++ Just (ErrorReparsing errs) ->+ -- Extract and finalize the inner errors+ errs >>= finalizeCustomError++ -- If any custom errors are present, arbitrarily take the first one+ -- (since only one custom error should be used at a time).+ findCustomError :: ParseError Text HledgerParseErrorData -> Maybe HledgerParseErrorData+ findCustomError err = case err of+ FancyError _ errSet ->+ finds (\case {ErrorCustom e -> Just e; _ -> Nothing}) errSet+ _ -> Nothing++ finds :: (Foldable t) => (a -> Maybe b) -> t a -> Maybe b+ finds f = getAlt . foldMap (Alt . f)++ -- Megaparsec lists every alternative the parser expected; for some parsers+ -- (eg period expressions, CSV rule field names) that's dozens or hundreds.+ -- When there are that many, show just the first few.+ limitExpected :: ParseError Text HledgerParseErrorData -> ParseError Text HledgerParseErrorData+ limitExpected (TrivialError o u es) | S.size es > 20 =+ TrivialError o u $ S.fromList (take 10 $ S.toAscList es) <> S.singleton (Label $ 'o' NE.:| ("ther valid values (" ++ show (S.size es - 10) ++ " more)"))+ limitExpected e = e+++--- * "Final" parse errors+--+-- | A type representing "final" parse errors that cannot be backtracked+-- from and are guaranteed to halt parsing. The anti-backtracking+-- behaviour is implemented by an 'ExceptT' layer in the parser's monad+-- stack, using this type as the 'ExceptT' error type.+--+-- We have three goals for this type:+-- (1) it should be possible to convert any parse error into a "final"+-- parse error,+-- (2) it should be possible to take a parse error thrown from an include+-- file and re-throw it in the context of the parent file, and+-- (3) the pretty-printing of "final" parse errors should be consistent+-- with that of ordinary parse errors, but should also report the stack of+-- parent files when errors are thrown from included files, and+-- (4) readers of non-journal formats (like CSV), which produce complete+-- error messages rather than parse errors, should be able to throw those+-- as "final" parse errors too, so they get the same include file stack.+--+-- In order to pretty-print a "final" parse error (goal 3), it must be+-- bundled with include filepaths and its full source text. When a "final"+-- parse error is thrown from within a parser, we do not have access to+-- the full source, so we must hold the parse error ('FinalParseError')+-- until it can be combined with the full source (and any parent file paths)+-- by the parser's caller ('FinalParseErrorBundle').++data FinalParseError' e+ -- a parse error thrown as a "final" parse error+ = FinalError (ParseError Text e)+ -- a parse error obtained from running a parser, e.g. using 'runParserT'+ | FinalBundle (ParseErrorBundle Text e)+ -- a parse error thrown from an include file+ | FinalBundleWithStack (FinalParseErrorBundle' e)+ -- a complete error message from a non-megaparsec reader (eg for CSV), shown without a source excerpt+ | FinalMessage String+ deriving (Show)++type FinalParseError = FinalParseError' HledgerParseErrorData++-- We need a 'Monoid' instance for 'FinalParseError' so that 'ExceptT+-- FinalParseError m' is an instance of Alternative and MonadPlus, which+-- is needed to use some parser combinators, e.g. 'many'.+--+-- This monoid instance simply takes the first (left-most) error.++instance Semigroup (FinalParseError' e) where+ e <> _ = e++instance Monoid (FinalParseError' e) where+ mempty = FinalError $ FancyError 0 $+ S.singleton (ErrorFail "default parse error")+ mappend = (<>)++-- | A type bundling a 'ParseError' with its full source text, filepath,+-- and stack of include files. Suitable for pretty-printing.+--+-- Megaparsec's 'ParseErrorBundle' type already bundles a parse error with+-- its full source text and filepath, so we just add a stack of include+-- files. Or, it can hold a complete error message instead (see 'FinalMessage').+data FinalParseErrorBundle' e = FinalParseErrorBundle'+ { finalErrorBundle :: Either String (ParseErrorBundle Text e)+ , includeFileStack :: [FilePath]+ } deriving (Show)++type FinalParseErrorBundle = FinalParseErrorBundle' HledgerParseErrorData+++--- * Constructing and throwing final parse errors++-- | Convert a "regular" parse error into a "final" parse error.+finalError :: ParseError Text e -> FinalParseError' e+finalError = FinalError++-- | Like megaparsec's 'fancyFailure', but as a "final" parse error.+finalFancyFailure+ :: (MonadParsec e s m, MonadError (FinalParseError' e) m)+ => S.Set (ErrorFancy e) -> m a+finalFancyFailure errSet = do+ offset <- getOffset+ throwError $ FinalError $ FancyError offset errSet++-- | Like 'fail', but as a "final" parse error.+finalFail :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => String -> m a+finalFail = finalFancyFailure . S.singleton . ErrorFail++-- | Like megaparsec's 'customFailure', but as a "final" parse error.+finalCustomFailure :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => e -> m a+finalCustomFailure = finalFancyFailure . S.singleton . ErrorCustom++-- | Throw a complete error message, eg from a non-megaparsec reader, as a "final" parse error.+-- It will be shown with the include file stack, but without a source excerpt.+finalMessageFailure :: MonadError (FinalParseError' e) m => String -> m a+finalMessageFailure = throwError . FinalMessage+++--- * Pretty-printing "final" parse errors++-- | Pretty-print a "final" parse error: print the stack of include files,+-- then apply the pretty-printer for parse error bundles.+-- Note that 'attachSource' must be used on a "final" parse error before it can be pretty-printed.+finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String+finalErrorBundlePretty bundle =+ concatMap showIncludeFilepath (includeFileStack bundle)+ <> either id customErrorBundlePretty (finalErrorBundle bundle)+ where+ showIncludeFilepath path = "in file included from " <> path <> ",\n"++-- | Attach a filepath and source text to a "final" parse error so that it can be pretty-printed.+-- You must ensure that you provide the appropriate source text and filepath.+attachSource :: FilePath -> Text -> FinalParseError' e -> FinalParseErrorBundle' e+attachSource filePath sourceText finalParseError = case finalParseError of++ -- A parse error thrown directly with the 'FinalError' constructor+ -- requires both source and filepath.+ FinalError err ->+ let bundle = ParseErrorBundle+ { bundleErrors = err NE.:| []+ , bundlePosState = initialPosState filePath sourceText }+ in FinalParseErrorBundle'+ { finalErrorBundle = Right bundle+ , includeFileStack = [] }++ -- A 'ParseErrorBundle' already has the appropriate source and filepath+ -- and so needs neither.+ FinalBundle peBundle -> FinalParseErrorBundle'+ { finalErrorBundle = Right peBundle+ , includeFileStack = [] }++ -- A parse error from a 'FinalParseErrorBundle' was thrown from an+ -- include file, so we add the filepath to the stack.+ FinalBundleWithStack fpeBundle -> fpeBundle+ { includeFileStack = filePath : includeFileStack fpeBundle }++ -- A complete error message needs neither source nor filepath.+ FinalMessage msg -> FinalParseErrorBundle'+ { finalErrorBundle = Left msg+ , includeFileStack = [] }+++--- * Handling parse errors from include files with "final" parse errors++-- | Parse an include file with the given parser and initial state,+-- discarding the resulting state,+-- and re-throwing any parse errors as final parse errors with the file's info attached.+parseIncludeFile+ :: Monad m+ => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a+ -> st+ -> FilePath+ -> Text+ -> StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a+parseIncludeFile parser initialState filepath text = catchError parser' handler+ where+ parser' = do+ eResult <- lift $ lift $ runParserT (evalStateT parser initialState) filepath text+ case eResult of+ Left parseErrorBundle -> throwError $ FinalBundle parseErrorBundle+ Right result -> pure result+ -- Attach source and filepath of the include file to its parse errors+ handler e = throwError $ FinalBundleWithStack $ attachSource filepath text e+++--- * Helpers++-- | Like megaparsec's 'initialState', but instead for 'PosState'.+-- Used when constructing 'ParseErrorBundle's.+-- The values for "tab width" and "line prefix" are taken from 'initialState'.+initialPosState :: FilePath -> Text -> PosState Text+initialPosState filePath sourceText = PosState+ { pstateInput = sourceText+ , pstateOffset = 0+ , pstateSourcePos = initialPos filePath+ , pstateTabWidth = defaultTabWidth+ , pstateLinePrefix = "" }
+ Hledger/Utils/Regex.hs view
@@ -0,0 +1,315 @@+{-|++Easy regular expression helpers, currently based on regex-tdfa. These should:++- be cross-platform, not requiring C libraries++- support unicode++- support extended regular expressions++- support replacement, with backreferences etc.++- support splitting++- have mnemonic names++- have simple monomorphic types++- work with simple strings++Regex strings are automatically compiled into regular expressions the first+time they are seen, and these are cached. If you use a huge number of unique+regular expressions this might lead to increased memory usage. Several+functions have memoised variants (*Memo), which also trade space for time.++Currently two APIs are provided:++- The old partial one (with ' suffixes') which will call error on any problem+ (eg with malformed regexps). This comes from hledger's origin as a+ command-line tool.++- The new total one which will return an error message. This is better for+ long-running apps like hledger-web.++Current limitations:++- (?i) and similar are not supported++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Hledger.Utils.Regex (+ -- * Regexp type and constructors+ Regexp(reString)+ ,toRegex+ ,toRegexCI+ ,toRegex'+ ,toRegexCI'+ ,regexEscape+ -- * type aliases+ ,Replacement+ ,RegexError+ -- * total regex operations+ ,regexMatch+ ,regexMatchText+ ,regexMatchTextGroups+ ,regexReplace+ ,regexReplaceUnmemo+ ,regexReplaceAllBy+ )+where++import Control.DeepSeq (NFData(..), rwhnf)+import Control.Monad (foldM)+import Data.Aeson (ToJSON(..), Value(String))+import Data.Array (Array, (!), elems, indices)+import Data.Char (isDigit)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.MemoUgly (memo)+import Data.Text (Text)+import Data.Text qualified as T+import Text.Regex.TDFA (+ Regex, CompOption(..), defaultCompOpt, defaultExecOpt,+ makeRegexOptsM, AllMatches(getAllMatches), match, MatchArray,+ RegexLike(..), RegexMaker(..), RegexOptions(..), RegexContext(..)+ )+++-- | Regular expression. Extended regular expression-ish syntax ? But does not support eg (?i) syntax.+data Regexp+ = Regexp { reString :: Text, reCompiled :: Regex }+ | RegexpCI { reString :: Text, reCompiled :: Regex }++instance Eq Regexp where+ Regexp s1 _ == Regexp s2 _ = s1 == s2+ RegexpCI s1 _ == RegexpCI s2 _ = s1 == s2+ _ == _ = False++instance Ord Regexp where+ Regexp s1 _ `compare` Regexp s2 _ = s1 `compare` s2+ RegexpCI s1 _ `compare` RegexpCI s2 _ = s1 `compare` s2+ Regexp _ _ `compare` RegexpCI _ _ = LT+ RegexpCI _ _ `compare` Regexp _ _ = GT++instance Show Regexp where+ showsPrec d r = showParen (d > app_prec) $ reCons . showsPrec (app_prec+1) (T.unpack $ reString r)+ where app_prec = 10+ reCons = case r of Regexp _ _ -> showString "Regexp "+ RegexpCI _ _ -> showString "RegexpCI "++instance Read Regexp where+ readsPrec d r = readParen (d > app_prec) (\r' -> [(toRegexCI' m,t) |+ ("RegexCI",s) <- lex r',+ (m,t) <- readsPrec (app_prec+1) s]) r+ ++ readParen (d > app_prec) (\r' -> [(toRegex' m, t) |+ ("Regex",s) <- lex r',+ (m,t) <- readsPrec (app_prec+1) s]) r+ where app_prec = 10++instance ToJSON Regexp where+ toJSON (Regexp s _) = String $ "Regexp " <> s+ toJSON (RegexpCI s _) = String $ "RegexpCI " <> s++instance RegexLike Regexp String where+ matchOnce = matchOnce . reCompiled+ matchAll = matchAll . reCompiled+ matchCount = matchCount . reCompiled+ matchTest = matchTest . reCompiled+ matchAllText = matchAllText . reCompiled+ matchOnceText = matchOnceText . reCompiled++instance RegexContext Regexp String String where+ match = match . reCompiled+ matchM = matchM . reCompiled++instance NFData Regexp where rnf = rwhnf++-- Convert a Regexp string to a compiled Regex, or return an error message.+-- (This compiles from a String; regex-tdfa can compile from Text too, since 1.3.1,+-- but compilation is memoised, so unpacking costs little.)+toRegex :: Text -> Either RegexError Regexp+toRegex = memo $ \s -> mkRegexErr s (Regexp s <$> makeRegexM (T.unpack s))++-- Like toRegex, but make a case-insensitive Regex.+toRegexCI :: Text -> Either RegexError Regexp+toRegexCI = memo $ \s -> mkRegexErr s (RegexpCI s <$> makeRegexOptsM defaultCompOpt{caseSensitive=False} defaultExecOpt (T.unpack s))++-- | Make a nice error message for a regexp error.+mkRegexErr :: Text -> Maybe a -> Either RegexError a+mkRegexErr s = maybe (Left errmsg) Right+ where errmsg = T.unpack $ "This regular expression is invalid or unsupported, please correct it: " <> s++-- Convert a Regexp string to a compiled Regex, throw an error+toRegex' :: Text -> Regexp+toRegex' = either errorWithoutStackTrace id . toRegex++-- Like toRegex', but make a case-insensitive Regex.+toRegexCI' :: Text -> Regexp+toRegexCI' = either errorWithoutStackTrace id . toRegexCI++-- | Escape POSIX extended regex metacharacters in a text so the result+-- matches the input as a literal. Eg @regexEscape "U$"@ produces @"U\\$"@,+-- which compiled as a regex matches only the two-character string @U$@.+regexEscape :: Text -> Text+regexEscape = T.concatMap esc+ where+ esc c | c `elem` ("\\.^$*+?()[]{}|" :: String) = T.pack ['\\', c]+ | otherwise = T.singleton c++-- | A replacement pattern. May include numeric backreferences (\N).+type Replacement = String++-- | An error message arising during a regular expression operation.+-- Eg: trying to compile a malformed regular expression, or+-- trying to apply a malformed replacement pattern.+type RegexError = String++-- helpers++-- | Test whether a Regexp matches a String. This is an alias for `matchTest` for consistent+-- naming.+regexMatch :: Regexp -> String -> Bool+regexMatch = matchTest++-- | Tests whether a Regexp matches a Text.+--+-- This unpacks the Text to a String, which measured about 10% faster than matching+-- the Text directly (regex-tdfa 1.3.2.6, 2026-11). regex-tdfa's issue #9, a large slowdown+-- with Text, was about extracting match text (as regexMatchTextGroups does), not this test.+regexMatchText :: Regexp -> Text -> Bool+regexMatchText r = matchTest r . T.unpack++-- | Return a (possibly empty) list of match groups derived by applying the+-- Regex to a Text.+regexMatchTextGroups :: Regexp -> Text -> [Text]+regexMatchTextGroups r txt = let+ pat = reCompiled r+ (_,_,_,matches) = match pat txt :: (Text,Text,Text,[Text])+ in matches++--------------------------------------------------------------------------------+-- new total functions++-- | A memoising version of regexReplace. Caches the result for each+-- search pattern, replacement pattern, target string tuple.+-- This won't generate a regular expression parsing error since that+-- is pre-compiled nowadays, but there can still be a runtime error +-- from the replacement pattern, eg with a backreference referring +-- to a nonexistent match group.+regexReplace :: Regexp -> Replacement -> String -> Either RegexError String+regexReplace re repl = memo $ regexReplaceUnmemo re repl++-- helpers:++-- Replace this regular expression with this replacement pattern in this+-- string, or return an error message. (There should be no regexp+-- parsing errors these days since Regexp's compiled form is used,+-- but there can still be a runtime error from the replacement+-- pattern, eg a backreference referring to a nonexistent match group.)+--+-- This takes time linear in the length of the string: it makes one pass,+-- left to right, and takes match group texts from the part of the string+-- being processed (not from the start, as MatchText would).+--+-- >>> regexReplaceUnmemo (toRegex' "a") "b" "banana"+-- Right "bbnbnb"+-- >>> regexReplaceUnmemo (toRegex' "([0-9]+)-([0-9]+)") "\\2/\\1" "x 1-2 y 30-40"+-- Right "x 2/1 y 40/30"+-- >>> regexReplaceUnmemo (toRegex' "a(x)?") "[\\1]" "a ax"+-- Right "[] [x]"+-- >>> regexReplaceUnmemo (toRegex' "x*") "-" "abc"+-- Right "-a-b-c-"+-- >>> regexReplaceUnmemo (toRegex' "a") "\\1" "a"+-- Left "no match group exists for backreference \"\\1\""+regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String+regexReplaceUnmemo re repl str =+ foldM replaceMatch (0, str, id) (match (reCompiled re) str :: [MatchArray])+ >>= \(_, rest, prependdone) -> Right $ prependdone rest+ where+ -- Given the position reached in the original string, the rest of the string from there,+ -- and the output so far, replace one match with the replacement text appropriate+ -- for this match. Or return an error message.+ replaceMatch :: (Int, String, String -> String) -> MatchArray -> Either RegexError (Int, String, String -> String)+ replaceMatch (pos, todo, prepend) groups =+ case elems groups of+ [] -> Right (pos, todo, prepend)+ (off,len):_ -> do -- groups should have 0-based indexes, and there should always be at least one, since this is a match+ let (prematch, matchandrest) = splitAt (off - pos) todo+ groupText (goff, glen)+ | goff < 0 = "" -- an optional group that did not participate in the match+ | otherwise = take glen $ drop (goff - off) matchandrest+ -- The replacement text: the replacement pattern with all+ -- numeric backreferences replaced by the appropriate groups+ -- from this match. Or an error message.+ rpl <- regexReplaceAllByM backrefRegex (lookupMatchGroup $ fmap groupText groups) repl+ Right (off + len, drop len matchandrest, prepend . (prematch ++) . (rpl ++))+ -- Given some match groups and a numeric backreference,+ -- return the referenced group text, or an error message.+ lookupMatchGroup :: Array Int String -> String -> Either RegexError String+ lookupMatchGroup grps ('\\':s@(_:_)) | all isDigit s =+ case read s of n | n `elem` indices grps -> Right $ grps ! n -- PARTIAL: should not fail, all digits+ _ -> Left $ "no match group exists for backreference \"\\"++s++"\""+ lookupMatchGroup _ s = Left $ "lookupMatchGroup called on non-numeric-backreference \""++s++"\", shouldn't happen"+ backrefRegex = toRegex' "\\\\[0-9]+" -- PARTIAL: should not fail++-- regexReplace' :: Regexp -> Replacement -> String -> String+-- regexReplace' re repl s =+-- foldl (replaceMatch repl) s (reverse $ match (reCompiled re) s :: [MatchText String])+-- where+-- replaceMatch :: Replacement -> String -> MatchText String -> String+-- replaceMatch replpat s matchgroups = pre ++ repl ++ post+-- where+-- ((_,(off,len)):_) = elems matchgroups -- groups should have 0-based indexes, and there should always be at least one, since this is a match+-- (pre, post') = splitAt off s+-- post = drop len post'+-- repl = regexReplaceAllBy backrefRegex (lookupMatchGroup matchgroups) replpat+-- where+-- lookupMatchGroup :: MatchText String -> String -> String+-- lookupMatchGroup grps ('\\':s@(_:_)) | all isDigit s =+-- case read s of n | n `elem` indices grps -> fst (grps ! n)+-- -- PARTIAL:+-- _ -> error' $ "no match group exists for backreference \"\\"++s++"\""+-- lookupMatchGroup _ s = error' $ "lookupMatchGroup called on non-numeric-backreference \""++s++"\", shouldn't happen"+-- backrefRegex = toRegex' "\\\\[0-9]+" -- PARTIAL: should not fail+++-- helpers++-- adapted from http://stackoverflow.com/questions/9071682/replacement-substition-with-haskell-regex-libraries:++-- Replace all occurrences of a regexp in a string, transforming each match+-- with the given pure function.+regexReplaceAllBy :: Regexp -> (String -> String) -> String -> String+regexReplaceAllBy re transform s = prependdone rest+ where+ (_, rest, prependdone) = foldl' go (0, s, id) matches+ where+ matches = getAllMatches $ match (reCompiled re) s :: [(Int, Int)] -- offset and length+ go :: (Int,String,String->String) -> (Int,Int) -> (Int,String,String->String)+ go (pos,todo,prepend) (off,len) =+ let (prematch, matchandrest) = splitAt (off - pos) todo+ (matched, rest2) = splitAt len matchandrest+ in (off + len, rest2, prepend . (prematch++) . (transform matched ++))++-- Replace all occurrences of a regexp in a string, transforming each match+-- with the given monadic function. Eg if the monad is Either, a Left result+-- from the transform function short-circuits and is returned as the overall+-- result.+regexReplaceAllByM :: forall m. Monad m => Regexp -> (String -> m String) -> String -> m String+regexReplaceAllByM re transform s =+ foldM go (0, s, id) matches >>= \(_, rest, prependdone) -> pure $ prependdone rest+ where+ matches = getAllMatches $ match (reCompiled re) s :: [(Int, Int)] -- offset and length+ go :: (Int,String,String->String) -> (Int,Int) -> m (Int,String,String->String)+ go (pos,todo,prepend) (off,len) =+ let (prematch, matchandrest) = splitAt (off - pos) todo+ (matched, rest) = splitAt len matchandrest+ in transform matched >>= \matched' -> pure (off + len, rest, prepend . (prematch++) . (matched' ++))
+ Hledger/Utils/String.hs view
@@ -0,0 +1,301 @@+-- | String formatting helpers, starting to get a bit out of control.++module Hledger.Utils.String (+ takeEnd,+ -- * misc+ capitalise,+ lowercase,+ uppercase,+ underline,+ stripbrackets,+ -- quoting+ quoteIfNeeded,+ singleQuoteIfNeeded,+ shellQuoteIfNeeded,+ quoteForCommandLine,+ -- quotechars,+ -- whitespacechars,+ words',+ wordsmay,+ wordsEither,+ stripQuotes,+ isSingleQuoted,+ isDoubleQuoted,+ stripAnsi,+ -- * single-line layout+ strip,+ lstrip,+ rstrip,+ strip1Char,+ stripBy,+ strip1By,+ chomp,+ chomp1,+ singleline,+ elideLeft,+ elideRight,+ formatString,+ -- * wide-character-aware layout+ charWidth,+ strWidth,+ strWidthAnsi,+ takeWidth,+ ) where+++import Data.Char (isSpace, toLower, toUpper)+import Data.List (intercalate, dropWhileEnd)+import Data.Text qualified as T+import System.Info (os)+import Safe (headErr, tailErr)+import Text.Megaparsec (between, choice, errorBundlePretty, many, noneOf, sepBy, some)+import Text.Megaparsec.Char (char)+import Text.Printf (printf)++import Hledger.Utils.Parse+import Hledger.Utils.Regex (toRegex', regexReplace)+import Text.DocLayout (charWidth, realLength)+++-- | Take elements from the end of a list.+takeEnd n l = go (drop n l) l+ where+ go (_:xs) (_:ys) = go xs ys+ go [] r = r+ go _ [] = []++capitalise :: String -> String+capitalise (c:cs) = toUpper c : cs+capitalise s = s++lowercase, uppercase :: String -> String+lowercase = map toLower+uppercase = map toUpper++-- | Remove leading and trailing whitespace.+strip :: String -> String+strip = lstrip . rstrip++-- | Remove leading whitespace.+lstrip :: String -> String+lstrip = dropWhile isSpace++-- | Remove trailing whitespace.+rstrip :: String -> String+rstrip = reverse . lstrip . reverse++-- | Strip the given starting and ending character+-- from the start and end of a string if both are present.+strip1Char :: Char -> Char -> String -> String+strip1Char b e s = case s of+ (c:cs) | c==b, not $ null cs, last cs==e -> init cs+ _ -> s++-- | Strip a run of zero or more characters matching the predicate+-- from the start and end of a string.+stripBy :: (Char -> Bool) -> String -> String+stripBy f = dropWhileEnd f . dropWhile f++-- | Strip a single balanced enclosing pair of a character matching the predicate+-- from the start and end of a string.+strip1By :: (Char -> Bool) -> String -> String+strip1By f s = case s of+ (c:cs) | f c, not $ null cs, last cs==c -> init cs+ _ -> s++-- | Remove all trailing newlines/carriage returns.+chomp :: String -> String+chomp = reverse . dropWhile (`elem` "\r\n") . reverse++-- | Remove all trailing newline/carriage returns, leaving just one trailing newline.+chomp1 :: String -> String+chomp1 = (++"\n") . chomp++-- | Remove consecutive line breaks, replacing them with single space+singleline :: String -> String+singleline = unwords . filter (/="") . (map strip) . lines++stripbrackets :: String -> String+stripbrackets = dropWhile (`elem` "([") . reverse . dropWhile (`elem` "])") . reverse :: String -> String++elideLeft :: Int -> String -> String+elideLeft width s =+ if length s > width then ".." ++ takeEnd (width - 2) s else s++elideRight :: Int -> String -> String+elideRight width s =+ if length s > width then take (width - 2) s ++ ".." else s++-- | Clip and pad a string to a minimum & maximum width, and/or left/right justify it.+-- Works on multi-line strings too (but will rewrite non-unix line endings).+formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String+formatString leftJustified minwidth maxwidth s = intercalate "\n" $ map (printf fmt) $ lines s+ where+ justify = if leftJustified then "-" else ""+ minwidth' = maybe "" show minwidth+ maxwidth' = maybe "" (("."++).show) maxwidth+ fmt = "%" ++ justify ++ minwidth' ++ maxwidth' ++ "s"++underline :: String -> String+underline s = s' ++ replicate (length s) '-' ++ "\n"+ where s'+ | last s == '\n' = s+ | otherwise = s ++ "\n"++-- | Double-quote this string if it contains whitespace, single quotes+-- or double-quotes, escaping the quotes as needed.+quoteIfNeeded :: String -> String+quoteIfNeeded s | any (`elem` s) (quotechars++whitespacechars++redirectchars) = showChar '"' $ escapeQuotes s "\""+ | otherwise = s+ where+ escapeQuotes [] x = x+ escapeQuotes ('"':cs) x = showString "\\\"" $ escapeQuotes cs x+ escapeQuotes (c:cs) x = showChar c $ escapeQuotes cs x++-- | Single-quote this string if it contains whitespace or double-quotes.+-- Does not work for strings containing single quotes.+singleQuoteIfNeeded :: String -> String+singleQuoteIfNeeded s | any (`elem` s) (quotechars++whitespacechars) = singleQuote s+ | otherwise = s++-- | Prepend and append single quotes to a string.+singleQuote :: String -> String+singleQuote s = "'"++s++"'"++-- | Quote a string if needed for use as one argument in a shell command line+-- on the current platform. Uses double-quote escaping on Windows (cmd.exe does+-- not recognise single quotes as a quoting character); elsewhere uses single+-- quotes, which are literal in POSIX shells. Use this whenever interpolating+-- a path or other string into a command that will be passed to+-- 'System.Process.runCommand', 'System.Process.callCommand', or+-- 'System.Process.shell'.+shellQuoteIfNeeded :: String -> String+shellQuoteIfNeeded+ | os == "mingw32" = quoteIfNeeded+ | otherwise = singleQuoteIfNeeded++-- | Try to single- and backslash-quote a string as needed to make it usable+-- as an argument on a (sh/bash) shell command line. At least, well enough +-- to handle common currency symbols, like $. Probably broken in many ways.+--+-- >>> quoteForCommandLine "a"+-- "a"+-- >>> quoteForCommandLine "\""+-- "'\"'"+-- >>> quoteForCommandLine "$"+-- "'$'"+-- >>> quoteForCommandLine "it's"+-- "'it'\\''s'"+--+quoteForCommandLine :: String -> String+quoteForCommandLine s+ | null s = "''" -- an empty argument must be quoted, or it vanishes from the command line+ | any (`elem` s) (quotechars++whitespacechars++shellchars) = singleQuote $ escapeSingleQuotes s+ | otherwise = s++-- | Escape single quotes appearing in a string we're protecting by wrapping in single quotes.+-- A backslash is not an escape inside single quotes in POSIX sh, so the quote has to be+-- closed, the apostrophe emitted separately, and the quote reopened: 'it'\\''s'.+escapeSingleQuotes :: String -> String+escapeSingleQuotes = concatMap escapeSingleQuote+ where+ escapeSingleQuote c | c `elem` "'" = "'\\''"+ escapeSingleQuote c = [c]++quotechars, whitespacechars, redirectchars, shellchars :: [Char]+quotechars = "'\""+whitespacechars = " \t\n\r"+redirectchars = "<>"+shellchars = "<>(){}[]$&?#!~`*+\\"++-- | Quote-aware version of words, splitting a string into words like the+-- shell does: spaces inside single or double quotes don't split, quotes enclosing+-- a word are removed, and a word can mix unquoted and quoted parts+-- (so date:'1 to 15' is the single word date:1 to 15).+-- Can raise an error if parsing fails (eg if there's an unclosed quote);+-- wordsmay and wordsEither are total versions.+--+-- >>> words' "a b"+-- ["a","b"]+-- >>> words' "'a b' c"+-- ["a b","c"]+-- >>> words' "date:'1 to 15' x"+-- ["date:1 to 15","x"]+-- >>> words' "\"it's\""+-- ["it's"]+-- >>> words' "a '' b"+-- ["a","","b"]+-- >>> wordsmay "an unclosed 'quote"+-- Nothing+words' :: String -> [String]+words' "" = []+words' s = fromparse $ parsewithString wordsp s -- PARTIAL++-- | Like words', but return Nothing if parsing fails+-- (eg because of an unclosed quote), rather than raising an error.+wordsmay :: String -> Maybe [String]+wordsmay = either (const Nothing) Just . wordsEither++-- | Like words', but on failure (eg because of an unclosed quote) return+-- a pretty error message, showing the position and the problem, instead of+-- raising an error.+wordsEither :: String -> Either String [String]+wordsEither "" = Right []+wordsEither s = either (Left . errorBundlePretty) Right $ parsewithString wordsp s++wordsp :: SimpleStringParser [String]+wordsp = wordp `sepBy` skipNonNewlineSpaces1+ -- eof+ where+ wordp = concat <$> many segmentp+ segmentp = choice+ [ between (char '\'') (char '\'') (many $ noneOf "'")+ , between (char '"') (char '"') (many $ noneOf "\"")+ , some $ noneOf $ quotechars <> whitespacechars+ ]++-- | Strip one matching pair of single or double quotes on the ends of a string.+stripQuotes :: String -> String+stripQuotes s = if isSingleQuoted s || isDoubleQuoted s then init $ tailErr s else s -- PARTIAL tailErr won't fail because isDoubleQuoted++isSingleQuoted :: String -> Bool+isSingleQuoted s@(_:_:_) = headErr s == '\'' && last s == '\'' -- PARTIAL headErr, last will succeed because of pattern+isSingleQuoted _ = False++isDoubleQuoted :: String -> Bool+isDoubleQuoted s@(_:_:_) = headErr s == '"' && last s == '"' -- PARTIAL headErr, last will succeed because of pattern+isDoubleQuoted _ = False++-- Functions below treat wide (eg CJK) characters as double-width.++-- | Double-width-character-aware string truncation. Take as many+-- characters as possible from a string without exceeding the+-- specified width. Eg takeWidth 3 "りんご" = "り".+takeWidth :: Int -> String -> String+takeWidth _ "" = ""+takeWidth 0 _ = ""+takeWidth w (c:cs) | cw <= w = c:takeWidth (w-cw) cs+ | otherwise = ""+ where cw = charWidth c++-- | Like strWidth, but also strips ANSI escape sequences before+-- calculating the width.+--+-- This is no longer used in code, as widths are calculated before+-- adding ANSI escape sequences, but is being kept around for now.+strWidthAnsi :: String -> Int+strWidthAnsi = strWidth . stripAnsi++-- | Alias for 'realLength'.+strWidth :: String -> Int+strWidth = realLength++-- | Strip ANSI escape sequences from a string.+--+-- >>> stripAnsi "\ESC[31m-1\ESC[m"+-- "-1"+stripAnsi :: String -> String+stripAnsi s = either err id $ regexReplace ansire "" s+ where+ err = errorWithoutStackTrace "stripAnsi: invalid replacement pattern" -- PARTIAL, shouldn't happen+ ansire = toRegex' $ T.pack "\ESC\\[([0-9]+;)*([0-9]+)?[ABCDHJKfmsu]" -- PARTIAL, should succeed
+ Hledger/Utils/Test.hs view
@@ -0,0 +1,150 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Hledger.Utils.Test (+ module Test.Tasty+ ,module Test.Tasty.HUnit+ -- ,module QC+ -- ,module SC+ ,assertLeft+ ,assertRight+ ,assertParse+ ,assertParseEq+ ,assertParseEqOn+ ,assertParseError+ ,assertParseE+ ,assertParseEqE+ ,assertParseErrorE+ ,assertParseStateOn+)+where++import Control.Monad (unless)+import Control.Monad.Except (ExceptT(..), liftEither, runExceptT, withExceptT)+import Control.Monad.State.Strict (StateT, evalStateT, execStateT)+import Data.Default (Default(..))+import Data.List (isInfixOf)+import Data.Text qualified as T+import Test.Tasty hiding (defaultMain)+import Test.Tasty.HUnit+-- import Test.Tasty.QuickCheck as QC+-- import Test.Tasty.SmallCheck as SC+import Text.Megaparsec++import Hledger.Utils.IO (pshow)+import Hledger.Utils.Parse+ ( HledgerParseErrorData,+ FinalParseError,+ attachSource,+ customErrorBundlePretty,+ finalErrorBundlePretty,+ )++-- * tasty helpers++-- TODO: pretty-print values in failure messages++-- | Assert any Left value.+assertLeft :: (HasCallStack, Eq b, Show b) => Either a b -> Assertion+assertLeft (Left _) = return ()+assertLeft (Right b) = assertFailure $ "expected Left, got (Right " ++ show b ++ ")"++-- | Assert any Right value.+assertRight :: (HasCallStack, Eq a, Show a) => Either a b -> Assertion+assertRight (Right _) = return ()+assertRight (Left a) = assertFailure $ "expected Right, got (Left " ++ show a ++ ")"++-- | Run a parser on the given text and display a helpful error.+parseHelper :: (HasCallStack, Default st, Monad m) =>+ StateT st (ParsecT HledgerParseErrorData T.Text m) a -> T.Text -> ExceptT String m a+parseHelper parser input =+ withExceptT (\e -> "\nparse error at " ++ customErrorBundlePretty e ++ "\n") . ExceptT+ $ runParserT (evalStateT (parser <* eof) def) "" input++-- | Run a stateful parser in IO and process either a failure or success to+-- produce an 'Assertion'. Suitable for hledger's JournalParser parsers.+assertParseHelper :: (HasCallStack, Default st) =>+ (String -> Assertion) -> (a -> Assertion)+ -> StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text+ -> Assertion+assertParseHelper onFailure onSuccess parser input =+ either onFailure onSuccess =<< runExceptT (parseHelper parser input)++-- | Assert that this stateful parser runnable in IO successfully parses+-- all of the given input text, showing the parse error if it fails.+-- Suitable for hledger's JournalParser parsers.+assertParse :: (HasCallStack, Default st) =>+ StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text -> Assertion+assertParse = assertParseHelper assertFailure (const $ return ())++-- | Assert a parser produces an expected value.+assertParseEq :: (HasCallStack, Eq a, Show a, Default st) =>+ StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text -> a -> Assertion+assertParseEq parser input = assertParseEqOn parser input id++-- | Like assertParseEq, but transform the parse result with the given function+-- before comparing it.+assertParseEqOn :: (HasCallStack, Eq b, Show b, Default st) =>+ StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text -> (a -> b) -> b -> Assertion+assertParseEqOn parser input f expected =+ assertParseHelper assertFailure (assertEqual "" expected . f) parser input++-- | Assert that this stateful parser runnable in IO fails to parse+-- the given input text, with a parse error containing the given string.+assertParseError :: (HasCallStack, Eq a, Show a, Default st) =>+ StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text -> String -> Assertion+assertParseError parser input errstr = assertParseHelper+ (\e -> unless (errstr `isInfixOf` e) $ assertFailure $ "\nparse error is not as expected:" ++ e)+ (\v -> assertFailure $ "\nparse succeeded unexpectedly, producing:\n" ++ pshow v ++ "\n")+ parser input++-- | Run a stateful parser in IO like assertParse, then assert that the+-- final state (the wrapped state, not megaparsec's internal state),+-- transformed by the given function, matches the given expected value.+assertParseStateOn :: (HasCallStack, Eq b, Show b, Default st) =>+ StateT st (ParsecT HledgerParseErrorData T.Text IO) a -> T.Text -> (st -> b) -> b -> Assertion+assertParseStateOn parser input f expected = do+ es <- runParserT (execStateT (parser <* eof) def) "" input+ case es of+ Left err -> assertFailure $ (++"\n") $ ("\nparse error at "++) $ customErrorBundlePretty err+ Right s -> assertEqual "" expected $ f s++-- | These "E" variants of the above are suitable for hledger's ErroringJournalParser parsers.+parseHelperE :: (HasCallStack, Default st, Monad m) =>+ StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError m)) a -> T.Text -> ExceptT String m a+parseHelperE parser input = do+ withExceptT (\e -> "\nparse error at " ++ customErrorBundlePretty e ++ "\n") . liftEither+ =<< withExceptT (\e -> "parse error at " ++ finalErrorBundlePretty (attachSource "" input e))+ (runParserT (evalStateT (parser <* eof) def) "" input)++assertParseHelperE :: (HasCallStack, Default st) =>+ (String -> Assertion) -> (a -> Assertion)+ -> StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError IO)) a -> T.Text+ -> Assertion+assertParseHelperE onFailure onSuccess parser input =+ either onFailure onSuccess =<< runExceptT (parseHelperE parser input)++assertParseE+ :: (HasCallStack, Eq a, Show a, Default st)+ => StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError IO)) a -> T.Text -> Assertion+assertParseE = assertParseHelperE assertFailure (const $ return ())++assertParseEqE+ :: (Default st, Eq a, Show a, HasCallStack)+ => StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError IO)) a -> T.Text -> a -> Assertion+assertParseEqE parser input = assertParseEqOnE parser input id++assertParseEqOnE+ :: (HasCallStack, Eq b, Show b, Default st)+ => StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError IO)) a -> T.Text -> (a -> b) -> b -> Assertion+assertParseEqOnE parser input f expected =+ assertParseHelperE assertFailure (assertEqual "" expected . f) parser input++assertParseErrorE+ :: (Default st, Eq a, Show a, HasCallStack)+ => StateT st (ParsecT HledgerParseErrorData T.Text (ExceptT FinalParseError IO)) a -> T.Text -> String -> Assertion+assertParseErrorE parser input errstr = assertParseHelperE+ (\e -> unless (errstr `isInfixOf` e) $ assertFailure $ "\nparse error is not as expected:" ++ e)+ (\v -> assertFailure $ "\nparse succeeded unexpectedly, producing:\n" ++ pshow v ++ "\n")+ parser input
+ Hledger/Utils/Text.hs view
@@ -0,0 +1,308 @@+-- | Text formatting helpers, ported from String as needed.+-- There may be better alternatives out there.++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Utils.Text+ (+ -- * misc+ textCapitalise,+ -- underline,+ -- stripbrackets,+ textUnbracket,+ wrap,+ textChomp,+ -- quoting+ quoteIfSpaced,+ quoteForQuery,+ textQuoteIfNeeded,+ -- singleQuoteIfNeeded,+ -- quotechars,+ -- whitespacechars,+ escapeDoubleQuotes,+ escapeBackslash,+ -- escapeSingleQuotes,+ -- escapeQuotes,+ -- words',+ textStripQuotes,+ -- textIsSingleQuoted,+ -- textIsDoubleQuoted,+ -- * single-line layout+ -- elideLeft,+ textElideRight,+ formatText,+ -- * multi-line layout+ textConcatTopPadded,+ textConcatBottomPadded,+ fitText,+ linesPrepend,+ linesPrepend2,+ unlinesB,+ -- * wide-character-aware layout+ WideBuilder(..),+ wbToText,+ wbFromText,+ wbUnpack,+ textTakeWidth,+ -- * Reading+ readDecimal,+ -- * tests+ tests_Text+ )+where++import Data.Char (digitToInt)+import Data.Default (def)+import Data.Maybe (catMaybes)+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 Text.DocLayout (charWidth, realLength)++import Test.Tasty (testGroup)+import Test.Tasty.HUnit ((@?=), testCase)+import Text.Tabular.AsciiWide+ (Align(..), Header(..), Properties(..), TableOpts(..), renderRow, textCell)+import Text.WideString (WideBuilder(..), wbToText, wbFromText, wbUnpack)+++textCapitalise :: Text -> Text+textCapitalise t = T.toTitle c <> cs where (c,cs) = T.splitAt 1 t++-- stripbrackets :: String -> String+-- stripbrackets = dropWhile (`elem` "([") . reverse . dropWhile (`elem` "])") . reverse :: String -> String++-- elideLeft :: Int -> String -> String+-- elideLeft width s =+-- if length s > width then ".." ++ reverse (take (width - 2) $ reverse s) else s++textElideRight :: Int -> Text -> Text+textElideRight width t =+ if T.length t > width then T.take (width - 2) t <> ".." else t++-- | Wrap a Text with the surrounding Text.+wrap :: Text -> Text -> Text -> Text+wrap start end x = start <> x <> end++-- | Remove trailing newlines/carriage returns.+textChomp :: Text -> Text+textChomp = T.dropWhileEnd (`elem` ['\r', '\n'])++-- | Clip and pad a string to a minimum & maximum width, and/or left/right justify it.+-- Works on multi-line strings too (but will rewrite non-unix line endings).+formatText :: Bool -> Maybe Int -> Maybe Int -> Text -> Text+formatText leftJustified minwidth maxwidth t =+ T.intercalate "\n" . map (pad . clip) $ if T.null t then [""] else T.lines t+ where+ pad = maybe id justify minwidth+ clip = maybe id T.take maxwidth+ justify n = if leftJustified then T.justifyLeft n ' ' else T.justifyRight n ' '++-- underline :: String -> String+-- underline s = s' ++ replicate (length s) '-' ++ "\n"+-- where s'+-- | last s == '\n' = s+-- | otherwise = s ++ "\n"++-- | Wrap a string in double quotes, and \-prefix any embedded single+-- quotes, if it contains whitespace and is not already single- or+-- double-quoted.+quoteIfSpaced :: T.Text -> T.Text+quoteIfSpaced s | textIsSingleQuoted s || textIsDoubleQuoted s = s+ | not $ any (\c -> T.any (==c) s) whitespacechars = s+ | otherwise = textQuoteIfNeeded s++-- | Quote this text for a hledger query, if needed: like quoteIfSpaced,+-- except text containing double quotes (and no single quotes) is+-- wrapped in single quotes, unescaped. The query parser (words'')+-- reads no backslash escapes inside quoted phrases, so the escaped+-- quotes textQuoteIfNeeded writes would not round-trip - eg in a+-- labeled lot subaccount name, {2026-04-03, "0001", $304.25}.+quoteForQuery :: T.Text -> T.Text+quoteForQuery s+ | textIsSingleQuoted s || textIsDoubleQuoted s = s+ | T.any (== '"') s, not (T.any (== '\'') s) = "'" <> s <> "'"+ | otherwise = quoteIfSpaced s++-- -- | Wrap a string in double quotes, and \-prefix any embedded single+-- -- quotes, if it contains whitespace and is not already single- or+-- -- double-quoted.+-- quoteIfSpaced :: String -> String+-- quoteIfSpaced s | textIsSingleQuoted s || textIsDoubleQuoted s = s+-- | not $ any (`elem` s) whitespacechars = s+-- | otherwise = "'"++escapeSingleQuotes s++"'"++-- -- | Double-quote this string if it contains whitespace, single quotes+-- -- or double-quotes, escaping the quotes as needed.+textQuoteIfNeeded :: T.Text -> T.Text+textQuoteIfNeeded s | any (\c -> T.any (==c) s) (quotechars++whitespacechars) = "\"" <> escapeDoubleQuotes s <> "\""+ | otherwise = s++-- -- | Single-quote this string if it contains whitespace or double-quotes.+-- -- No good for strings containing single quotes.+-- singleQuoteIfNeeded :: String -> String+-- singleQuoteIfNeeded s | any (`elem` s) whitespacechars = "'"++s++"'"+-- | otherwise = s++quotechars, whitespacechars :: [Char]+quotechars = "'\""+whitespacechars = " \t\n\r"++escapeDoubleQuotes :: T.Text -> T.Text+escapeDoubleQuotes = T.replace "\"" "\\\""++escapeBackslash :: T.Text -> T.Text+escapeBackslash = T.replace "\\" "\\\\"++-- escapeSingleQuotes :: T.Text -> T.Text+-- escapeSingleQuotes = T.replace "'" "\'"++-- escapeQuotes :: String -> String+-- escapeQuotes = regexReplace "([\"'])" "\\1"++-- -- | Quote-aware version of words - don't split on spaces which are inside quotes.+-- -- NB correctly handles "a'b" but not "''a''". Can raise an error if parsing fails.+-- words' :: String -> [String]+-- words' "" = []+-- words' s = map textStripQuotes $ fromparse $ parsewith p s+-- where+-- p = do ss <- (singleQuotedPattern <|> doubleQuotedPattern <|> pattern) `sepBy` many1 spacenonewline+-- -- eof+-- return ss+-- pattern = many (noneOf whitespacechars)+-- singleQuotedPattern = between (char '\'') (char '\'') (many $ noneOf "'")+-- doubleQuotedPattern = between (char '"') (char '"') (many $ noneOf "\"")++-- | Strip one matching pair of single or double quotes on the ends of a string.+textStripQuotes :: Text -> Text+textStripQuotes s = if textIsSingleQuoted s || textIsDoubleQuoted s then T.init $ T.tail s else s++textIsSingleQuoted :: Text -> Bool+textIsSingleQuoted s =+ T.length s >= 2 && T.head s == '\'' && T.last s == '\''++textIsDoubleQuoted :: Text -> Bool+textIsDoubleQuoted s =+ T.length s >= 2 && T.head s == '"' && T.last s == '"'++-- | Remove all matching pairs of square brackets and parentheses from the text.+textUnbracket :: Text -> Text+textUnbracket s = T.drop stripN $ T.dropEnd stripN s+ where+ matchBracket :: Char -> Maybe Char+ matchBracket '(' = Just ')'+ matchBracket '[' = Just ']'+ matchBracket _ = Nothing++ expectedClosingBrackets = catMaybes $ takeWhile (/= Nothing) $ matchBracket <$> T.unpack s+ stripN = length $ takeWhile (uncurry (==)) $ zip expectedClosingBrackets $ reverse $ T.unpack s++-- | Join several multi-line strings as side-by-side rectangular strings of the same height, top-padded.+-- Treats wide characters as double width.+textConcatTopPadded :: [Text] -> Text+textConcatTopPadded = TL.toStrict . renderRow def{tableBorders=False, borderSpaces=False}+ . Group NoLine . map (Header . textCell BottomLeft)++-- | Join several multi-line strings as side-by-side rectangular strings of the same height, bottom-padded.+-- Treats wide characters as double width.+textConcatBottomPadded :: [Text] -> Text+textConcatBottomPadded = TL.toStrict . renderRow def{tableBorders=False, borderSpaces=False}+ . Group NoLine . map (Header . textCell TopLeft)++-- -- Functions below treat wide (eg CJK) characters as double-width.++-- | General-purpose wide-char-aware single-line text layout function.+-- It can left- or right-pad a short string to a minimum width.+-- It can left- or right-clip a long string to a maximum width, optionally inserting an ellipsis (the third argument).+-- It clips and pads on the right when the fourth argument is true, otherwise on the left.+-- It treats wide characters as double width.+fitText :: Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text+fitText mminwidth mmaxwidth ellipsify rightside = clip . pad+ where+ clip :: Text -> Text+ clip s =+ case mmaxwidth of+ Just w+ | realLength s > max 0 w ->+ if rightside+ then textTakeWidth (w - T.length ellipsis) s <> ellipsis+ else ellipsis <> T.reverse (textTakeWidth (w - T.length ellipsis) $ T.reverse s)+ | otherwise -> s+ where+ ellipsis = if ellipsify then ".." else ""+ Nothing -> s+ pad :: Text -> Text+ pad s =+ case mminwidth of+ Just w+ | sw < w ->+ if rightside+ then s <> T.replicate (w - sw) " "+ else T.replicate (w - sw) " " <> s+ | otherwise -> s+ Nothing -> s+ where sw = realLength s++-- | Double-width-character-aware string truncation. Take as many+-- characters as possible from a string without exceeding the+-- specified width. Eg textTakeWidth 3 "りんご" = "り".+textTakeWidth :: Int -> Text -> Text+textTakeWidth _ "" = ""+textTakeWidth 0 _ = ""+textTakeWidth w t | not (T.null t),+ let c = T.head t,+ let cw = charWidth c,+ cw <= w+ = T.cons c $ textTakeWidth (w-cw) (T.tail t)+ | otherwise = ""++-- | Add a prefix to each line of a string.+linesPrepend :: Text -> Text -> Text+linesPrepend prefix = T.unlines . map (prefix<>) . T.lines++-- | Add a prefix to the first line of a string, +-- and a different prefix to the remaining lines.+linesPrepend2 :: Text -> Text -> Text -> Text+linesPrepend2 prefix1 prefix2 s = T.unlines $ case T.lines s of+ [] -> []+ l:ls -> (prefix1<>l) : map (prefix2<>) ls++-- | Join a list of Text Builders with a newline after each item.+unlinesB :: [TB.Builder] -> TB.Builder+unlinesB = foldMap (<> TB.singleton '\n')++-- | Read a decimal number from a Text. Assumes the input consists only of digit+-- characters.+readDecimal :: Text -> Integer+readDecimal = T.foldl' step 0+ where step a c = a * 10 + toInteger (digitToInt c)+++tests_Text = testGroup "Text" [+ testCase "quoteIfSpaced" $ do+ quoteIfSpaced "a'a" @?= "a'a"+ quoteIfSpaced "a\"a" @?= "a\"a"+ quoteIfSpaced "a a" @?= "\"a a\""+ quoteIfSpaced "mimi's cafe" @?= "\"mimi's cafe\""+ quoteIfSpaced "\"alex\" cafe" @?= "\"\\\"alex\\\" cafe\""+ quoteIfSpaced "le'shan's cafe" @?= "\"le'shan's cafe\""+ quoteIfSpaced "\"be'any's\" cafe" @?= "\"\\\"be'any's\\\" cafe\"",+ testCase "textUnbracket" $ do+ textUnbracket "()" @?= ""+ textUnbracket "(a)" @?= "a"+ textUnbracket "(ab)" @?= "ab"+ textUnbracket "[ab]" @?= "ab"+ textUnbracket "([ab])" @?= "ab"+ textUnbracket "(()b)" @?= "()b"+ textUnbracket "[[]b]" @?= "[]b"+ textUnbracket "[()b]" @?= "()b"+ textUnbracket "[([]())]" @?= "[]()"+ textUnbracket "[([[[()]]])]" @?= ""+ textUnbracket "[([[[(]]])]" @?= "("+ textUnbracket "[([[[)]]])]" @?= ")",+ testCase "fitText" $ do+ fitText Nothing (Just (-2)) True True "" @?= ""+ fitText Nothing (Just 0) True True "" @?= ""+ fitText Nothing (Just 6) True True "Test Text" @?= "Test.."+ ]
− Hledger/Utils/UTF8.hs
@@ -1,87 +0,0 @@-{--From pandoc, slightly extended. Example usage:-- import Prelude hiding (readFile,writeFile,getContents,putStr,putStrLn)- import Hledger.Utils.UTF8 (readFile,writeFile,getContents,putStr,putStrLn)--------------------------------------------------------------------------Copyright (C) 2010 John MacFarlane <jgm@berkeley.edu>--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 2 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, write to the Free Software-Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--}--{- |- Module : Text.Pandoc.UTF8- Copyright : Copyright (C) 2010 John MacFarlane- License : GNU GPL, version 2 or above -- Maintainer : John MacFarlane <jgm@berkeley.edu>- Stability : alpha- Portability : portable--UTF-8 aware string IO functions that will work with GHC 6.10 or 6.12.--}-module Hledger.Utils.UTF8 ( readFile- , writeFile- , appendFile- , getContents- , hGetContents- , putStr- , putStrLn- , hPutStr- , hPutStrLn- )--where-import qualified Data.ByteString.Lazy as B-import Data.ByteString.Lazy.UTF8 (toString, fromString)-import Prelude hiding (readFile, writeFile, appendFile, getContents, putStr, putStrLn)-import System.IO (Handle)-import Control.Monad (liftM)--bom :: B.ByteString-bom = B.pack [0xEF, 0xBB, 0xBF]--stripBOM :: B.ByteString -> B.ByteString-stripBOM s | bom `B.isPrefixOf` s = B.drop 3 s-stripBOM s = s--readFile :: FilePath -> IO String-readFile = liftM (toString . stripBOM) . B.readFile--writeFile :: FilePath -> String -> IO ()-writeFile f = B.writeFile f . fromString--appendFile :: FilePath -> String -> IO ()-appendFile f = B.appendFile f . fromString--getContents :: IO String-getContents = liftM (toString . stripBOM) B.getContents--hGetContents :: Handle -> IO String-hGetContents h = liftM (toString . stripBOM) (B.hGetContents h)--putStr :: String -> IO ()-putStr = B.putStr . fromString--putStrLn :: String -> IO ()-putStrLn = B.putStrLn . fromString--hPutStr :: Handle -> String -> IO ()-hPutStr h = B.hPutStr h . fromString--hPutStrLn :: Handle -> String -> IO ()-hPutStrLn h s = hPutStr h (s ++ "\n")
+ Hledger/Write/Beancount.hs view
@@ -0,0 +1,574 @@+{-|+Helpers for beancount output.+-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Beancount (+ showTransactionBeancount,+ showPriceDirectiveBeancount,+ beancountTransactions,+ beancountRenameAccounts,+ beancountDirectives,+ beancountItemRenderer,+ -- postingsAsLinesBeancount,+ -- postingAsLinesBeancount,+ -- showAccountNameBeancount,+ tagsToBeancountMetadata,+ showBeancountMetadata,+ accountNameToBeancount,+ commodityToBeancount,+ -- beancountTopLevelAccounts,++ -- * Tests+ tests_WriteBeancount+)+where++-- import Prelude hiding (Applicative(..))+import Data.Char+import Data.Default (def)+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.Calendar (fromGregorian)+import Safe (maximumBound)+import Text.DocLayout (realLength)+import Text.Printf+import Text.Tabular.AsciiWide hiding (render)++import Hledger.Utils+import Hledger.Data.Types+import Hledger.Data.AccountName+import Hledger.Data.Amount+import Hledger.Data.Currency (currencySymbolToCode)+import Hledger.Data.Dates (showDate)+import Hledger.Data.Posting (renderCommentLines, showBalanceAssertion, postingIndent, isReal, postingHasTag, conversionPostingTagName)+import Hledger.Data.Transaction (payeeAndNoteFromDescription', transactionMapPostings)+import Hledger.Data.Journal (journalAccountType)+import Hledger.Write.Journal (ItemRenderer(..), journalItemRenderer)+import Data.Function ((&))+import Data.List.Extra (groupOnKey, nubSort)+import Data.Bifunctor (first)+import Data.List (intersperse, sort, sortOn)+import Data.Map qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust)+import Safe (minimumDef)++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++-- | Like showTransaction, but applies various adjustments to produce valid Beancount journal data.+showTransactionBeancount :: Transaction -> Text+showTransactionBeancount t =+ -- https://beancount.github.io/docs/beancount_language_syntax.html+ -- similar to showTransactionHelper, but I haven't bothered with Builder+ T.unlines (map beancountCommentLine $ T.lines $ tprecedingcomment t)+ <> firstline <> nl+ <> foldMap ((<> nl).postingIndent.showBeancountMetadata (Just maxmdnamewidth)) mds+ <> foldMap ((<> nl)) newlinecomments+ <> foldMap ((<> nl)) (postingsAsLinesBeancount $ tpostings t)+ <> nl+ where+ firstline = T.concat [date, status, payee, note, samelinecomment]+ date = showDate $ tdate t+ status = if tstatus t == Pending then " !" else " *"+ (payee,note) =+ case payeeAndNoteFromDescription' $ tdescription t of+ ("","") -> ("", "" )+ ("",n ) -> ("" , wrapq n )+ (p ,"") -> (wrapq p, wrapq "")+ (p ,n ) -> (wrapq p, wrapq n )+ where+ wrapq = wrap " \"" "\"" . escapeDoubleQuotes . escapeBackslash+ mds = tagsToBeancountMetadata $ ttags t+ maxmdnamewidth = maximum' $ map (T.length . fst) mds+ (samelinecomment, newlinecomments) =+ case renderCommentLines (tcomment t) of [] -> ("",[])+ c:cs -> (c,cs)++-- | Prepare transactions for Beancount output: remove virtual postings,+-- and remove conversion postings which are redundant with costs+-- (Beancount doesn't allow both; costs are more useful to it).+-- Assumes at most one cost + conversion postings group per transaction.+beancountTransactions :: [Transaction] -> [Transaction]+beancountTransactions ts =+ [ t{tpostings = filter (\p -> not $ isredundantconvp p) ps}+ | t <- ts+ , let ps = filter isReal $ tpostings t+ , let hascost = any (any (isJust . acost) . amounts . pamount) ps+ , let isredundantconvp p = hascost && postingHasTag conversionPostingTagName p+ ]++-- | Rename accounts for Beancount output, in these transactions' postings and in the journal's+-- account declarations: an account whose top-level name is not one of Beancount's required ones+-- is prefixed with the Beancount top-level account corresponding to its hledger account type,+-- if that is known (declared or inferred). Eg with "account bonds ; type:A", bonds:treasury+-- becomes Assets:bonds:treasury (and then Assets:Bonds:Treasury when rendered).+-- Accounts of unknown type are left unchanged, and will raise an error when rendered.+beancountRenameAccounts :: Journal -> [Transaction] -> (Journal, [Transaction])+beancountRenameAccounts j ts =+ ( j{ jdeclaredaccounts = map (first rename) $ jdeclaredaccounts j+ , jdeclaredaccounttags = M.mapKeys rename $ jdeclaredaccounttags j+ }+ , map (transactionMapPostings $ \p -> p{paccount = rename $ paccount p}) ts+ )+ where+ rename a+ | hasBeancountTopLevelAccount a = a+ | otherwise = maybe a (\t -> beancountTopLevelAccountFor t <> ":" <> a) $ journalAccountType j a++-- | Does this hledger account name's top-level part convert to one of Beancount's required top-level accounts ?+hasBeancountTopLevelAccount :: AccountName -> Bool+hasBeancountTopLevelAccount a = case accountNameComponents a of+ c:_ -> beancountTopLevelComponent c `elem` beancountTopLevelAccounts+ [] -> False++-- | The Beancount top-level account corresponding to a hledger account type.+beancountTopLevelAccountFor :: AccountType -> BeancountAccountName+beancountTopLevelAccountFor t = case t of+ Asset -> "Assets"+ Cash -> "Assets"+ Liability -> "Liabilities"+ Equity -> "Equity"+ Conversion -> "Equity"+ UnrealisedGain -> "Equity"+ Imbalance -> "Equity"+ Revenue -> "Income"+ Gain -> "Income"+ Expense -> "Expenses"++-- | Options and directives for a Beancount export of this journal and these+-- (Beancount-prepared, possibly filtered) transactions:+-- a sample tolerance option (commented out);+-- operating_currency options for the currencies used in costs;+-- commodity directives for declared commodities, with their tags as metadata;+-- open directives for declared and used accounts, each dated on its earliest posting+-- (or the earliest date overall), with account tags as metadata and a lots: tag as booking method;+-- and price directives, sorted by date.+-- Blank lines separate the sections; the result ends with a newline (or is empty if all sections are empty).+beancountDirectives :: Journal -> [Transaction] -> TL.Text+beancountDirectives j ts =+ TL.fromStrict $ T.intercalate "\n" $ filter (not . T.null) [toleranceoptions, operatingcurrencyoptions, commodities, opens, prices]+ where+ -- https://beancount.github.io/docs/precision_tolerances.html#configuration-for-default-tolerances+ toleranceoptions = ";option \"inferred_tolerance_default\" \"*:0.005\"\n"++ -- "A list of currencies that we single out during reporting and create dedicated columns for ...+ -- This is used to indicate the main currencies that you work with in real life"+ -- We use: all currencies used in costs.+ operatingcurrencyoptions = T.unlines+ [ "option \"operating_currency\" \"" <> commodityToBeancount c <> "\"" | c <- costcurrencies ]+ where+ costcurrencies = nubSort [ acommodity $ costAmount c | t <- ts, p <- tpostings t, a <- amounts $ pamount p, Just c <- [acost a] ]+ costAmount (UnitCost a) = a+ costAmount (TotalCost a) = a++ -- The earliest transaction date, or failing that the earliest price date, or an arbitrary early date.+ firstdate = minimumDef (minimumDef (fromGregorian 1900 1 1) $ map pddate pricedirs) $ map tdate ts++ -- "DATE commodity CURRENCY": optional in Beancount, but preserves the declarations and their metadata.+ commodities = T.unlines+ [ withMetadata (showDate firstdate <> " commodity " <> commodityToBeancount c) tags+ | (c, tags) <- M.toList $ M.union (jdeclaredcommoditytags j) (M.map (const []) $ jdeclaredcommodities j)+ ]++ -- "all account names that receive postings to them will eventually have to have+ -- a corresponding Open directive with a date that precedes all transactions posted to the account"+ opens = T.unlines+ [ withMetadata (showDate d <> " open " <> accountNameToBeancount a <> bookingmethod) (filter (not . islotstag) tags)+ | a <- nubSort $ map fst (jdeclaredaccounts j) <> M.keys firstpostingdates+ , let d = fromMaybe firstdate $ M.lookup a firstpostingdates+ , let tags = fromMaybe [] $ M.lookup a $ jdeclaredaccounttags j+ , let bookingmethod = maybe "" (\v -> " \"" <> v <> "\"") $ lookup "lots" $ map (first T.toLower) tags+ ]+ where+ firstpostingdates = M.fromListWith min [ (paccount p, tdate t) | t <- ts, p <- tpostings t ]+ islotstag = (== "lots") . T.toLower . fst++ prices = T.unlines $ map showPriceDirectiveBeancount $ sortOn pddate pricedirs+ pricedirs = jpricedirectives j++ -- A directive line, followed by any tags as indented metadata lines.+ withMetadata line tags = T.intercalate "\n" $ line : map (postingIndent . showBeancountMetadata (Just maxwidth)) mds+ where+ mds = tagsToBeancountMetadata tags+ maxwidth = maximum' $ map (T.length . fst) mds++-- | An item renderer for Beancount output (print --export -O beancount).+-- Transactions are rendered with showTransactionBeancount.+-- Directives are dropped: those with Beancount equivalents are generated by beancountDirectives instead.+-- Comment lines and comment blocks are converted to Beancount (;) comments.+beancountItemRenderer :: ItemRenderer+beancountItemRenderer = (journalItemRenderer showTransactionBeancount)+ { irDirective = const Nothing+ , irComment = beancountCommentLine+ , irCommentBlock = T.unlines . map ("; " <>) . filter (not . T.isPrefixOf "end comment") . drop 1 . T.lines+ }++-- | Convert a journal comment line (starting with ; # or *) to a Beancount comment line (starting with ;).+beancountCommentLine :: Text -> Text+beancountCommentLine l = if ";" `T.isPrefixOf` T.stripStart l then l else "; " <> l++-- | Render a PriceDirective in Beancount format: DATE price COMMODITY AMOUNT+showPriceDirectiveBeancount :: PriceDirective -> Text+showPriceDirectiveBeancount pd =+ showDate (pddate pd)+ <> " price "+ <> commodityToBeancount (pdcommodity pd)+ <> " "+ <> wbToText (showAmountB beancountPriceFmt $ amountToBeancount $ pdamount pd)+ where+ beancountPriceFmt = defaultFmt{ displayZeroCommodity=True, displayForceDecimalMark=True, displayQuotes=False }++nl = "\n"++type BMetadata = Tag++-- https://beancount.github.io/docs/beancount_language_syntax.html#metadata-1+-- | Render a Beancount metadata as a metadata line (without the indentation or newline).+-- If a maximum name length is provided, space will be left after the colon+-- so that successive metadata values will all start at the same column.+showBeancountMetadata :: Maybe Int -> BMetadata -> Text+showBeancountMetadata mmaxnamewidth (n,v) =+ fitText (fmap (+2) mmaxnamewidth) Nothing False True (n <> ": ")+ <> toBeancountMetadataValue v++-- | Make a list of tags ready to be rendered as Beancount metadata:+-- Encode and lengthen names, encode values, and combine repeated tags into one.+-- Metadatas will be sorted by (encoded) name and then value.+tagsToBeancountMetadata :: [Tag] -> [BMetadata]+tagsToBeancountMetadata = sort . map (first toBeancountMetadataName) . uniquifyTags . filter (not.isHiddenTagName.fst)++-- | In a list of tags, replace each tag that appears more than once+-- with a single tag with all of the values combined into one, comma-and-space-separated.+-- This function also sorts all tags by name and then value.+uniquifyTags :: [Tag] -> [Tag]+uniquifyTags ts = [(k, T.intercalate ", " $ map snd $ tags) | (k, tags) <- groupOnKey fst $ sort ts]++toBeancountMetadataName :: TagName -> Text+toBeancountMetadataName name =+ prependStartCharIfNeeded $+ case T.uncons name of+ Nothing -> ""+ Just (c,cs) ->+ T.concatMap (\d -> if isBeancountMetadataNameChar d then T.singleton d else toBeancountMetadataNameChar d) $ T.cons c cs+ where+ -- If the name is empty, make it "mm".+ -- If it has only one character, prepend "m".+ -- If the first character is not a valid one, prepend "m".+ prependStartCharIfNeeded t =+ case T.uncons t of+ Nothing -> T.replicate 2 $ T.singleton beancountMetadataDummyNameStartChar+ Just (c,cs) | T.null cs || not (isBeancountMetadataNameStartChar c) -> T.cons beancountMetadataDummyNameStartChar t+ _ -> t++-- | Is this a valid character to start a Beancount metadata name (lowercase ASCII letter) ?+isBeancountMetadataNameStartChar :: Char -> Bool+isBeancountMetadataNameStartChar = isAsciiLower++-- | Dummy valid starting character to prepend to a Beancount metadata name if needed.+beancountMetadataDummyNameStartChar :: Char+beancountMetadataDummyNameStartChar = 'm'++-- | Is this a valid character in the middle of a Beancount metadata name (a lowercase ASCII letter, digit, _ or -) ?+isBeancountMetadataNameChar :: Char -> Bool+isBeancountMetadataNameChar c = isAsciiLower c || isDigit c || c `elem` ['_', '-']++-- | Convert a character to one or more characters valid inside a Beancount metadata name.+-- ASCII uppercase letters are lowercased, spaces are converted to dashes, and unsupported+-- characters (including non-ASCII letters) are encoded as c<HEXBYTES>.+toBeancountMetadataNameChar :: Char -> Text+toBeancountMetadataNameChar c+ | isBeancountMetadataNameChar c = T.singleton c+ | isAsciiUpper c = T.singleton $ toLower c+ | isSpace c = "-"+ | otherwise = T.pack $ printf "c%x" c++toBeancountMetadataValue :: TagValue -> Text+toBeancountMetadataValue = ("\"" <>) . (<> "\"") . T.concatMap toBeancountMetadataValueChar++-- | Is this a valid character in the middle of a Beancount metadata name (a lowercase letter, digit, _ or -) ?+isBeancountMetadataValueChar :: Char -> Bool+isBeancountMetadataValueChar c = c `notElem` ['"']++-- | Convert a character to one or more characters valid inside a Beancount metadata value:+-- a double quote is encoded as c<HEXBYTES>.+toBeancountMetadataValueChar :: Char -> Text+toBeancountMetadataValueChar c+ | isBeancountMetadataValueChar c = T.singleton c+ | otherwise = T.pack $ printf "c%x" c+++-- | Render a transaction's postings as indented lines, suitable for `print -O beancount` output.+-- See also Posting.postingsAsLines.+postingsAsLinesBeancount :: [Posting] -> [Text]+postingsAsLinesBeancount ps = concatMap first3 linesWithWidths+ where+ linesWithWidths = map (postingAsLinesBeancount False maxacctwidth maxamtwidth) ps+ maxacctwidth = maximumBound 0 $ map second3 linesWithWidths+ maxamtwidth = maximumBound 0 $ map third3 linesWithWidths++-- | Render one posting, on one or more lines, suitable for `print -O beancount` output.+-- Also returns the widths calculated for the account and amount fields.+-- See also Posting.postingAsLines.+postingAsLinesBeancount :: Bool -> Int -> Int -> Posting -> ([Text], Int, Int)+postingAsLinesBeancount elideamount acctwidth amtwidth p =+ (concatMap (++ (map (" "<>) $ metadatalines <> newlinecomments)) postingblocks+ ,thisacctwidth+ ,thisamtwidth+ )+ where+ -- This needs to be converted to strict Text in order to strip trailing+ -- spaces. This adds a small amount of inefficiency, and the only difference+ -- is whether there are trailing spaces in print (and related) reports. This+ -- could be removed and we could just keep everything as a Text Builder, but+ -- would require adding trailing spaces to 42 failing tests.+ postingblocks = [map T.stripEnd . T.lines . TL.toStrict $+ render [ textCell BottomLeft statusandaccount+ , textCell BottomLeft " "+ , Cell BottomLeft [pad amt]+ , textCell BottomLeft samelinecomment+ ]+ | (amt,_assertion) <- shownAmountsAssertions]+ render = renderRow def{tableBorders=False, borderSpaces=False} . Group NoLine . map Header+ pad amt = WideBuilder (TB.fromText $ T.replicate w " ") w <> amt+ where w = max 12 amtwidth - wbWidth amt -- min. 12 for backwards compatibility++ pacct = showAccountNameBeancount Nothing $ paccount p+ pstatusandacct p' = if pstatus p' == Pending then "! " else "" <> pacct++ -- currently prices are considered part of the amount string when right-aligning amounts+ -- Since we will usually be calling this function with the knot tied between+ -- amtwidth and thisamtwidth, make sure thisamtwidth does not depend on+ -- amtwidth at all.+ shownAmounts+ | elideamount = [mempty]+ | otherwise = map addCostBasisAndCost amtParts+ where+ -- render amounts without cost or cost basis; we append them in beancount order (costbasis before cost) below+ basefmt = defaultFmt{ displayZeroCommodity=True, displayForceDecimalMark=True, displayQuotes=False, displayCost=False, displayCostBasis=False }+ costfmt = defaultFmt{ displayZeroCommodity=True, displayForceDecimalMark=True, displayQuotes=False }+ a' = mapMixedAmount amountToBeancount $ pamount p+ -- get the display builders (with costs stripped) paired with the original amounts (with costs intact)+ amtParts = zip (map fst $ showMixedAmountLinesPartsB basefmt a') (amounts a')+ addCostBasisAndCost (builder, amt) =+ builder <> showAmountCostBasisBeancountB costfmt amt <> showAmountCostB costfmt amt+ thisamtwidth = maximumBound 0 $ map wbWidth shownAmounts++ -- when there is a balance assertion, show it only on the last posting line+ shownAmountsAssertions = zip shownAmounts shownAssertions+ where+ shownAssertions = replicate (length shownAmounts - 1) mempty ++ [assertion]+ where+ assertion = maybe mempty ((WideBuilder (TB.singleton ' ') 1 <>).showBalanceAssertion) $ pbalanceassertion p++ -- pad to the maximum account name width, plus 2 to leave room for status flags, to keep amounts aligned+ statusandaccount = postingIndent . fitText (Just $ 2 + acctwidth) Nothing False True $ pstatusandacct p+ thisacctwidth = realLength pacct+ mds = tagsToBeancountMetadata $ filter (tagInComment (pcomment p)) (ptags p)+ tagInComment c (n,_) = case toRegex ("\\b" <> n <> ":") of+ Right r -> regexMatchText r c+ Left _ -> False+ metadatalines = map (postingIndent . showBeancountMetadata (Just maxtagnamewidth)) mds+ where maxtagnamewidth = maximum' $ map (T.length . fst) mds+ (samelinecomment, newlinecomments) =+ case renderCommentLines (pcomment p) of [] -> ("",[])+ c:cs -> (c,cs)++-- | Like showAccountName for Beancount journal format.+-- Calls accountNameToBeancount first.+showAccountNameBeancount :: Maybe Int -> AccountName -> Text+showAccountNameBeancount w = maybe id T.take w . accountNameToBeancount++type BeancountAccountName = AccountName+type BeancountAccountNameComponent = AccountName++-- | Convert a hledger account name to a valid Beancount account name.+-- It replaces spaces and underscores with dashes and other non-supported characters with C<HEXBYTES>;+-- prepends the letter A to any part which doesn't begin with a letter or number;+-- adds a second :A part if there is only one part;+-- and capitalises each part.+-- It also checks that the first part is one of the required english+-- account names Assets, Liabilities, Equity, Income, or Expenses, and if not+-- raises an informative error.+-- Ref: https://beancount.github.io/docs/beancount_language_syntax.html#accounts+accountNameToBeancount :: AccountName -> BeancountAccountName+accountNameToBeancount a = b+ where+ cs1 = case accountNameComponents $ dbg9 "hledger account name " a of+ c:cs -> beancountTopLevelComponent c : map accountNameComponentToBeancount cs+ [] -> []+ cs2 =+ case cs1 of+ c:_ | c `notElem` beancountTopLevelAccounts -> error' e+ where+ e = T.unpack $ T.unlines [+ "bad top-level account: " <> c+ ,"in beancount account name: " <> accountNameFromComponents cs1+ ,"converted from hledger account name: " <> a+ ,"For Beancount, top-level accounts must be one of " <> T.intercalate ", " beancountTopLevelAccounts <> "."+ ,"Declare this account's type (eg: account " <> a <> " ; type:A) so that hledger can add the right one,"+ ,"or use --alias to rename it."+ ]+ [c] -> [c, "A"]+ cs -> cs+ b = dbg9 "beancount account name" $ accountNameFromComponents cs2++-- | Convert a hledger account name's top-level part for Beancount:+-- "revenue" or "revenues" (case insensitive) become "Income", otherwise it is converted like any other part.+beancountTopLevelComponent :: AccountName -> BeancountAccountNameComponent+beancountTopLevelComponent c+ | T.toLower c `elem` ["revenue", "revenues"] = "Income"+ | otherwise = accountNameComponentToBeancount c++accountNameComponentToBeancount :: AccountName -> BeancountAccountNameComponent+accountNameComponentToBeancount acctpart =+ prependStartCharIfNeeded $+ case T.uncons acctpart of+ Nothing -> ""+ Just (c,cs) ->+ textCapitalise $+ T.concatMap (\d -> if isBeancountAccountChar d then (T.singleton d) else T.pack $ charToBeancount d) $ T.cons c cs+ where+ prependStartCharIfNeeded t =+ case T.uncons t of+ Just (c,_) | not $ isBeancountAccountStartChar c -> T.cons beancountAccountDummyStartChar t+ _ -> t++-- | Dummy valid starting character to prepend to Beancount account name parts if needed (A).+beancountAccountDummyStartChar :: Char+beancountAccountDummyStartChar = 'A'++-- | Convert a character which is not valid in a Beancount account name+-- (or commodity name) to one or more valid characters: spaces and underscores,+-- which are the usual hledger word separators, become a dash;+-- anything else is encoded as C<HEXBYTES>.+charToBeancount :: Char -> String+charToBeancount c+ | isSpace c || c == '_' = "-"+ | otherwise = printf "C%x" c++-- XXX these probably allow too much unicode:++-- https://hackage.haskell.org/package/base-4.20.0.1/docs/Data-Char.html#v:isUpperCase would be more correct,+-- but isn't available till base 4.18/ghc 9.6. isUpper is close enough in practice.+isuppercase = isUpper++-- | Is this a valid character to start a Beancount account name part (capital letter or digit) ?+isBeancountAccountStartChar :: Char -> Bool+isBeancountAccountStartChar c = (isLetter c && isuppercase c) || isDigit c++-- | Is this a valid character to appear elsewhere in a Beancount account name part (letter, digit, or -) ?+isBeancountAccountChar :: Char -> Bool+isBeancountAccountChar c = isLetter c || isDigit c || c=='-'++beancountTopLevelAccounts = ["Assets", "Liabilities", "Equity", "Income", "Expenses"]++type BeancountAmount = Amount++-- | Do some best effort adjustments to make an amount that renders+-- in a way that Beancount can read: force the commodity symbol to the right,+-- capitalise all letters, convert a few currency symbols to codes.+amountToBeancount :: Amount -> BeancountAmount+amountToBeancount a@Amount{acommodity=c,astyle=s,acost=mp} = a{acommodity=c', astyle=s', acost=mp'}+ where+ c' = commodityToBeancount c+ s' = s{ascommodityside=R, ascommodityspaced=True}+ mp' = costToBeancount <$> mp+ where+ costToBeancount (TotalCost amt) = TotalCost $ amountToBeancount amt+ costToBeancount (UnitCost amt) = UnitCost $ amountToBeancount amt++-- | Show an amount's cost basis in Beancount lot syntax: {cost, date, label}+-- Returns a WideBuilder with the formatted cost basis, or mempty if there's no cost basis.+showAmountCostBasisBeancountB :: AmountFormat -> Amount -> WideBuilder+showAmountCostBasisBeancountB afmt amt = case acostbasis amt of+ Nothing -> mempty+ Just CostBasis{cbCost=Nothing, cbDate=Nothing, cbLabel=Nothing} ->+ WideBuilder (TB.fromString " {}") 3+ Just CostBasis{cbCost, cbDate, cbLabel} ->+ case parts of+ [] -> mempty+ _ -> WideBuilder (TB.fromString " {") 2 <> contents <> WideBuilder (TB.singleton '}') 1+ where+ parts = catMaybes+ [ fmap (showAmountB afmt . amountToBeancount) cbCost+ , fmap (wbFromText . T.pack . show) cbDate+ , fmap (wbFromText . quote) cbLabel+ ]+ contents = mconcat $ Data.List.intersperse (WideBuilder (TB.fromString ", ") 2) parts+ quote t = "\"" <> t <> "\""++type BeancountCommoditySymbol = CommoditySymbol++-- | Convert a hledger commodity name to a valid Beancount commodity name.+-- That is: 2-24 uppercase letters / digits / apostrophe / period / underscore / dash,+-- starting with a letter, and ending with a letter or digit.+-- Ref: https://beancount.github.io/docs/beancount_language_syntax.html#commodities-currencies+-- So this:+-- replaces common currency symbols with their ISO 4217 currency codes,+-- capitalises all letters,+-- replaces spaces with dashes and other invalid characters with C<HEXBYTES>,+-- prepends a C if the first character is not a letter,+-- appends a C if the last character is not a letter or digit,+-- doubles it if less than 2 characters,+-- and disables hledger's enclosing double quotes.+--+-- >>> commodityToBeancount ""+-- "CC"+-- >>> commodityToBeancount "$"+-- "USD"+-- >>> commodityToBeancount "Usd"+-- "USD"+-- >>> commodityToBeancount "\"a1\""+-- "A1"+-- >>> commodityToBeancount "\"A 1!\""+-- "A-1C21"+-- >>> commodityToBeancount "K"+-- "KK"+--+commodityToBeancount :: CommoditySymbol -> BeancountCommoditySymbol+commodityToBeancount "" = "CC"+commodityToBeancount com =+ dbg9 "beancount commodity name" $+ let com' = textStripQuotes com+ in case currencySymbolToCode com' of+ Just code -> code+ Nothing ->+ com'+ & T.toUpper+ & T.concatMap (\d -> if isBeancountCommodityChar d then T.singleton d else T.pack $ charToBeancount d)+ & fixstart+ & fixend+ & fixshort+ where+ fixstart bcom = case T.uncons bcom of+ Just (c,_) | isBeancountCommodityStartChar c -> bcom+ _ -> "C" <> bcom+ fixend bcom = case T.unsnoc bcom of+ Just (_,c) | isBeancountCommodityEndChar c -> bcom+ _ -> bcom <> "C"+ fixshort bcom+ | T.length bcom < 2 = bcom <> bcom -- e.g. "K" -> "KK"+ | otherwise = bcom++-- | Is this a valid character in the middle of a Beancount commodity name (a capital letter, digit, or '._-) ?+isBeancountCommodityChar :: Char -> Bool+isBeancountCommodityChar c = (isLetter c && isuppercase c) || isDigit c || c `elem` ['\'', '.', '_', '-']++-- | Is this a valid character to start a Beancount commodity name (a capital letter) ?+isBeancountCommodityStartChar :: Char -> Bool+isBeancountCommodityStartChar c = isLetter c && isuppercase c++-- | Is this a valid character to end a Beancount commodity name (a capital letter or digit) ?+isBeancountCommodityEndChar :: Char -> Bool+isBeancountCommodityEndChar c = (isLetter c && isuppercase c) || isDigit c++--- ** tests++tests_WriteBeancount :: TestTree+tests_WriteBeancount = testGroup "Write.Beancount" [+ ]
+ Hledger/Write/Chart.hs view
@@ -0,0 +1,502 @@+{- |+A renderer-independent description of a chart, made from a report.++This is to charts what "Hledger.Write.Spreadsheet" is to tables:+each chart-capable report has an adapter that turns its report data into a 'Chart',+choosing a useful default chart for that report (see doc/SPEC-charts.md, "Smart defaults"),+and renderers turn a 'Chart' into text, SVG, CSV or JSON.++The model carries the report's own display information+(period headings, account display names, commodity display styles, the report title)+so that every renderer labels things exactly as the report's table would.+Signs are already as the report shows them (eg normal-balance flipping done by bs/is/cf).++Values are kept exact here ('Quantity'); renderers convert them to Double only for drawing.+-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Chart (+ Chart(..),+ XAxis(..),+ ChartLabel(..),+ Panel(..),+ BarLayout(..),+ Series(..),+ SeriesRole(..),+ Mark(..),+ Summary(..),+ SummaryKind(..),+ Colour(..),+ seriesColours,+ Colouring(..),+ chartColouring,+ stableSlots,+ stableSlotsFavouringFirst,+ categoryTints,+ seriesSize,+ maxTints,+ mainAccountType,+ SeriesValues,+ isContra,+ isHatched,+ hatchedSeries,+ legendListsSeries,+ seriesValues,+ valueAt,+ setChartScales,+ chartWithoutTotalMarks,+ setChartLayout,+ scaleSpans,+ chartAsCsv,+ tests_Hledger_Write_Chart,+) where++import Control.Applicative ((<|>))+import Data.Bits (shiftR, xor)+import Data.Char (ord)+import Data.List (find, nub, partition, sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe)+import Data.Ord (Down(..))+import Data.Set qualified as S+import Data.Word (Word32)++import Data.Array (Array, bounds, inRange, listArray, (!))++import Data.Aeson (ToJSON)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time (Day)+import GHC.Generics (Generic)++import Hledger.Data.Amount (AmountFormat(..), machineFmt, nullamt, showAmountWith)+import Hledger.Data.Dates (showDate)+import Hledger.Data.Json ()+import Hledger.Data.AccountType (isAccountSubtypeOf)+import Hledger.Data.Types (AccountType(..), Amount(..), DateSpan(..), Quantity)+import Hledger.Utils.Test+import Hledger.Write.Csv (CSV)+++-- | A chart: a title, an x axis, and one or more panels drawn against that x axis.+-- Typically there is one panel per commodity.+-- A chart with no panels, or whose panels have no series, has no data; renderers should say so, not fail.+data Chart = Chart+ { chTitle :: Text -- ^ the report's title, as its table would show it (may be empty)+ , chXAxis :: XAxis -- ^ the x positions, shared by all panels+ , chPanels :: [Panel] -- ^ the panels, in display order (eg largest commodity first)+ , chNotes :: [Text] -- ^ notes to show below the chart, eg about what its values leave out+ } deriving (Show, Eq, Generic, ToJSON)++-- | The x positions of a chart: what each value in a series corresponds to.+-- Every series in the chart has one value per x position (renderers must not assume this, and should ignore extras).+--+-- Renderers choose orientation from this: periods and dates are drawn along a horizontal time axis in SVG,+-- categories as horizontal bars. Text charts always draw one row per x position.+data XAxis+ = XCategories [ChartLabel] -- ^ unordered categories, eg the accounts of a single-period balance report+ | XPeriods [(DateSpan, Text)] -- ^ consecutive report periods, each with its heading as the report's table shows it+ | XDates [Day] -- ^ individual dates, possibly irregular and repeated, eg one per transaction in a register+ deriving (Show, Eq, Generic, ToJSON)++-- | A name for a category or a series.+-- For accounts this comes from the report's display name, so it follows the report's tree/flat mode and depth.+data ChartLabel = ChartLabel+ { lbFull :: Text -- ^ the full name, eg a full account name; used in CSV/JSON and tooltips+ , lbShort :: Text -- ^ the name to display, eg a leaf account name in tree mode+ , lbIndent :: Int -- ^ indentation level to display it with (0 for none)+ , lbType :: Maybe AccountType -- ^ the account type, if this names an account (or accounts) of a known type;+ -- charts colour accounts by their main type (see 'seriesColours')+ , lbAccount :: Bool -- ^ does this name an account (or accounts) ? Otherwise it's something else, eg a total.+ , lbTipLines :: [Text] -- ^ more lines for tooltips, eg the accounts that an "other" series combines+ } deriving (Show, Eq, Generic, ToJSON)++-- | One chart area with its own y axis, holding series of values in a single unit.+data Panel = Panel+ { pnUnit :: Amount -- ^ the unit of all values in this panel, as a template amount whose quantity is ignored:+ -- its commodity symbol and display style are used to show values and axis ticks.+ -- Eg a currency, @%@ (as produced by --percent), or no commodity with precision 0 for counts.+ , pnSeries :: [Series] -- ^ the series, in display order (legend order)+ , pnGroupNames :: [Text] -- ^ names for the groups of series, by group number (see 'seGroup'), if they have names;+ -- eg a compound report's section titles. Text charts show them.+ , pnScale :: Maybe Quantity -- ^ a fixed scale, if one was requested: the amount spanned by the chart (see 'scaleSpans'),+ -- so that charts with the same scale are drawn at the same size per amount.+ -- Otherwise the chart is scaled to fit its values.+ , pnLayout :: BarLayout -- ^ how to draw bars of several groups+ , pnCounts :: Bool -- ^ are the values counts of whole things (eg postings) ? Then text charts draw at most one cell per unit,+ -- so that small counts are not magnified (unless a fixed scale is set).+ , pnSummary :: [Summary] -- ^ values summarising the whole chart, shown below it (eg with -T and -A, the total and the average per period)+ , pnValueLabels :: [Maybe Text] -- ^ text to show at each x position (or none there), eg a holding's gain percent:+ -- in graphical charts instead of its value (which the axis shows), in a smaller font+ -- (over time, only if they all fit); in text charts after it.+ -- Text beginning with + is shown in the revenue colour; with -, in the expense colour+ -- in graphical charts, the negative style in text charts.+ -- If empty, the values are shown as usual+ } deriving (Show, Eq, Generic, ToJSON)++-- | A value summarising a panel's values over the whole x axis, such as their total or their average.+data Summary = Summary+ { suKind :: SummaryKind+ , suLabel :: Text -- ^ its name, as the report's table would show it (eg "Total", "Average")+ , suValue :: Amount -- ^ its value, with its own display style (eg an average of counts has a decimal place)+ } deriving (Show, Eq, Generic, ToJSON)++data SummaryKind+ = SummaryTotal -- ^ the total of all x positions' values+ | SummaryAverage -- ^ the average per x position, which SVG charts also draw as a line across the plot (with a legend entry)+ deriving (Show, Eq, Generic, ToJSON)++-- | How to draw the bars of a panel whose series are in several groups (eg a compound report's sections).+data BarLayout+ = Diverging -- ^ all groups stacked in one bar at each x position, positive values above (or right of) zero and negative ones below+ | Grouped -- ^ each group stacked in its own bar, the groups' bars side by side (in text, a row per group), with the total marked separately;+ -- values are shown with their usual sign as positive (see 'setChartLayout')+ deriving (Show, Eq, Generic, ToJSON)++-- | A named sequence of values, one per x position.+data Series = Series+ { seLabel :: ChartLabel+ , seRole :: SeriesRole+ , seMark :: Mark+ , seValues :: [Maybe Quantity] -- ^ one value per x position; Nothing means no value there (a gap, not zero).+ -- At each x position, bar series' values are stacked: positive values above zero, negative values below.+ , seGroup :: Int -- ^ which group this series belongs to (eg its section, in a compound report chart; otherwise 0).+ -- Groups are stacked together, or drawn side by side, as the panel's 'pnLayout' says.+ , seSign :: Int -- ^ the usual sign of this series' values, if it has one (1 or -1; otherwise 0).+ -- Values of the opposite sign are contra amounts, which renderers may show distinctly;+ -- eg a refund (negative expense) in a compound report chart.+ } deriving (Show, Eq, Generic, ToJSON)++-- | What a series represents, which renderers may show differently (eg a muted colour for 'SeriesOther').+data SeriesRole+ = SeriesItem -- ^ an ordinary series, eg one account+ | SeriesOther -- ^ several items combined, eg "other (5 accounts)", to limit the number of series+ | SeriesTotal -- ^ a total of other series, eg the net total of stacked bars, or net worth+ | SeriesShortfall -- ^ an amount missing from what the bar stands for, eg the part of a holding's cost basis lost (beyond its value):+ -- drawn hatched, in its place in the stack+ | SeriesProvisional -- ^ an amount not yet final, eg an unrealised gain or loss: drawn hatched, in its place in the stack+ deriving (Show, Eq, Generic, ToJSON)++-- | How a series is drawn.+data Mark+ = MarkBar -- ^ a bar from zero to the value+ | MarkLine -- ^ a line joining the values (in text charts, drawn as bars)+ | MarkMarker -- ^ a marker at the value, not joined, eg a net total over stacked bars, or a budget goal+ | MarkNone -- ^ not drawn: values shown only as text (text charts' value column, tooltips, chart data),+ -- eg holdings' values, which their bars' solid parts reach already+ deriving (Show, Eq, Generic, ToJSON)++-- | Is this value of the series a contra amount (of the opposite sign to the series' usual sign) ?+isContra :: Series -> Quantity -> Bool+isContra s q = seSign s /= 0 && q /= 0 && signum q /= fromIntegral (seSign s)++-- | Is this value of the series drawn hatched ? Contra amounts are, and the values of hatched series (see 'hatchedSeries').+isHatched :: Series -> Quantity -> Bool+isHatched s q = hatchedSeries s || isContra s q++-- | Is this series drawn hatched throughout, in its colour (and so shown hatched in legends) ?+-- Shortfalls and provisional amounts are (see 'SeriesShortfall', 'SeriesProvisional').+hatchedSeries :: Series -> Bool+hatchedSeries s = seRole s `elem` [SeriesShortfall, SeriesProvisional]++-- | Should a legend list these drawn series (on a category axis, or not) ?+-- Yes when there are several, or one is an "other" series (whose muted colour needs explaining),+-- or a lone series names an account on a time axis (where nothing else would name it).+-- A lone series on a category axis is not listed: its bars are labelled on the axis, and coloured by category.+legendListsSeries :: Bool -> [Series] -> Bool+legendListsSeries categories ss =+ length ss > 1 || any ((== SeriesOther) . seRole) ss || (not categories && any (lbAccount . seLabel) ss)++-- | The main account type (asset, liability, equity, revenue or expense) of an account type, which is one of those or a subtype of one.+mainAccountType :: AccountType -> AccountType+mainAccountType t = fromMaybe t $ find (t `isAccountSubtypeOf`) [Asset, Liability, Equity, Revenue, Expense]++-- | How a series (or a bar) is coloured, in a renderer-independent way.+data Colour+ = TypeColour AccountType Int -- ^ the conventional hue of this main account type, in its Nth tint (to distinguish several of that type)+ | IndexColour Int -- ^ the Nth categorical colour, for series with no account type+ | LoneColour -- ^ a hue that no account type uses, for a chart's only series when it is not an account,+ -- or for an account of unknown type in a chart with one account per panel+ | NeutralColour -- ^ a neutral colour, eg for the contra amounts legend swatch+ | OtherColour (Maybe AccountType) -- ^ a muted colour, for a series combining several items: grey, tinged with their main account type's hue if any+ | TotalColour -- ^ the ink (text) colour, for a total+ deriving (Show, Eq)++-- | How many tints of a type's colour renderers provide, to distinguish several accounts of one type.+maxTints :: Int+maxTints = 8++-- | How many categorical colours renderers provide (see 'IndexColour').+categoricalColours :: Int+categoricalColours = 8++-- | How a chart's accounts are coloured (decided for the whole chart, so that colours mean the same in all of its panels).+data Colouring+ = ByName -- ^ in distinct colours chosen by name, to tell them apart: when none has a known type+ | ByType -- ^ by main account type (in tints chosen by name): when any has a known type, even if all are of one type,+ -- so that a type's hue means the same in every chart, and an account keeps its colour in other charts+ | Single -- ^ by type, or if unknown in the lone colour: when each panel shows just one account, so there is nothing to tell apart+ deriving (Show, Eq)++-- | How this chart's accounts should be coloured: considering all of its panels, so that eg in a balance sheet,+-- a commodity's panel with just one asset account shows it in the assets' hue, like the other panels.+chartColouring :: Chart -> Colouring+chartColouring Chart{chPanels}+ | all ((<= 1) . length . filter ((/= SeriesTotal) . seRole) . pnSeries) chPanels = Single+ | or [isJust $ lbType $ seLabel s | p <- chPanels, s <- pnSeries p, seRole s `elem` [SeriesItem, SeriesShortfall, SeriesProvisional]] = ByType+ | otherwise = ByName++-- | Colours for a panel's series, in order, for the chart's colouring (see 'chartColouring').+-- Coloured by type, each account of known type gets its main type's hue, in one of several tints+-- (shared when there are more than 'maxTints' of a type). Otherwise, and accounts of unknown type, get categorical colours;+-- except that a lone series which is not an account (eg a total, or "..." for all accounts), or a lone account of unknown type+-- in a chart of single accounts, gets a hue that no account type uses.+--+-- The tints and categorical colours are chosen by the series' names, not their positions or number (see 'stableSlots'),+-- so that an account keeps its colour in other charts: eg after removing other accounts (even down to just one), or sorting differently.+-- A series of known type which is not an account (eg a holding's cost or gain) has its type's first tint,+-- so that its colour doesn't depend on its name (which may be translated).+seriesColours :: Colouring -> [Series] -> [Colour]+seriesColours colouring series = zipWith colour series' slots+ where+ series'+ | colouring == ByName = [s{seLabel = (seLabel s){lbType = Nothing}} | s <- series]+ | otherwise = series+ typeOf s = mainAccountType <$> lbType (seLabel s)+ onlyone = length [s | s <- series, seRole s /= SeriesTotal] == 1+ -- each series' slot among the other ordinary series of its type (or with no type)+ slots = [ fromMaybe 0 $ M.lookup i slotmap | i <- [0 .. length series' - 1] ]+ slotmap = M.fromList $ concat+ [ zip is $ slotsfor t [(lbFull $ seLabel s, seriesSize s) | s <- ss]+ | t <- nub $ map (typeOf . snd) named+ , let (is, ss) = unzip [(i, s) | (i, s) <- named, typeOf s == t] ]+ -- the ordinary series which choose tints or categorical colours by name: accounts, and series of unknown type+ named = [(i, s) | (i, s) <- zip [0 :: Int ..] series', seRole s == SeriesItem, lbAccount (seLabel s) || isNothing (typeOf s)]+ -- a type's tints are chosen favouring the first, most saturated ones (the paler ones look washed out),+ -- so that they are used mainly when several accounts of the type need telling apart; categorical colours, without bias+ slotsfor t = if isJust t then stableSlotsFavouringFirst 0.5 maxTints else stableSlots categoricalColours+ colour s k = case (seRole s, typeOf s) of+ (SeriesTotal, _) -> TotalColour+ (SeriesOther, t) -> OtherColour t+ (_, Just t)+ | lbAccount (seLabel s) -> TypeColour t k+ | otherwise -> TypeColour t 0+ (_, Nothing)+ | onlyone && (colouring == Single || not (lbAccount $ seLabel s)) -> LoneColour+ | otherwise -> IndexColour k++-- | A tint for each of these categories (eg a single-period chart's accounts, with their values), chosen by name+-- among the categories of the same main account type, as 'seriesColours' chooses them for series:+-- so that accounts of one type can be told apart, and tend to keep their tints in a multi-period chart.+categoryTints :: [ChartLabel] -> [Maybe Quantity] -> [Int]+categoryTints labels vals = [M.findWithDefault 0 j tints | j <- [0 .. length labels - 1]]+ where+ cats = [(j, mainAccountType <$> lbType l, (lbFull l, maybe 0 abs v)) | (j, l, v) <- zip3 [0 :: Int ..] labels (vals ++ repeat Nothing)]+ tints = M.fromList $ concat+ [ zip js $ stableSlotsFavouringFirst 0.5 maxTints items+ | t <- nub [t | (_, t, _) <- cats]+ , let (js, items) = unzip [(j, item) | (j, t', item) <- cats, t' == t] ]++-- | A series' size, for ranking: the sum of its absolute values.+seriesSize :: Series -> Quantity+seriesSize = sum . map abs . catMaybes . seValues++-- | Give each of these names one of n slots (0 to n-1), chosen by the name rather than its position,+-- so that a name tends to get the same slot in other lists: eg a colour that stays with an account in successive charts.+-- Each name has its own order of preference for the slots (from a hash of it), and gets the first one still free.+-- The names choose in order of their sizes (largest first; then by name), so that adding or removing small items+-- (or removing the largest) disturbs few others; positions don't matter.+-- When there are more names than slots, slots are shared: once all are taken, the names choose among them all again.+stableSlots :: Ord a => Int -> [(Text, a)] -> [Int]+stableSlots = stableSlotsFavouringFirst 0++-- | Like 'stableSlots', but with each name's preferences biased towards the first slots, by this much+-- (0: not at all; 1: fully, so that every name has the same order of preference).+-- Eg with 0.5, the last of 4 slots is never a name's first choice, and the first is its first choice most often.+stableSlotsFavouringFirst :: Ord a => Double -> Int -> [(Text, a)] -> [Int]+stableSlotsFavouringFirst bias n items+ | n <= 0 = map (const 0) items+ | otherwise = [ fromMaybe 0 $ M.lookup i assigned | i <- [0 .. length items - 1] ]+ where+ assigned = snd $ foldl' place (S.empty, M.empty) $ sortOn (\(i, (nm, size)) -> (Down size, nm, i)) $ zip [0 :: Int ..] items+ place (used, m) (i, (nm, _)) =+ let prefs = preferences nm+ used' = if S.size used >= n then S.empty else used+ slot = fromMaybe (fromMaybe 0 $ listToMaybe prefs) $ find (`S.notMember` used') prefs+ in (S.insert slot used', M.insert i slot m)+ -- a name's slots, in its order of preference+ -- (by the slot's position, if biased, plus a pseudo-random fraction from the name)+ preferences nm = sortOn (\k -> bias * fromIntegral k + fromIntegral (hash (nm <> "/" <> T.pack (show k))) / 2 ^ (32 :: Int)) [0 .. n - 1]+ -- a simple, stable hash: FNV-1a (32 bit), with murmur3's finaliser to mix in the last characters well+ -- (which here are the slot number; without it, names had only a few dozen orders of preference)+ hash :: Text -> Word32+ hash = fmix32 . T.foldl' (\h c -> (h `xor` fromIntegral (ord c)) * 16777619) 2166136261+ fmix32 h0 =+ let h1 = (h0 `xor` (h0 `shiftR` 16)) * 0x85ebca6b+ h2 = (h1 `xor` (h1 `shiftR` 13)) * 0xc2b2ae35+ in h2 `xor` (h2 `shiftR` 16)++-- | A series' values, indexed by x position, for fast lookup by renderers.+type SeriesValues = Array Int (Maybe Quantity)++seriesValues :: Series -> SeriesValues+seriesValues Series{seValues} = listArray (0, length seValues - 1) seValues++-- | The value at this x position, if there is one.+valueAt :: SeriesValues -> Int -> Maybe Quantity+valueAt a j = if inRange (bounds a) j then a ! j else Nothing++-- | Give each panel a fixed scale (see 'pnScale'): the absolute quantity of the scale amount in the panel's commodity,+-- or else of the one with no commodity symbol. When several are in the same commodity, the last one is used.+setChartScales :: [Amount] -> Chart -> Chart+setChartScales scales chart = chart{chPanels = map setscale $ chPanels chart}+ where+ setscale p = p{pnScale = lookup (acommodity $ pnUnit p) byc <|> lookup "" byc <|> pnScale p}+ byc = reverse [(acommodity a, abs $ aquantity a) | a <- scales]++-- | Don't draw the totals (or nets): give each panel's total series no mark ('MarkNone'),+-- so that it is still shown as values where those are shown (eg in tooltips), but not drawn.+chartWithoutTotalMarks :: Chart -> Chart+chartWithoutTotalMarks chart = chart{chPanels = [p{pnSeries = map unmark $ pnSeries p} | p <- chPanels chart]}+ where+ unmark s = if seRole s == SeriesTotal then s{seMark = MarkNone} else s++-- | Set the bar layout of every panel to this one, if given (otherwise keeping each panel's own), and prepare the panels for it.+-- This should be applied before drawing a chart, or showing its data.+-- The grouped layout is for comparing the groups' sizes, so its series are shown with their usual sign as positive+-- (eg expenses as well as revenues upward, like a compound report's tables), and their contra amounts as negative.+-- (Applying this again does nothing more, since those series' usual sign is then positive.)+-- And since only bars can be side by side, in a panel with several groups, series drawn as lines (eg end balances) become bars.+-- Its series are put in their groups' order.+setChartLayout :: Maybe BarLayout -> Chart -> Chart+setChartLayout ml chart = chart{chPanels = map setlayout $ chPanels chart}+ where+ setlayout p = p{pnLayout = l, pnSeries = ingrouporder $ map (asbar . resign l) (pnSeries p)}+ where+ l = fromMaybe (pnLayout p) ml+ -- with the grouped layout, each group's series together, in the groups' order, then any total+ ingrouporder ss+ | l == Grouped = sortOn seGroup items ++ totals+ | otherwise = ss+ where (totals, items) = partition ((== SeriesTotal) . seRole) ss+ asbar s | l == Grouped, length (pnGroupNames p) > 1, seRole s /= SeriesTotal, seMark s == MarkLine = s{seMark = MarkBar}+ asbar s = s+ resign Grouped s | seSign s /= 0 = s{seValues = map (fmap (* fromIntegral (seSign s))) (seValues s), seSign = 1}+ resign _ s = s++-- | With a fixed scale (the amount that a chart spans), and the largest positive and (absolute) negative extents of the values,+-- how much of the scale is given to each direction: (above or right of zero, below or left of zero).+-- Negative values get the room they need and positive values the rest (all of it if there are no negative values;+-- if there are only negative values, they get all of it).+-- If the values don't fit, both directions are shrunk in proportion, and the values beyond them will be clipped.+scaleSpans :: (Ord a, Fractional a) => a -> a -> a -> (a, a)+scaleSpans scale maxpos maxneg+ | maxpos <= 0 && maxneg > 0 = (0, scale)+ | maxpos + maxneg <= scale = (scale - maxneg, maxneg)+ | otherwise = (scale - neg, neg)+ where neg = maxneg * scale / (maxpos + maxneg)++-- | Render a chart's data as CSV (or TSV) records, in long ("tidy") form: one record per value,+-- with a header record. This shows exactly what the chart shows, after any combining of series,+-- and can be charted with other tools.+--+-- Values are shown with the panel unit's display precision, without commodity symbol or digit group marks.+-- A gap (no value) is shown as an empty field.+-- Each panel's summary values (see 'pnSummary') follow its series, with role "rowtotal" or "average", and no mark or x.+chartAsCsv :: Chart -> CSV+chartAsCsv Chart{chXAxis, chPanels} =+ ["commodity", "series", "role", "mark", "x", "value"]+ : concat+ [ [ [acommodity pnUnit, lbFull (seLabel s), roleName (seRole s), markName (seMark s), x, maybe "" (showValue pnUnit) mq]+ | s <- pnSeries+ , (x, mq) <- zip xlabels (seValues s)+ ]+ ++ [ [acommodity pnUnit, suLabel, summaryName suKind, "", "", showValue suValue (aquantity suValue)] | Summary{suKind, suLabel, suValue} <- pnSummary ]+ | Panel{pnUnit, pnSeries, pnSummary} <- chPanels+ ]+ where+ xlabels = case chXAxis of+ XCategories ls -> map lbFull ls+ XPeriods ps -> map snd ps+ XDates ds -> map showDate ds+ showValue unit q = T.pack $ showAmountWith machineFmt{displayCommodity=False} unit{aquantity=q}+ roleName r = case r of+ SeriesItem -> "item"+ SeriesOther -> "other"+ SeriesTotal -> "total"+ SeriesShortfall -> "shortfall"+ SeriesProvisional -> "provisional"+ markName m = case m of+ MarkBar -> "bar"+ MarkLine -> "line"+ MarkMarker -> "marker"+ MarkNone -> "none"+ summaryName k = case k of+ SummaryTotal -> "rowtotal"+ SummaryAverage -> "average"++tests_Hledger_Write_Chart :: TestTree+tests_Hledger_Write_Chart = testGroup "Write.Chart" [+ testCase "scaleSpans" $ do+ scaleSpans 100 80 0 @?= (100 :: Quantity, 0)+ scaleSpans 100 0 30 @?= (0, 100)+ scaleSpans 100 50 30 @?= (70, 30)+ scaleSpans 100 150 50 @?= (75, 25)+ scaleSpans 100 0 0 @?= (100, 0)+ ,testCase "seriesColours" $ do+ let ser n t = Series (ChartLabel n n 0 t True []) SeriesItem MarkBar [Just 1] 0 0+ tints cs = [k | TypeColour _ k <- cs]+ -- in a chart coloured by type, accounts get their types' hues, in different tints; untyped series get categorical colours+ let cs = seriesColours ByType [ser "e1" (Just Expense), ser "a" (Just Cash), ser "u1" Nothing, ser "e2" (Just Expense), ser "u2" Nothing]+ length [c | c@(TypeColour Asset _) <- cs] @?= 1+ length (nub $ tints [c | c@(TypeColour Expense _) <- cs]) @?= 2+ length (nub [k | IndexColour k <- cs]) @?= 2+ -- as many accounts of one type as there are tints get a tint each+ length (nub $ tints $ seriesColours ByType [ser (T.pack $ show i) (Just Expense) | i <- [1 .. maxTints]]) @?= maxTints+ -- a chart is coloured by type when any account has a type, even if all are of one type; by name when none has+ let chartOf ts = Chart "" (XCategories []) [Panel nullamt [ser (T.pack $ show i) t | (i, t) <- zip [1 :: Int ..] ts] [] Nothing Diverging False [] []] []+ chartColouring (chartOf [Just Expense, Just Expense]) @?= ByType+ chartColouring (chartOf [Just Expense, Nothing]) @?= ByType+ chartColouring (chartOf [Nothing, Nothing]) @?= ByName+ chartColouring (chartOf [Just Expense]) @?= Single+ -- colours follow the accounts, not their positions+ seriesColours ByType [ser "e2" (Just Expense), ser "e1" (Just Expense)] @?= reverse (seriesColours ByType [ser "e1" (Just Expense), ser "e2" (Just Expense)])+ -- coloured by name (as when no account has a type) accounts get categorical colours, all different+ let rs = seriesColours ByName [ser (T.pack $ show i) (Just Revenue) | i <- [1 .. categoricalColours]]+ length (nub [k | IndexColour k <- rs]) @?= categoricalColours+ -- and keep them when fewer are shown, down to one+ seriesColours ByName (take 1 [ser (T.pack $ show i) (Just Revenue) | i <- [1 .. categoricalColours]]) @?= take 1 rs+ -- typed series which are not accounts (eg a holding's cost, gain and loss) get their types' first tints, whatever their names+ let nonacct n t = (ser n (Just t)){seLabel = ChartLabel n n 0 (Just t) False []}+ seriesColours ByType [nonacct n t | (n, t) <- [("Kosten", Asset), ("Gewinn", Revenue), ("Verlust", Expense)]]+ @?= [TypeColour Asset 0, TypeColour Revenue 0, TypeColour Expense 0]+ -- a lone series which is not an account gets the lone colour; others and totals get theirs+ seriesColours ByName [(ser "u" Nothing){seLabel = ChartLabel "u" "u" 0 Nothing False []}] @?= [LoneColour]+ seriesColours ByName [(ser "o" Nothing){seRole = SeriesOther}, (ser "t" Nothing){seRole = SeriesTotal}]+ @?= [OtherColour Nothing, TotalColour]+ -- in a chart of single accounts, a lone account has its type's hue, or if unknown the lone colour+ seriesColours Single [ser "e" (Just Expense)] @?= map (TypeColour Expense) (stableSlotsFavouringFirst 0.5 maxTints [("e", 1 :: Quantity)])+ seriesColours Single [ser "u" Nothing] @?= [LoneColour]+ ,testCase "stableSlots" $ do+ let items = [("a", 3), ("b", 2), ("c", 1)] :: [(Text, Int)]+ slots = stableSlots 8 items+ length (nub slots) @?= 3 -- different slots, while there are enough+ stableSlots 8 (reverse items) @?= reverse slots -- positions don't matter+ all (`elem` [0 .. 7]) slots @?= True+ length (nub $ stableSlots 2 items) @?= 2 -- more items than slots: they share them+ stableSlots 0 items @?= [0, 0, 0]+ -- with twice as many items as slots, each slot is shared by two+ let many = stableSlots 4 [(T.pack $ show i, i) | i <- [1 .. 8 :: Int]]+ [length $ filter (== k) many | k <- [0 .. 3]] @?= [2, 2, 2, 2]+ ,testCase "categoryTints" $ do+ let lbl n t = ChartLabel n n 0 t True []+ ts = categoryTints [lbl "e1" (Just Expense), lbl "a" (Just Asset), lbl "e2" (Just Expense), lbl "e3" (Just Expense)] [Just 3, Just 2, Just 1, Nothing]+ length ts @?= 4+ length (nub [t | (i, t) <- zip [0 :: Int ..] ts, i /= 1]) @?= 3 -- the categories of a type get different tints+ ]
+ Hledger/Write/Chart/Palette.hs view
@@ -0,0 +1,96 @@+{- |+The exact colours of chart series, shared by the chart renderers (SVG, and text in terminals with 24-bit colour),+so that charts look the same everywhere.++The categorical palette and chart colours are the dataviz skill's validated reference palette (8 slots, light and dark variants);+the account type colours were chosen from it and validated on the pairs that appear together (assets-liabilities-equity, revenues-expenses).+-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Chart.Palette (+ colourHex,+ tint,+ tests_Hledger_Write_Chart_Palette,+) where++import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Numeric (readHex)+import Safe (atMay)+import Text.Printf (printf)++import Hledger.Data.Types (AccountType(..))+import Hledger.Utils.Test+import Hledger.Write.Chart (Colour(..), mainAccountType, maxTints)+++-- | A chart colour as #rrggbb, in its light variant (for light backgrounds) or its dark variant (for dark backgrounds).+colourHex :: Bool -> Colour -> Text+colourHex dark c = case c of+ TypeColour at k -> tint (tintFraction dark k) $ pick $ typeColour $ mainAccountType at+ IndexColour k -> pick $ fromMaybe ("#2a78d6", "#3987e5") $ categorical `atMay` (k `mod` length categorical)+ OtherColour Nothing -> grey+ OtherColour (Just at) -> mixWith 0.6 grey $ pick $ typeColour $ mainAccountType at -- the type's hue, greyed+ LoneColour -> pick ("#1597b0", "#22a6be") -- cyan+ NeutralColour -> pick ("#52514e", "#c3c2b7")+ TotalColour -> pick ("#0b0b0b", "#ffffff")+ where+ pick (light, darkc) = if dark then darkc else light+ grey = "#898781"++-- | Conventional colours for the main account types (light, dark).+typeColour :: AccountType -> (Text, Text)+typeColour at = case at of+ Asset -> ("#2a78d6", "#3987e5") -- blue+ Liability -> ("#eda100", "#c98500") -- amber+ Equity -> ("#4a3aa7", "#9085e9") -- violet+ Revenue -> ("#008300", "#008300") -- green+ Expense -> ("#e34948", "#e66767") -- red+ _ -> ("#4a3aa7", "#9085e9")++-- | The categorical palette (light, dark), in its validated order.+categorical :: [(Text, Text)]+categorical =+ [ ("#2a78d6", "#3987e5"), ("#eb6834", "#d95926"), ("#1baf7a", "#199e70"), ("#eda100", "#c98500")+ , ("#e87ba4", "#d55181"), ("#008300", "#008300"), ("#4a3aa7", "#9085e9"), ("#e34948", "#e66767") ]++-- | How the Nth tint of a type's colour differs from it ('maxTints' of them, repeating), on a light or dark background:+-- the fraction to mix with white (positive) or black (negative). Ordered with the most visible first, since accounts prefer+-- the first ones (see 'seriesColours'): the colour itself, then darker (on a light background) or lighter (on a dark one),+-- then the other of those, then lighter still.+tintFraction :: Bool -> Int -> Double+tintFraction dark k = fromMaybe 0 $ take maxTints fractions `atMay` (k `mod` maxTints)+ where fractions = if dark then [0, 0.4, -0.3, 0.65, 0.2, -0.15, 0.8, -0.45] else [0, -0.3, 0.4, 0.65, -0.15, 0.2, -0.45, 0.8]++-- | Mix a #rrggbb colour with white (by a positive fraction) or black (by a negative fraction).+tint :: Double -> Text -> Text+tint f+ | f >= 0 = mixWith f "#ffffff"+ | otherwise = mixWith (negate f) "#000000"++-- | Mix a #rrggbb colour with another, by this fraction of the other (0 to 1).+mixWith :: Double -> Text -> Text -> Text+mixWith f other hex = case (rgb hex, rgb other) of+ (Just cs, Just os) -> "#" <> T.concat (zipWith (\c o -> T.pack $ printf "%02x" (mix c o)) cs os)+ _ -> hex+ where+ rgb h = let digits = T.drop 1 h in+ if T.length digits == 6 then mapM channel [T.take 2 $ T.drop i digits | i <- [0, 2, 4]] else Nothing+ channel t = case readHex (T.unpack t) of [(n, "")] -> Just (n :: Int); _ -> Nothing+ mix :: Int -> Int -> Int+ mix c o = round $ fromIntegral c + (fromIntegral o - fromIntegral c) * f++tests_Hledger_Write_Chart_Palette :: TestTree+tests_Hledger_Write_Chart_Palette = testGroup "Write.Chart.Palette" [+ testCase "colourHex" $ do+ colourHex False (TypeColour Revenue 0) @?= "#008300"+ colourHex True (TypeColour Expense 0) @?= "#e66767"+ colourHex False (TypeColour Cash 0) @?= "#2a78d6" -- a subtype gets its main type's colour+ colourHex False (TypeColour Expense maxTints) @?= colourHex False (TypeColour Expense 0) -- tints repeat+ ,testCase "tint" $ do+ tint 0.5 "#000000" @?= "#808080"+ tint (-0.5) "#ffffff" @?= "#808080"+ tint 0.5 "not a colour" @?= "not a colour"+ ]
+ Hledger/Write/Chart/Svg.hs view
@@ -0,0 +1,1051 @@+{- |+Draw a 'Chart' as SVG, a self-contained graphical file viewable in web browsers and many image viewers.++Charts over time (periods or dates) are drawn with time along the x axis:+bar series as vertical bars (stacked, with a 2px gap between segments), line series as 2px lines,+and totals as ink-coloured line marks across each period's bars, or as an ink-coloured line.+Charts of categories (eg the accounts of a single-period report) are drawn as horizontal bars,+with labels on the left and an aligned value column on the right.+There is one panel per commodity, one above the other, and a legend listing the series (see 'legendListsSeries'), and any average line.+Each mark has a tooltip (an SVG title) giving its x label, series and value,+and for an "other" series, the accounts it combines, one per line.++The SVG includes its own styles, with a colour-blind-safe palette and a dark-mode variant+(used when the viewer prefers a dark colour scheme). Text widths are estimated, since fonts are not known.+Coordinates are rounded to one decimal place, so the output is deterministic.++A page embedding a chart can draw it with 'SvgOptions', eg without its styles, which the page then supplies+('chartStylesheet').+-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Chart.Svg (+ chartAsSvg,+ chartAsSvgWith,+ chartSvgMarkup,+ SvgOptions(..),+ defaultSvgOptions,+ chartSvgMarkupWith,+ chartPanelsSvgMarkupWith,+ chartStylesheet,+ tests_Hledger_Write_Chart_Svg,+) where++import Control.Monad (forM_, join, mfilter, unless, when)+import Data.Char (isDigit, isUpper)+import Data.Function (on)+import Data.List (find, groupBy, nub, sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map qualified as M+import Data.Array qualified as Arr+import Data.Decimal (realFracToDecimal)+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)+import Data.Time (Day, addDays, diffDays, fromGregorian, toGregorian)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Safe (atMay, headMay, lastMay, maximumDef, minimumDef)+import Text.Blaze (AttributeValue, (!?), customAttribute, toValue)+import Text.Blaze.Svg.Renderer.Text (renderSvg)+import Text.Blaze.Svg11 ((!), Svg)+import Text.Blaze.Svg11 qualified as S+import Text.Blaze.Svg11.Attributes qualified as A+import Text.DocLayout qualified as DL+import Text.Printf (printf)++import Hledger.Data.Amount (nullamt, oneLineNoCostFmt, showAmountWith)+import Hledger.Data.Dates (nulldatespan, showDate)+import Hledger.Data.Types (AccountType(..), Amount(..), AmountPrecision(..), AmountStyle(..), Quantity)+import Hledger.Utils.Test+import Hledger.Write.Chart+import Hledger.Write.Chart.Palette (colourHex)+++-- | Render a chart as a complete SVG document, with a dark variant for viewers preferring a dark colour scheme.+chartAsSvg :: Chart -> TL.Text+chartAsSvg = chartAsSvgWith True++-- | Render a chart as SVG, with or without the dark variant+-- (eg without, when embedding it in a page that is always light).+-- It has one element per line, for readability.+chartAsSvgWith :: Bool -> Chart -> TL.Text+chartAsSvgWith dark = (<> "\n") . TL.replace "><" ">\n<" . renderSvg . chartSvgMarkup dark++-- | A chart as SVG markup, which can also be embedded in HTML; with or without the dark variant.+chartSvgMarkup :: Bool -> Chart -> Svg+chartSvgMarkup dark = chartSvgMarkupWith defaultSvgOptions{svgDark = dark}++-- | How to draw a chart as SVG.+data SvgOptions = SvgOptions+ { svgStyles :: Bool -- ^ include the chart's styles ? A page embedding the chart can leave them out and supply+ -- 'chartStylesheet' itself, eg one whose Content-Security-Policy allows no inline styles.+ , svgDark :: Bool -- ^ include the styles' dark variant, for viewers preferring a dark colour scheme ?+ , svgWidth :: Double -- ^ the chart's width, in pixels. A page shrinks a chart wider than it shows it, text and all,+ -- so it can draw the chart as wide as that instead.+ , svgPlotHeight :: Double -- ^ the height of each plot of values over time or of categories as columns, in pixels,+ -- not counting its labels; also deciding how many y ticks it has (see 'plotIntervals').+ -- (Horizontal bars are as tall as their rows.)+ , svgPointLink :: Int -> Maybe Text -- ^ a link for each x position (by index), if any: lines' tooltip targets there link to it,+ -- eg to a page's row for that transaction. They are left out of the tab order, being many.+ , svgDateScale :: Bool -- ^ give each plot of values by date its date scale, for a page's script (eg to select dates by+ -- dragging across it): a transparent rectangle over the plot (class plot), with its first and last+ -- dates (data-d0, data-d1) and their x positions (data-x0, data-x1), between which dates are spaced evenly ?+ , svgToday :: Maybe Day -- ^ today's date, if each plot of values by date should be shaded as of it: the future, after it,+ -- and the past where values are below zero (eg an overdrawn account), with the zero line in red.+ , svgIds :: Text -- ^ the prefix of the ids that the chart's elements refer to (its clipping paths and hatching).+ -- Charts on one page need different ones when one may be hidden while another is shown,+ -- since a hidden chart's patterns and clipping paths may not apply to another's elements.+ }++-- | A self-contained chart: with its styles, including their dark variant, 880px wide, plots 260px high, no links, no date scale, and no shading.+defaultSvgOptions :: SvgOptions+defaultSvgOptions = SvgOptions+ { svgStyles = True+ , svgDark = True+ , svgWidth = 880+ , svgPlotHeight = 260+ , svgPointLink = const Nothing+ , svgDateScale = False+ , svgToday = Nothing+ , svgIds = "hledger-chart"+ }++-- | A chart as SVG markup, which can also be embedded in HTML, drawn with these options.+chartSvgMarkupWith :: SvgOptions -> Chart -> Svg+chartSvgMarkupWith opts c = chartSvgMarkupColoured (chartColouring c) opts c++-- | Each of a chart's panels as a chart of its own, in SVG markup drawn with these options,+-- coloured as in the whole chart; eg for a page to show one commodity's panel at a time.+-- Each has its own ids (see 'svgIds'), the given prefix numbered.+chartPanelsSvgMarkupWith :: SvgOptions -> Chart -> [Svg]+chartPanelsSvgMarkupWith opts c =+ [ chartSvgMarkupColoured (chartColouring c) opts{svgIds = svgIds opts <> "-" <> T.pack (show k)} c{chPanels = [p]}+ | (k, p) <- zip [0 :: Int ..] (chPanels c) ]++-- | A chart as SVG markup, drawn with these options and this colouring.+chartSvgMarkupColoured :: Colouring -> SvgOptions -> Chart -> Svg+chartSvgMarkupColoured colouring opts@SvgOptions{svgStyles, svgDark, svgWidth} Chart{chTitle, chXAxis, chPanels, chNotes} =+ S.svg+ ! customAttribute "xmlns" "http://www.w3.org/2000/svg"+ ! A.class_ "hledger-chart"+ ! A.width (toValue $ num svgWidth)+ ! A.height (toValue $ num totalheight)+ ! A.viewbox (toValue $ "0 0 " <> num svgWidth <> " " <> num totalheight)+ ! customAttribute "role" "img"+ !? (not $ T.null chTitle, customAttribute "aria-label" (toValue chTitle))+ $ do+ unless (T.null chTitle) $ S.title (S.toMarkup chTitle)+ when svgStyles $ S.style (S.toMarkup $ stylesheet (isJust $ svgToday opts) svgDark)+ S.rect ! A.class_ "bg" ! A.width "100%" ! A.height "100%"+ unless (T.null chTitle) $+ S.text_ ! A.class_ "title" ! A.x (toValue $ num pad) ! A.y (toValue $ num (pad + 17)) $ S.toMarkup chTitle+ sequence_ panelmarkups+ when (null chPanels) $+ S.text_ ! A.class_ "label" ! A.x (toValue $ num pad) ! A.y (toValue $ num (pad + titleheight + 16)) $ "No data"+ -- the notes, below the panels+ forM_ (zip [0 :: Int ..] chNotes) $ \(i, n) ->+ S.text_ ! A.class_ "note" ! A.x (toValue $ num pad) ! A.y (toValue $ num (contentbottom + 14 + noteHeight * fromIntegral i)) $ S.toMarkup n+ where+ titleheight = if T.null chTitle then 0 else 38+ showheadings = length chPanels > 1+ (panelsbottom, panelmarkups) = foldl stackPanel (pad + titleheight, []) chPanels+ contentbottom = if null chPanels then panelsbottom + 14 + pad else panelsbottom+ totalheight = contentbottom + (if null chNotes then 0 else noteHeight * fromIntegral (length chNotes) + pad / 2)+ stackPanel (top, ms) p =+ let (h, m) = panelSvg opts chXAxis colouring showheadings top p+ in (top + h + panelGap, ms ++ [m])++-- Layout constants, in pixels. (The chart's width and its plots' height are in 'SvgOptions'.)+pad, panelGap, legendRowHeight, rowHeight, noteHeight :: Double+pad = 16+panelGap = 16+legendRowHeight = 24+rowHeight = 28 -- height of a row in a horizontal bar chart+noteHeight = 22 -- height of a note's line, below the panels++-- | The narrowest a chart's periods can be (the chart's width divided by their number, in pixels)+-- for a total to be marked across their bars. The bars are 3/4 of their period (so here, 24px wide),+-- and a mark is 4px wider than them on each side, so below this the marks would run into each other.+minMarkedPeriodWidth :: Double+minMarkedPeriodWidth = 32++-- | How many intervals a plot this high (in pixels) divides its y axis into, roughly: about one per 50px, from 2 to 5.+plotIntervals :: Double -> Int+plotIntervals h = max 2 $ min 5 $ floor (h / 50)++-- | A value label's classes (see 'pnValueLabels'): a gain (beginning with +) in the revenue colour,+-- a loss (beginning with -) in the expense colour, as text charts show them.+vlabelClass :: Text -> AttributeValue+vlabelClass t+ | "+" `T.isPrefixOf` t = "value vlabel gain"+ | "-" `T.isPrefixOf` t = "value vlabel loss"+ | otherwise = "value vlabel"++-- | The size of value labels' font (see 'pnValueLabels'), relative to the usual 14px: 12px, so that more of them fit.+valueLabelScale :: Double+valueLabelScale = 12 / 14++-- | Estimated rendered width of a value label (see 'textWidth').+labelWidth :: Text -> Double+labelWidth = (* valueLabelScale) . textWidth++-- | Estimated rendered width of some text, in the 14px system sans font (fonts are not known),+-- from the widths of kinds of character (measured with SF Pro; Segoe UI and others are similar or narrower).+textWidth :: Text -> Double+textWidth = T.foldl' (\w c -> w + glyphWidth c) 0+ where+ glyphWidth c+ | DL.charWidth c == 2 = 14+ | DL.charWidth c == 0 = 0+ | isDigit c = 8.7 -- tabular digits, as in ticks and values+ | c `elem` ("mwMW" :: String) = 12+ | isUpper c = 9.5+ | c `elem` ("fijlrt" :: String) = 4.2+ | c `elem` (" .,:;'|!()" :: String) = 3.8+ | otherwise = 7.9++-- | A series to draw, with its CSS class and the values it draws.+data DrawSeries = DrawSeries+ { dsClass :: Text+ , dsSeries :: Series+ , dsValues :: SeriesValues+ }++-- | Draw one panel with its top at the given y; return its height and markup.+panelSvg :: SvgOptions -> XAxis -> Colouring -> Bool -> Double -> Panel -> (Double, Svg)+panelSvg opts xaxis colouring showheading top Panel{pnUnit, pnSeries, pnScale, pnLayout, pnSummary, pnValueLabels} =+ (headingh + legendh + bodyh + summaryh, do+ when (headingh > 0) $+ S.text_ ! A.class_ "heading" ! A.x (toValue $ num pad) ! A.y (toValue $ num (top + 16)) $ S.toMarkup (acommodity pnUnit)+ -- a hatching pattern, for contra amounts and shortfalls+ when hashatching $ S.defs $ S.pattern ! A.id_ (toValue $ hatchId $ svgIds opts) ! A.width "5" ! A.height "5" ! A.patternunits "userSpaceOnUse" ! A.patterntransform "rotate(45)" $+ S.line ! A.class_ "hatch" ! A.x1 "0" ! A.y1 "0" ! A.x2 "0" ! A.y2 "5"+ legendm+ bodym+ when (summaryh > 0) $+ S.text_ ! A.class_ "label" ! A.x (toValue $ num pad) ! A.y (toValue $ num (top + headingh + legendh + bodyh + 16)) $ S.toMarkup summarytext)+ where+ headingh = if showheading && not (T.null $ acommodity pnUnit) then 28 else 0+ -- the summary values, on a line below the plot, eg "Total 11, Average 0.9"+ summaryh = if null pnSummary then 0 else 26+ summarytext = T.intercalate ", " [suLabel su <> " " <> showSummary su | su <- pnSummary]+ showSummary = T.pack . showAmountWith oneLineNoCostFmt . suValue+ -- the average, drawn as a line across a chart of periods+ maverage = case xaxis of+ XPeriods _ -> find ((== SummaryAverage) . suKind) pnSummary+ _ -> Nothing+ -- The series drawn as marks: items and "other" (bars or lines), and the total (dots or a line). Other markers are not drawn yet.+ items = [s | s <- pnSeries, seRole s /= SeriesTotal, seMark s `notElem` [MarkMarker, MarkNone]]+ mtotal = find ((== SeriesTotal) . seRole) pnSeries+ -- The total, if it's to be marked: always (even where it is just the end of the bars, or zero), since a graphical+ -- chart draws it only when asked for (--chart=net, hledger-web's N key); but not when it would be marked across+ -- the bars of periods too narrow for it (eg weekly over years):+ -- the marks, wider than the bars, would run together and hide them.+ -- A total line over the bars of just one period (eg a single-period balance sheet's net) would be a single point,+ -- so it is marked across them instead.+ -- A total that isn't to be drawn (MarkNone) is shown only as the value, in tooltips.+ mtotalmark = case mtotal of+ Just t | seMark t == MarkNone -> Nothing+ Just t | crowded && seMark t /= MarkLine && hasbars -> Nothing+ Just t | xcount == Just 1 && seMark t == MarkLine && hasbars -> Just t{seMark = MarkMarker}+ _ -> mtotal+ hasbars = any ((== MarkBar) . seMark) items+ -- the number of x positions, on a time axis+ xcount = case xaxis of+ XPeriods ps -> Just $ length ps+ XDates ds -> Just $ length ds+ XCategories _ -> Nothing+ crowded = maybe False (\k -> svgWidth opts / fromIntegral (max 1 k) < minMarkedPeriodWidth) xcount+ drawn = zipWith (\c s -> DrawSeries (colourClass c) s (seriesValues s)) (seriesColours colouring items) items+ listseries = legendListsSeries (case xaxis of XCategories _ -> True; _ -> False) (map dsSeries drawn)+ (legendh, legendm) = legendSvg (svgIds opts) (svgWidth opts) (top + headingh) listseries+ [(dsClass d, seMark s, lbFull $ seLabel s, hatchedSeries s) | d <- drawn, let s = dsSeries d]+ (if length items > 1 then mtotalmark else Nothing) hascontra (suLabel <$> maverage)+ hascontra = or [isContra s q | s <- items, seMark s == MarkBar, Just q <- seValues s]+ hashatching = or [isHatched s q | s <- items, seMark s == MarkBar, Just q <- seValues s]+ (bodyh, bodym) = case xaxis of+ XCategories ls -> categoriesSvg (svgIds opts) (svgWidth opts) (svgPlotHeight opts) (top + headingh + legendh) pnScale pnUnit drawn mtotal mtotalmark pnValueLabels ls+ XPeriods ps -> timeSvg opts (top + headingh + legendh) pnScale pnLayout pnUnit drawn mtotalmark averageline pnValueLabels (EvenScale $ map snd ps)+ XDates ds -> timeSvg opts (top + headingh + legendh) pnScale pnLayout pnUnit drawn mtotalmark Nothing pnValueLabels (DateScale ds)+ averageline = (\su -> (suLabel su <> " · " <> showSummary su, aquantity $ suValue su)) <$> maverage++-- | A legend: a swatch and label for each series, flowing left to right, if they are to be listed (eg when there are several).+-- A series drawn hatched (a shortfall) has a hatched swatch. If there are contra amounts, a neutral hatched swatch is shown for them too.+-- If an average line is drawn (with this label), a dashed swatch is shown for it, even when the series are not listed.+legendSvg :: Text -> Double -> Double -> Bool -> [(Text, Mark, Text, Bool)] -> Maybe Series -> Bool -> Maybe Text -> (Double, Svg)+legendSvg ids width top listseries entries mtotal hascontra maveragelabel+ | null allentries = (0, mempty)+ | otherwise = (fromIntegral (length rows) * legendRowHeight + 8, mapM_ drawRow (zip [0 ..] rows))+ where+ allentries+ | not listseries = averageentry+ | otherwise = entries+ ++ [("total", if seMark t == MarkLine || all (\(_, mk, _, _) -> mk == MarkLine) entries then MarkLine else MarkMarker, lbFull (seLabel t), False) | Just t <- [mtotal]]+ ++ averageentry+ ++ [(colourClass NeutralColour, MarkBar, "contra", True) | hascontra]+ averageentry = [(averageClass, MarkLine, lbl, False) | Just lbl <- [maveragelabel]]+ averageClass = "average"+ itemWidth (_, _, lbl, _) = 20 + textWidth lbl + 18+ rows = reverse $ map reverse $ foldl place [] allentries+ place [] e = [[e]]+ place (r:rs) e+ | sum (map itemWidth r) + itemWidth e <= width - 2 * pad = (e : r) : rs+ | otherwise = [e] : r : rs+ drawRow :: (Int, [(Text, Mark, Text, Bool)]) -> Svg+ drawRow (i, row) = do+ let y = top + fromIntegral i * legendRowHeight + 10+ xs = scanl (+) pad (map itemWidth row)+ forM_ (zip xs row) $ \(x, (cls, mk, lbl, hatched)) -> do+ case mk of+ MarkLine | cls == averageClass -> -- a dashed line, a little longer so that it ends with a dash+ S.line ! A.class_ "average" ! A.x1 (toValue $ num x) ! A.x2 (toValue $ num (x + 14))+ ! A.y1 (toValue $ num y) ! A.y2 (toValue $ num y)+ MarkLine -> S.line ! A.class_ ("line " <> toValue cls) ! A.x1 (toValue $ num x) ! A.x2 (toValue $ num (x + 12))+ ! A.y1 (toValue $ num y) ! A.y2 (toValue $ num y)+ MarkMarker -> S.line ! A.class_ ("mark " <> toValue cls) ! A.x1 (toValue $ num x) ! A.x2 (toValue $ num (x + 12))+ ! A.y1 (toValue $ num y) ! A.y2 (toValue $ num y)+ MarkBar | hatched -> do+ swatch x y ! A.class_ ("fill " <> toValue cls)+ swatch x y ! A.fill (toValue $ "url(#" <> hatchId ids <> ")")+ MarkBar -> swatch x y ! A.class_ ("fill " <> toValue cls)+ MarkNone -> mempty+ -- the total's label is classed like its swatch and its line or marks, so that a page can hide them all (eg hledger-web's N key)+ S.text_ ! A.class_ (if cls == "total" then "label total" else "label") ! A.x (toValue $ num (x + 20)) ! A.y (toValue $ num (y + 5)) $ S.toMarkup lbl+ swatch x y = S.rect ! A.x (toValue $ num x) ! A.y (toValue $ num (y - 6)) ! A.width "12" ! A.height "12" ! A.rx "3"++-- | How x positions are placed along a time axis: evenly, with these labels (eg report periods),+-- or by date, on a time scale (eg a register's transactions; lines are then drawn as steps).+data XScale = EvenScale [Text] | DateScale [Day]++-- | Draw series over time, along the given x scale:+-- vertical stacked bars (with the grouped layout, a stack per group, side by side), lines, and total marks or lines.+timeSvg :: SvgOptions -> Double -> Maybe Quantity -> BarLayout -> Amount -> [DrawSeries] -> Maybe Series -> Maybe (Text, Quantity) -> [Maybe Text] -> XScale -> (Double, Svg)+timeSvg SvgOptions{svgWidth = width, svgPlotHeight = plotheight, svgPointLink, svgDateScale, svgToday, svgIds} top mscale layout unit drawn mtotal maverage vlabels xscale = (plotheight + 32 + labelroom, do+ -- the plot's area with its date scale, if wanted, beneath the rest so that their tooltips and links still work+ when (svgDateScale && isJust datearray) $+ S.rect ! A.class_ "plot"+ ! A.x (toValue $ num plotleft) ! A.y (toValue $ num plottop) ! A.width (toValue $ num (plotright - plotleft)) ! A.height (toValue $ num plotheight)+ ! customAttribute "data-d0" (toValue $ showDate d0) ! customAttribute "data-d1" (toValue $ showDate d1)+ ! customAttribute "data-x0" (toValue $ num $ xofday d0) ! customAttribute "data-x1" (toValue $ num $ xofday d1)+ -- the shading as of today, if wanted: the past below zero, and the future, divided halfway between today and tomorrow+ forM_ mtoday $ \today -> do+ let xnow = clamp plotleft plotright $ xofdays (fromIntegral (diffDays today d0) + 0.5)+ yzero = yof 0+ shade cls x y w h = when (w > 0 && h > 0) $ S.rect ! A.class_ ("shade " <> cls)+ ! A.x (toValue $ num x) ! A.y (toValue $ num y) ! A.width (toValue $ num w) ! A.height (toValue $ num h)+ shade "past-negative" plotleft yzero (xnow - plotleft) (plotbottom - yzero)+ shade "future" xnow plottop (plotright - xnow) (yzero - plottop)+ shade "future-negative" xnow yzero (plotright - xnow) (plotbottom - yzero)+ -- gridlines and y tick labels+ forM_ ticks $ \t -> do+ S.line ! A.class_ (if t == 0 then (if isJust mtoday then "axis zero" else "axis") else "grid")+ ! A.x1 (toValue $ num plotleft) ! A.x2 (toValue $ num plotright) ! A.y1 (toValue $ num (yof t)) ! A.y2 (toValue $ num (yof t))+ S.text_ ! A.class_ "tick" ! A.x (toValue $ num (plotleft - 8)) ! A.y (toValue $ num (yof t + 5)) ! A.textAnchor "end" $ S.toMarkup (ticklabel t)+ -- x labels: periods' labels, thinned to avoid overlap; or ticks at calendar boundaries+ forM_ (placeXLabels width shownxlabels) $ \(x, lbl) ->+ S.text_ ! A.class_ "tick" ! A.x (toValue $ num x) ! A.y (toValue $ num (plotbottom + 21)) ! A.textAnchor "middle" $ S.toMarkup lbl+ -- bars: the stacks side by side (2px apart), each with its positive segments stacked upward and negative ones downward+ forM_ (zip [0 ..] xlabels) $ \(j, lbl) ->+ forM_ (zip [0 :: Int ..] stacks) $ \(k, stk) -> do+ let x = xcenter j - groupwidth / 2 + fromIntegral k * (barwidth + 2)+ stack lbl x (contraFirst [(d, q) | d <- stk, Just q <- [valueAt (dsValues d) j], q > 0]) 1+ stack lbl x (contraFirst [(d, q) | d <- stk, Just q <- [valueAt (dsValues d) j], q < 0]) (-1)+ -- the value labels, if any (see 'pnValueLabels'): above each x position's bars (or below, if they are all negative),+ -- if they all fit (all or none, so that which are shown doesn't depend on their lengths; tooltips have them too)+ when (all ((<= band - 2) . labelWidth) $ catMaybes vlabels) $+ forM_ (zip [0 ..] xlabels) $ \(j, _) -> forM_ (join $ vlabels `atMay` j) $ \t -> do+ let ends sign = [sum [toD q | d <- stk, Just q <- [valueAt (dsValues d) j], signum q == sign] | stk <- stacks]+ up = maximumDef 0 (ends 1)+ down = minimumDef 0 (ends (-1))+ vy = if up > 0 || down == 0 then yof up - 6 else yof down + 14+ S.text_ ! A.class_ (vlabelClass t) ! A.x (toValue $ num (xcenter j)) ! A.y (toValue $ num vy) ! A.textAnchor "middle" $ S.toMarkup t+ -- with a fixed scale, lines are clipped at the plot's edges+ when (isJust mscale) $ S.defs $ S.clippath ! A.id_ (toValue clipid) $+ S.rect ! A.x (toValue $ num plotleft) ! A.y (toValue $ num plottop) ! A.width (toValue $ num (plotright - plotleft)) ! A.height (toValue $ num plotheight)+ let clipLines = if isJust mscale then S.g ! A.clipPath (toValue $ "url(#" <> clipid <> ")") else id+ -- lines+ clipLines $ forM_ lines_ $ \d -> lineSvg (dsClass d) (dsSeries d)+ -- the total: as a line, or as a mark (a thin horizontal line) across each period's bars+ forM_ mtotal $ \t ->+ if seMark t == MarkLine || null bars then clipLines $ lineSvg "total" t+ else let tvals = seriesValues t in+ forM_ (zip [0 ..] xlabels) $ \(j, lbl) -> forM_ (valueAt tvals j) $ \q -> when (hasbars j) $ withTooltip (tooltip lbl t q <> maybe "" (" · " <>) (join $ vlabels `atMay` j)) $ do+ let y = toValue $ num (yof $ toD q)+ halfw = groupwidth / 2 + 4+ x1 = toValue $ num (xcenter j - halfw)+ x2 = toValue $ num (xcenter j + halfw)+ S.line ! A.class_ "mark total" ! A.x1 x1 ! A.x2 x2 ! A.y1 y ! A.y2 y+ -- the average, if any: a dashed line across the plot+ -- (with a solid target over it, since its dashes alone leave gaps)+ forM_ maverage $ \(tip, q) -> withTooltip tip $ do+ let y = yof $ toD q+ S.line ! A.class_ "average" ! A.x1 (toValue $ num plotleft) ! A.x2 (toValue $ num plotright) ! A.y1 (toValue $ num y) ! A.y2 (toValue $ num y)+ hitLine "" (plotleft, y) [(plotright, y)]+ )+ where+ xlabels = case xscale of+ EvenScale ls -> ls+ DateScale ds -> map showDate ds+ n = length xlabels+ -- the x labels shown: for periods, every k'th label, with the smallest k that leaves them all room+ -- (keeping them evenly spaced, even when the end ones are moved inward)+ shownxlabels = case xscale of+ EvenScale _ -> fromMaybe [] $ find fitsall [everykth k | k <- [labelevery .. max labelevery n]]+ DateScale _ -> [(xofday d, lbl) | (d, lbl) <- dateTicks d0 d1]+ everykth k = [(xcenter j, lbl) | (j, lbl) <- zip [0 :: Int ..] xlabels, j `mod` k == 0]+ fitsall ls = length (placeXLabels width ls) == length ls+ -- the date scale, if any: its dates (as an array, for fast lookup), first and last dates, and a date's x position (inset a little from the plot's edges)+ datearray = case xscale of+ DateScale ds -> Just $ Arr.listArray (0, length ds - 1) ds+ EvenScale _ -> Nothing+ (d0, d1) = case xscale of+ DateScale ds@(d:_) -> (minimumDef d ds, maximumDef d ds)+ _ -> (fromGregorian 2000 1 1, fromGregorian 2000 1 1)+ xofday d = xofdays $ fromIntegral (diffDays d d0)+ xofdays k = plotleft + 8 + (plotright - plotleft - 16) * k / fromIntegral (max 1 (diffDays d1 d0))+ -- today, if the plot is to be shaded as of it+ mtoday = if isJust datearray then svgToday else Nothing+ bars = [d | d <- drawn, seMark (dsSeries d) == MarkBar]+ lines_ = [d | d <- drawn, seMark (dsSeries d) == MarkLine]+ -- the bar series in stacks: one, or with the grouped layout, one per group (see 'seGroup')+ stacks = case layout of+ Grouped -> [ [d | d <- bars, seGroup (dsSeries d) == k] | k <- nub $ map (seGroup . dsSeries) bars ]+ Diverging -> [bars]+ -- the extent of the bars in each direction: each stack's sum, at each x position+ stackedsums sign = [ sum [toD q | d <- stk, Just q <- [valueAt (dsValues d) j], signum q == sign] | j <- [0 .. n - 1], stk <- stacks ]+ hasbars j = any (\d -> maybe False (/= 0) $ valueAt (dsValues d) j) bars+ -- contra amounts are drawn nearest the axis+ contraFirst = sortOn (\(d, q) -> not $ isContra (dsSeries d) q)+ pointvalues = [toD q | s <- map dsSeries lines_ ++ maybe [] pure mtotal, Just q <- seValues s]+ datamax = maximumDef 0 (stackedsums 1 ++ pointvalues)+ datamin = minimumDef 0 (stackedsums (-1) ++ pointvalues)+ (lo, hi, ticks, tickdecimals) = panelScale (plotIntervals plotheight) mscale (min 0 datamin) (max 0 datamax)+ ticklabel = tickLabel unit tickdecimals ticks+ plotleft = pad + maximumDef 0 (map (textWidth . ticklabel) ticks) + 12+ plotright = width - pad+ plottop = top + 6 + labelroom+ -- room above the plot for value labels above the tallest bars+ labelroom = if null vlabels then 0 else 14+ plotbottom = plottop + plotheight+ -- a value's y position, within the plot (for bars and marks), or anywhere (for lines, which are clipped)+ yof = clamp plottop plotbottom . yofline+ yofline v = plottop + plotheight * (hi - v) / (hi - lo)+ -- an id for the plot's clipping path, unique within the chart+ clipid = svgIds <> "-clip-" <> num top+ band = (plotright - plotleft) / fromIntegral (max 1 n)+ xcenter j = case datearray of+ Just a | Arr.inRange (Arr.bounds a) j -> xofday (a Arr.! j)+ _ -> plotleft + band * (fromIntegral j + 0.5)+ nbars = max 1 $ length stacks+ -- each bar's width, and the width of a group of side-by-side bars (2px apart)+ barwidth+ | band < 4 = max 1 (band * 0.9 / fromIntegral nbars)+ | otherwise = max 1 $ min 56 ((band * 0.75 - 2 * fromIntegral (nbars - 1)) / fromIntegral nbars)+ groupwidth = fromIntegral nbars * barwidth + 2 * fromIntegral (nbars - 1)+ labelevery = max 1 $ ceiling ((maximumDef 0 (map textWidth xlabels) + 12) / band) :: Int+ stack :: Text -> Double -> [(DrawSeries, Quantity)] -> Double -> Svg+ stack lbl x segs = vstack svgIds (lo, hi) yof x barwidth [(d, q, tooltip lbl (dsSeries d) q) | (d, q) <- segs]+ lineSvg :: Text -> Series -> Svg+ lineSvg cls s = do+ -- runs of consecutive values, so that gaps break the line+ let pts = [ fmap (\q -> (j, xcenter j, yofline (toD q), q)) (valueAt vals j) | let vals = seriesValues s, j <- [0 .. n - 1] ]+ forM_ (runs pts) $ \run ->+ S.polyline ! A.class_ ("line " <> toValue cls)+ ! A.points (toValue $ T.unwords [num x <> "," <> num y | (x, y) <- linePoints [(x, y) | (_, x, y, _) <- run]])+ -- invisible larger targets, for tooltips, and links if any: on a date scale, a circle around each point where+ -- the line changes; on periods, each point's stretch of the line, halfway to its neighbours, so all of it has one+ let target (j, _, _, q) = linked j . withTooltip (tooltip (fromMaybe "" $ xlabels `atMay` j) s q)+ case datearray of+ Just _ -> forM_ (hitPoints $ changes $ catMaybes pts) $ \p@(_, x, y, _) -> target p $+ S.circle ! A.class_ (toValue $ withClass cls "hit") ! A.cx (toValue $ num x) ! A.cy (toValue $ num y) ! A.r "6"+ Nothing -> forM_ (runs pts) $ \run -> let hs = hitPoints run in+ forM_ (zip3 (Nothing : map Just hs) hs (map Just (drop 1 hs) ++ [Nothing])) $ \(mprev, p@(_, x, y, _), mnext) -> target p $+ hitLine cls (x, y) $ stretchEnds mprev p mnext+ -- the ends of a point's stretch of a line: halfway to the previous point and to the next; or a lone point's short dash+ stretchEnds mprev (_, x, y, _) mnext = case (mprev, mnext) of+ (Nothing, Nothing) -> [(x - 6, y), (x + 6, y)]+ _ -> [((x + x') / 2, (y + y') / 2) | Just (_, x', y', _) <- [mprev, mnext]]+ -- An invisible line a little wider than the visible ones, as a tooltip target: from a point out to each of the given ends.+ -- With the point first, and the line's class (its colour), a page's script can mark the point and show the colour.+ hitLine cls (x, y) ends = S.path ! A.class_ (toValue $ withClass cls "hit-line")+ ! A.d (toValue $ T.unwords $ concat [["M", num x, num y, "L", num ex, num ey] | (ex, ey) <- ends])+ withClass cls c = T.unwords $ c : [cls | not (T.null cls)]+ -- the points a line is drawn through: thinned, and stepped on a date scale; or for a lone point+ -- (eg a single period's, or a register's one transaction), a short dash across it, like the legend's,+ -- since a line through one point is not drawn+ linePoints ps = case ps of+ [(x, y)] -> [(x - 6, y), (x + 6, y)]+ _ -> thinPoints $ (if isJust datearray then dropFlat . steps else id) ps+ -- some markup for the given x position, as a link if it has one+ linked j m = case svgPointLink j of+ Just url -> S.a ! customAttribute "href" (toValue url) ! customAttribute "tabindex" "-1" $ m+ Nothing -> m+ -- The points of a line by date where its value changes, and its first point. At the others nothing happened+ -- to it, eg a register's transactions in other commodities.+ changes ps = take 1 ps ++ [p | ((_, _, _, q0), p@(_, _, _, q)) <- zip ps (drop 1 ps), q /= q0]+ -- The points of a line given tooltip targets: all of them, or beyond 400, the last point in each 4px column,+ -- which keeps the SVG small while the targets (12px across) still cover the whole line.+ hitPoints ps+ | length ps <= 400 = ps+ | otherwise = M.elems $ M.fromList [(floor (x / 4) :: Integer, p) | p@(_, x, _, _) <- ps]+ tooltip :: Text -> Series -> Quantity -> Text+ tooltip lbl s q = T.intercalate " · " (filter (not . T.null) [lbl, lbFull (seLabel s), showValue unit q]) <> tipLines s++-- | Place x axis labels: centred at their x positions, but kept within the chart,+-- leaving out any that would overlap the previous one (eg after being moved inward from the chart's edge).+placeXLabels :: Double -> [(Double, Text)] -> [(Double, Text)]+placeXLabels width = reverse . foldl' place []+ where+ place kept (x, lbl) =+ let halfw = textWidth lbl / 2+ x' = max (pad + halfw) $ min (width - pad - halfw) x+ in case kept of+ (px, plbl) : _ | x' - halfw < px + textWidth plbl / 2 + 12 -> kept+ _ -> (x', lbl) : kept++-- | Draw series of categories (eg accounts): as vertical bars, or as horizontal bars when there are more than 'maxColumns' categories.+-- Categories with no values at all (eg accounts without this commodity) are left out.+-- With a single series, each category's bar has its own account type's colour, if known.+-- Categories with value labels (see 'pnValueLabels') are always drawn as horizontal bars, which have room for them all.+categoriesSvg :: Text -> Double -> Double -> Double -> Maybe Quantity -> Amount -> [DrawSeries] -> Maybe Series -> Maybe Series -> [Maybe Text] -> [ChartLabel] -> (Double, Svg)+categoriesSvg ids width plotheight top mscale unit drawn mtotal mtotalmark vlabels labels+ | length rows <= maxColumns && null vlabels = columnsSvg ids width plotheight top mscale unit rows rowValue rowTip valueText mmark+ | otherwise = barsSvg ids width top mscale unit rows rowValue rowTip (not $ null vlabels) valueText mmark+ where+ rows = [ (l, j, [(categoryColoured j l d, q) | d <- drawn, Just q <- [valueAt (dsValues d) j]])+ | (j, l) <- zip [0 ..] labels, not $ all (isNothing . flip valueAt j . dsValues) drawn ]+ categoryColoured j lbl d = case (drawn, lbType lbl) of+ ([_], Just at) -> d{dsClass = colourClass $ TypeColour (mainAccountType at) (fromMaybe 0 $ tints `atMay` j)}+ _ -> d+ -- with a single series, each category's tint of its type's colour+ tints = case drawn of+ [d] -> categoryTints labels (seValues $ dsSeries d)+ _ -> []+ mtotalvals = seriesValues <$> mtotal+ -- the name of the total, if it is to be marked across the bars, at the value+ mmark = lbFull . seLabel <$> mtotalmark+ -- A total that isn't drawn (MarkNone): its value, and the label shown instead if any, in the tooltips of each category's bar,+ -- eg "Value 2,500.00 USD · +66.7%".+ rowTip j = case (mtotal, rowValue j) of+ (Just t, Just q) | seMark t == MarkNone ->+ (lbFull (seLabel t) <> " " <> showValue unit q) : maybe [] pure (mfilter (/= showValue unit q) $ valueText j q)+ _ -> []+ -- the text to show for each category's value: the value, or the label given instead (see 'pnValueLabels'), if any+ valueText j q+ | null vlabels = Just $ showValue unit q+ | otherwise = join $ vlabels `atMay` j+ -- the value to show for each category: the total's, or the single series'+ rowValue j = case (mtotal, drawn) of+ (Just _, _) -> mtotalvals >>= flip valueAt j+ (_, [d]) -> valueAt (dsValues d) j+ _ -> Nothing++-- | The most categories to draw as vertical bars; beyond this, they are drawn as horizontal bars (rows), which can show many more names.+-- (Or always, when they have value labels; see 'categoriesSvg'.)+maxColumns :: Int+maxColumns = 30++-- | Draw categories as vertical bars (stacked if several series), with their names below (angled if they don't fit),+-- and their values above the bars (when they fit), in a plot this high.+-- The values are shown as the given function says, if at all. If a total's name is given, the values (the total's) are also marked across the bars.+columnsSvg :: Text -> Double -> Double -> Double -> Maybe Quantity -> Amount -> [(ChartLabel, Int, [(DrawSeries, Quantity)])] -> (Int -> Maybe Quantity) -> (Int -> [Text]) -> (Int -> Quantity -> Maybe Text) -> Maybe Text -> (Double, Svg)+columnsSvg ids width plotheight top mscale unit rows rowValue rowTip valueText mmark = (plotheight + 22 + negroom + labelheight, do+ -- gridlines and y tick labels+ forM_ ticks $ \t -> do+ S.line ! A.class_ (if t == 0 then "axis" else "grid")+ ! A.x1 (toValue $ num plotleft) ! A.x2 (toValue $ num plotright) ! A.y1 (toValue $ num (yof t)) ! A.y2 (toValue $ num (yof t))+ S.text_ ! A.class_ "tick" ! A.x (toValue $ num (plotleft - 8)) ! A.y (toValue $ num (yof t + 5)) ! A.textAnchor "end" $ S.toMarkup (ticklabel t)+ forM_ (zip [0 :: Int ..] rows) $ \(i, (lbl, j, segs)) -> do+ let x = xcenter i+ name = shortName lbl+ ly = plotbottom + negroom + 16+ -- the category's name, below; angled (reading upward to the bar) if the names don't fit+ if angled+ then S.text_ ! A.class_ "label" ! A.x (toValue $ num (x + 4)) ! A.y (toValue $ num ly) ! A.textAnchor "end"+ ! A.transform (toValue $ "rotate(-45 " <> num (x + 4) <> " " <> num ly <> ")") $ S.toMarkup name+ else S.text_ ! A.class_ "label" ! A.x (toValue $ num x) ! A.y (toValue $ num ly) ! A.textAnchor "middle" $ S.toMarkup name+ -- the bar+ let tip d q = T.intercalate " · " (nub $ [lbFull lbl, lbFull (seLabel $ dsSeries d), showValue unit q] ++ rowTip j) <> tipLines (dsSeries d)+ bx = x - barwidth / 2+ vstack ids (lo, hi) yof bx barwidth [(d, q, tip d q) | (d, q) <- segs, q > 0] 1+ vstack ids (lo, hi) yof bx barwidth [(d, q, tip d q) | (d, q) <- segs, q < 0] (-1)+ -- the total, if marked: a thin line across the bar+ forM_ mmark $ \tname -> forM_ (rowValue j) $ \q -> withTooltip (T.intercalate " · " $ nub $ [lbFull lbl, tname, showValue unit q] ++ maybe [] pure (valueText j q)) $ do+ let y = toValue $ num (yof $ toD q)+ S.line ! A.class_ "mark total" ! A.x1 (toValue $ num (bx - 4)) ! A.x2 (toValue $ num (bx + barwidth + 4)) ! A.y1 y ! A.y2 y+ -- the value, above the bar (or below, if negative), if it fits+ forM_ (rowValue j) $ \q -> forM_ (valueText j q) $ \v -> do+ let pos = sum [toD a | (_, a) <- segs, a > 0]+ neg = sum [toD a | (_, a) <- segs, a < 0]+ cliproom = if pos > hi || neg < lo then 6 else 0 -- room for a clip mark+ vy = if q >= 0 then yof pos - 6 - cliproom else yof neg + 14 + cliproom+ when (textWidth v <= band - 2) $+ S.text_ ! A.class_ "value" ! A.x (toValue $ num x) ! A.y (toValue $ num vy) ! A.textAnchor "middle" $ S.toMarkup v+ )+ where+ n = length rows+ stackedsums sign = [sum [toD q | (_, q) <- segs, signum q == sign] | (_, _, segs) <- rows]+ (lo, hi, ticks, tickdecimals) = panelScale (plotIntervals plotheight) mscale (minimumDef 0 $ stackedsums (-1)) (maximumDef 0 $ stackedsums 1)+ ticklabel = tickLabel unit tickdecimals ticks+ -- the plot's left edge: after the tick labels, and far enough right that angled names don't extend beyond the chart's left edge+ ticksright = pad + maximumDef 0 (map (textWidth . ticklabel) ticks) + 12+ plotleft+ | angled = max ticksright $ maximumDef 0 [pad + 0.71 * textWidth (shortName l) - 4 - bandwith ticksright * (fromIntegral i + 0.5) | (i, (l, _, _)) <- zip [0 :: Int ..] rows]+ | otherwise = ticksright+ plotright = width - pad+ plottop = top + 20 -- leaving room for values above the bars+ plotbottom = plottop + plotheight+ yof v = plottop + plotheight * (hi - clamp lo hi v) / (hi - lo)+ -- the width of each category's band, with the plot starting at this x position+ bandwith left = (plotright - left) / fromIntegral (max 1 n)+ band = bandwith plotleft+ xcenter i = plotleft + band * (fromIntegral i + 0.5)+ barwidth = max 1 $ min 64 (band * 0.6)+ -- names: full account names (since there's no indentation), shortened if very long+ shortName l = let t = lbFull l in if T.length t > 30 then T.take 29 t <> "…" else t+ namewidth = maximumDef 0 [textWidth (shortName l) | (l, _, _) <- rows]+ -- whether names are angled: decided with the widest band (before any room is made for angled names), to avoid a cycle+ angled = namewidth > bandwith ticksright - 4+ labelheight = if angled then namewidth * 0.71 + 16 else 24+ -- room below the plot for the values of negative bars, which may reach its bottom+ negroom = if any (any ((< 0) . snd) . (\(_, _, segs) -> segs)) rows then (if isJust mscale then 22 else 16) else 0++-- | Draw categories as horizontal bars (rows; stacked if several series), with their names on the left (indented as in the report)+-- and an aligned value column on the right.+-- The values are shown as the given function says, if at all. If a total's name is given, the values (the total's) are also marked across the bars.+-- If the flag is true, the values' text is value labels (see 'pnValueLabels'), shown smaller.+barsSvg :: Text -> Double -> Double -> Maybe Quantity -> Amount -> [(ChartLabel, Int, [(DrawSeries, Quantity)])] -> (Int -> Maybe Quantity) -> (Int -> [Text]) -> Bool -> (Int -> Quantity -> Maybe Text) -> Maybe Text -> (Double, Svg)+barsSvg ids width top mscale unit rows rowValue rowTip labelled valueText mmark = (fromIntegral (length rows) * rowHeight + 32, do+ -- gridlines and x tick labels (labels thinned to avoid overlap, always including zero)+ forM_ ticks $ \t -> do+ S.line ! A.class_ (if t == 0 then "axis" else "grid")+ ! A.x1 (toValue $ num (xof t)) ! A.x2 (toValue $ num (xof t)) ! A.y1 (toValue $ num plottop) ! A.y2 (toValue $ num plotbottom)+ when (round (t / tickstep) `mod` labelevery == (0 :: Integer)) $+ S.text_ ! A.class_ "tick" ! A.x (toValue $ num (xof t)) ! A.y (toValue $ num (plotbottom + 21)) ! A.textAnchor "middle" $ S.toMarkup (ticklabel t)+ forM_ (zip [0 :: Int ..] rows) $ \(i, (lbl, j, segs)) -> do+ let ymid = plottop + rowHeight * (fromIntegral i + 0.5)+ S.text_ ! A.class_ "label" ! A.x (toValue $ num (pad + 12 * fromIntegral (lbIndent lbl))) ! A.y (toValue $ num (ymid + 5))+ $ S.toMarkup (lbShort lbl)+ forM_ (rowValue j) $ \q -> forM_ (valueText j q) $ \v ->+ S.text_ ! A.class_ (if labelled then vlabelClass v else "value") ! A.x (toValue $ num (width - pad)) ! A.y (toValue $ num (ymid + 5)) ! A.textAnchor "end"+ $ S.toMarkup v+ stack lbl (rowTip j) ymid [(d, q) | (d, q) <- segs, q > 0] 1+ stack lbl (rowTip j) ymid [(d, q) | (d, q) <- segs, q < 0] (-1)+ -- the total, if marked: a thin line across the bar+ forM_ mmark $ \tname -> forM_ (rowValue j) $ \q -> withTooltip (T.intercalate " · " $ nub $ [lbFull lbl, tname, showValue unit q] ++ maybe [] pure (valueText j q)) $ do+ let x = toValue $ num (xof $ toD q)+ S.line ! A.class_ "mark total" ! A.x1 x ! A.x2 x ! A.y1 (toValue $ num (ymid - thickness / 2 - 4)) ! A.y2 (toValue $ num (ymid + thickness / 2 + 4))+ )+ where+ stackedsums sign = [sum [toD q | (_, q) <- segs, signum q == sign] | (_, _, segs) <- rows]+ (lo, hi, ticks, tickdecimals) = panelScale 5 mscale (minimumDef 0 $ stackedsums (-1)) (maximumDef 0 $ stackedsums 1)+ ticklabel = tickLabel unit{acommodity = ""} tickdecimals []+ labelwidth = min (width * 0.4) $ maximumDef 0 [12 * fromIntegral (lbIndent l) + textWidth (lbShort l) | (l, _, _) <- rows]+ valuewidth = maximumDef 0 [(if labelled then labelWidth else textWidth) v | (_, j, _) <- rows, Just q <- [rowValue j], Just v <- [valueText j q]]+ -- leave room for half of a tick label at each end+ edge = maximumDef 0 (map (textWidth . ticklabel) ticks) / 2+ plotleft = pad + max labelwidth edge + 12+ plotright = width - pad - max valuewidth edge - 16+ plottop = top + 4+ plotbottom = plottop + rowHeight * fromIntegral (length rows)+ xof v = plotleft + (plotright - plotleft) * (clamp lo hi v - lo) / (hi - lo)+ tickstep = case ticks of t1:t2:_ -> t2 - t1; _ -> 1+ labelevery = max 1 $ ceiling ((maximumDef 0 (map (textWidth . ticklabel) ticks) + 12) / max 1 (xof tickstep - xof 0)) :: Integer+ thickness = 16+ stack :: ChartLabel -> [Text] -> Double -> [(DrawSeries, Quantity)] -> Double -> Svg+ stack lbl extratip ymid segs sign = do+ let cums = scanl1 (+) (map (toD . snd) segs)+ starts = 0 : cums+ clipped = any (\c -> c > hi || c < lo) (lastMay cums)+ outer = maybe (xof 0) xof (lastMay cums)+ roundedEnd ids (not clipped) False (xof 0) (ymid - thickness / 2) thickness (outer - xof 0) $+ forM_ (zip3 [0 :: Int ..] segs (zip starts cums)) $ \(k, (d, q), (c0, c1)) -> do+ let gap = if k > 0 && abs (xof c1 - xof c0) >= 4 then 2 else 0 -- no gap for tiny segments, which it would hide+ xbase = xof c0 + sign * gap -- the end nearer the axis, after the gap (the sums are negative for negative segments)+ len = (xof c1 - xbase) * sign+ let path = toValue $ barPath False xbase (ymid - thickness / 2) thickness (sign * len) False+ when (len > 0.5) $ withTooltip (T.intercalate " · " (nub $ [lbFull lbl, lbFull (seLabel $ dsSeries d), showValue unit q] ++ extratip) <> tipLines (dsSeries d)) $ do+ S.path ! A.class_ ("fill " <> toValue (dsClass d)) ! A.d path+ when (isHatched (dsSeries d) q) $ S.path ! A.fill (toValue $ "url(#" <> hatchId ids <> ")") ! A.d path+ -- a bar clipped by a fixed scale has a small triangle beyond its end+ when clipped $ clipMark False (xof $ if sign > 0 then hi else lo) ymid thickness sign++-- | One direction of a vertical stacked bar, with its left edge at x and the given width, on a y scale:+-- segments (each with its series, value and tooltip) from zero outward (up if sign is 1, down if -1),+-- 2px apart (except tiny ones, which a gap would hide), with a rounded end (see 'roundedEnd').+-- If the bar extends beyond the y scale's range (lo, hi), it is clipped, with a small triangle beyond its end instead.+vstack :: Text -> (Double, Double) -> (Double -> Double) -> Double -> Double -> [(DrawSeries, Quantity, Text)] -> Double -> Svg+vstack ids (lo, hi) yof x width segs sign = do+ let cums = scanl1 (+) [toD q | (_, q, _) <- segs]+ starts = 0 : cums+ clipped = any (\c -> c > hi || c < lo) (lastMay cums)+ outer = maybe (yof 0) yof (lastMay cums)+ roundedEnd ids (not clipped) True x (yof 0) width (outer - yof 0) $+ forM_ (zip3 [0 :: Int ..] segs (zip starts cums)) $ \(k, (d, q, tip), (c0, c1)) -> do+ let gap = if k > 0 && abs (yof c1 - yof c0) >= 4 then 2 else 0+ ybase = yof c0 - sign * gap -- the end nearer zero, after the gap+ len = (ybase - yof c1) * sign -- positive when there is something to draw+ path = toValue $ barPath True x ybase width (-sign * len) False+ when (len > 0.5) $ withTooltip tip $ do+ S.path ! A.class_ ("fill " <> toValue (dsClass d)) ! A.d path+ -- a contra amount or shortfall is hatched+ when (isHatched (dsSeries d) q) $ S.path ! A.fill (toValue $ "url(#" <> hatchId ids <> ")") ! A.d path+ when clipped $ clipMark True (yof $ if sign > 0 then hi else lo) (x + width / 2) width sign++-- | Draw a bar's segments (if rounded) clipped to the bar's outline with a rounded outer end, so that the end+-- is rounded the same however thin its outermost segment. The bar is vertical or horizontal, with its base at a, b+-- (its left or top edge, at the axis), the given size across, and length (negative for up or left).+-- The clipping path's id, unique within the chart, is made from these, after the chart's prefix (see 'svgIds').+roundedEnd :: Text -> Bool -> Bool -> Double -> Double -> Double -> Double -> Svg -> Svg+roundedEnd ids rounded vertical a b size len segments+ | not rounded || abs len < 0.5 = segments+ | otherwise = do+ S.defs $ S.clippath ! A.id_ (toValue clipid) $ S.path ! A.d (toValue $ barPath vertical a b size len True)+ S.g ! A.clipPath (toValue $ "url(#" <> clipid <> ")") $ segments+ where+ clipid = ids <> "-clip-bar" <> T.intercalate "_" [if vertical then "v" else "h", num a, num b, num len]++-- | The id of the hatching pattern for contra amounts and shortfalls, after the chart's prefix (see 'svgIds').+hatchId :: Text -> Text+hatchId ids = ids <> "-hatch"++-- | A small triangle pointing outward from the edge of a plot, marking a bar that was clipped there:+-- for a vertical bar (at y position edge, centred on x position mid) or a horizontal one (at x position edge, centred on y position mid).+-- sign is the direction in which the bar grows (1: up or right, -1: down or left).+clipMark :: Bool -> Double -> Double -> Double -> Double -> Svg+clipMark vertical edge mid barsize sign =+ S.polygon ! A.class_ "clip" ! A.points (toValue $ T.unwords [num a <> "," <> num b | (a, b) <- map orient pts])+ where+ w = max 6 $ min 10 barsize+ -- the points as (position across the bar, distance outward from the edge)+ pts = [(mid - w / 2, 0), (mid + w / 2, 0), (mid, w / 2)]+ orient (across, out)+ | vertical = (across, edge - sign * out)+ | otherwise = (edge + sign * out, across)++-- | The points of a step line through these points: each value holds until the next point's x position.+steps :: [(Double, Double)] -> [(Double, Double)]+steps ps = take 1 ps ++ concat (zipWith (\(_, py) (x, y) -> [(x, py), (x, y)]) ps (drop 1 ps))++-- | Leave out the points inside a run of points at the same height, which a line draws the same without:+-- eg a step line's long flat stretches, as when most of a register's transactions are in other commodities.+dropFlat :: [(Double, Double)] -> [(Double, Double)]+dropFlat (a : b : c : rest)+ | snd a == snd b && snd b == snd c = dropFlat (a : c : rest)+ | otherwise = a : dropFlat (b : c : rest)+dropFlat ps = ps++-- | Reduce a line's points to at most four per pixel column (the first, lowest, highest and last, in their original order),+-- which draws the same line, but keeps the SVG small when there are many more points than pixels (eg a long register).+thinPoints :: [(Double, Double)] -> [(Double, Double)]+thinPoints = concatMap thin . groupBy ((==) `on` (column . fst))+ where+ column :: Double -> Integer+ column = round+ thin ps+ | length ps <= 4 = ps+ | otherwise = M.elems $ M.fromList $ catMaybes [headMay indexed, extreme (<), extreme (>), lastMay indexed]+ where+ indexed = zip [0 :: Int ..] ps+ -- the first point whose y is better than all others' by this comparison+ extreme better = foldl' (\acc p -> case acc of+ Just (_, (_, y')) | not (snd (snd p) `better` y') -> acc+ _ -> Just p) Nothing indexed++-- | Up to 8 ticks for a date axis from the first to the last date, at calendar boundaries+-- (every 1, 2, 7 or 14 days, every 1, 2, 3 or 6 months, or every 1, 2, 5, 10.. years), with labels.+dateTicks :: Day -> Day -> [(Day, Text)]+dateTicks d0 d1 = fromMaybe [] $ find ((<= 8) . length) candidates+ where+ (y0, _, _) = toGregorian d0+ (y1, _, _) = toGregorian d1+ candidates = [dayticks k | k <- [1, 2, 7, 14]] ++ [monthticks k | k <- [1, 2, 3, 6]] ++ [yearticks k | k <- [1, 2, 5, 10, 20, 50, 100, 1000]]+ inrange d = d >= d0 && d <= d1+ dayticks k = [(d, showDate d) | d <- takeWhile (<= d1) $ iterate (addDays k) d0]+ monthticks k = [ (d, T.pack $ printf "%04d-%02d" y m)+ | y <- [y0 .. y1], m <- [1 .. 12], (m - 1) `mod` k == 0, let d = fromGregorian y m 1, inrange d ]+ yearticks k = [ (d, T.pack $ show y) | y <- [y0 .. y1], y `mod` k == 0, let d = fromGregorian y 1 1, inrange d ]++-- | A series' more lines for its tooltips (eg the accounts an "other" series combines), each after a newline.+tipLines :: Series -> Text+tipLines s = T.concat ["\n" <> l | l <- lbTipLines $ seLabel s]++-- | Give some markup a tooltip, by grouping it with an SVG title.+withTooltip :: Text -> Svg -> Svg+withTooltip t m = S.g $ S.title (S.toMarkup t) >> m++-- | An SVG path for a bar (segment) growing from a base line, with its far end rounded (radius up to 4px) if requested.+-- Vertical: base line at y=b, from x=a with the given width, growing by len pixels (negative is upward, since y grows downward).+-- Horizontal: base line at x=a, from y=b with the given thickness, growing by len pixels (positive is rightward).+barPath :: Bool -> Double -> Double -> Double -> Double -> Bool -> Text+barPath vertical a b size len rounded+ | vertical =+ let e = b + len in T.unwords+ [ "M", num a, num b+ , "V", num (e - sgn * r)+ , "Q", num a, num e, num (a + r), num e+ , "H", num (a + size - r)+ , "Q", num (a + size), num e, num (a + size), num (e - sgn * r)+ , "V", num b, "Z" ]+ | otherwise =+ let e = a + len in T.unwords+ [ "M", num a, num b+ , "H", num (e - sgn * r)+ , "Q", num e, num b, num e, num (b + r)+ , "V", num (b + size - r)+ , "Q", num e, num (b + size), num (e - sgn * r), num (b + size)+ , "H", num a, "Z" ]+ where+ sgn = if len < 0 then -1 else 1+ r = if rounded then minimum [3, size / 2, abs len] else 0++-- | The scale for a panel's values, given their range (which should include 0), divided into about this many intervals:+-- a nice scale covering it ('niceScale'), or with a fixed scale, exactly the range it spans ('scaleSpans'),+-- with the nice scale's ticks that are within it.+panelScale :: Int -> Maybe Quantity -> Double -> Double -> (Double, Double, [Double], Int)+panelScale intervals mscale datamin datamax = case mscale of+ Just s | s > 0 ->+ let (hi, neg) = scaleSpans (toD s) (max 0 datamax) (abs $ min 0 datamin)+ lo = negate neg+ (_, _, ticks, decimals) = niceScale intervals lo hi+ eps = (hi - lo) * 1e-9+ in (lo, hi, filter (\t -> t >= lo - eps && t <= hi + eps) ticks, decimals)+ _ -> niceScale intervals datamin datamax++-- | Limit a value to a range.+clamp :: Double -> Double -> Double -> Double+clamp lo hi = max lo . min hi++-- | A "nice" linear scale covering the given range (which should include 0), in about this many intervals:+-- its low and high ends, its ticks (at multiples of 1, 2 or 5 times a power of ten),+-- and the number of decimal places needed to show the ticks.+niceScale :: Int -> Double -> Double -> (Double, Double, [Double], Int)+niceScale intervals lo0 hi0 = (lo, hi, ticks, decimals)+ where+ (a, b) = if hi0 - lo0 <= 0 then (lo0, lo0 + 1) else (lo0, hi0)+ -- choose the 1, 2 or 5 times a power of ten nearest the step that would give that many intervals (as d3 does)+ rawstep = (b - a) / fromIntegral intervals+ magnitude = 10 ** fromIntegral (floor (logBase 10 rawstep) :: Int)+ err = rawstep / magnitude+ step | err >= sqrt 50 = 10 * magnitude+ | err >= sqrt 10 = 5 * magnitude+ | err >= sqrt 2 = 2 * magnitude+ | otherwise = magnitude+ kmin = floor (a / step) :: Integer+ kmax = ceiling (b / step) :: Integer+ ticks = [fromIntegral k * step | k <- [kmin .. kmax]]+ lo = fromIntegral kmin * step+ hi = fromIntegral kmax * step+ decimals = max 0 $ negate (floor (logBase 10 step + 1e-9) :: Int)++-- | The value of a tick, as a quantity with the given number of decimal places.+-- | A y axis tick's label: its value in the unit's style, with this many decimal places.+-- To reduce clutter, the unit's commodity is shown only on the outermost of these ticks+-- (the top one, or the bottom one if the top one is zero).+tickLabel :: Amount -> Int -> [Double] -> Double -> Text+tickLabel unit decimals ticks t = showValue (withPrecision decimals u) (tickQuantity decimals t)+ where+ u = if Just t == unittick then unit else unit{acommodity = ""}+ unittick = case lastMay ticks of+ Just top | top /= 0 -> Just top+ _ -> headMay ticks++tickQuantity :: Int -> Double -> Quantity+tickQuantity decimals = realFracToDecimal (fromIntegral decimals)++-- | Show a quantity as an amount in the given unit (commodity and style).+showValue :: Amount -> Quantity -> Text+showValue unit q = T.pack $ showAmountWith oneLineNoCostFmt unit{aquantity = q}++-- | The unit with its display precision set to this many decimal places.+withPrecision :: Int -> Amount -> Amount+withPrecision d unit = unit{astyle = (astyle unit){asprecision = Precision (fromIntegral d)}}++toD :: Quantity -> Double+toD = realToFrac++-- | A coordinate for SVG, rounded to one decimal place, without a trailing ".0".+num :: Double -> Text+num x+ | r == 0 = "0"+ | otherwise = let t = T.pack (printf "%.1f" r) in fromMaybe t (T.stripSuffix ".0" t)+ where r = fromIntegral (round (x * 10) :: Integer) / 10 :: Double++-- | The runs of consecutive Just values in a list.+runs :: [Maybe a] -> [[a]]+runs ms = case dropWhile isNothing ms of+ [] -> []+ rest -> let (run, more) = span (not . isNothing) rest in catMaybes run : runs more++-- | The CSS class for a colour. (The rules are in 'chartStylesheet'.)+colourClass :: Colour -> Text+colourClass c = case c of+ TypeColour at k -> "t" <> typeCode (mainAccountType at) <> T.pack (show (k `mod` maxTints))+ IndexColour k -> "s" <> T.pack (show (k `mod` 8))+ LoneColour -> "lone"+ NeutralColour -> "neutral"+ OtherColour Nothing -> "other"+ OtherColour (Just at) -> "o" <> typeCode (mainAccountType at)+ TotalColour -> "total"++-- | A short code for each main account type, for CSS class names.+typeCode :: AccountType -> Text+typeCode at = case at of+ Asset -> "a"+ Liability -> "l"+ Equity -> "e"+ Revenue -> "r"+ Expense -> "x"+ _ -> "e"++-- | The chart's styles: a colour-blind-safe categorical palette (8 slots) and chart chrome colours,+-- with a dark variant used when the viewer prefers a dark colour scheme.+-- Colours are written literally in each rule (rather than as CSS custom properties),+-- since some SVG renderers (eg librsvg, used by many image viewers) don't support those.+-- Charts include these styles, unless drawn without them for a page that supplies them (see 'SvgOptions').+chartStylesheet :: Bool -> Text+chartStylesheet = stylesheet True++-- | The chart's styles, with the shading's or without them, as a chart includes them+-- when it is shaded as of today or not.+stylesheet :: Bool -> Bool -> Text+stylesheet shaded dark = T.unlines $+ [ ".hledger-chart{max-width:100%;height:auto;font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif;font-size:14px}"+ , ".hledger-chart .title{font-size:17px;font-weight:600}"+ , ".hledger-chart .heading{font-size:15px;font-weight:600}"+ , ".hledger-chart .value,.hledger-chart .tick{font-variant-numeric:tabular-nums}"+ , ".hledger-chart .vlabel{font-size:12px}"+ , ".hledger-chart .grid,.hledger-chart .axis{stroke-width:1}"+ , ".hledger-chart .line{fill:none;stroke-width:3;stroke-linejoin:round;stroke-linecap:round}"+ , ".hledger-chart .mark{stroke-width:2.5}"+ , ".hledger-chart .average{stroke-width:2;stroke-dasharray:5 4}"+ , ".hledger-chart .hit,.hledger-chart .plot{fill:transparent}"+ , ".hledger-chart .hit-line{fill:none;stroke:transparent;stroke-width:8;stroke-linecap:round}"+ , ".hledger-chart .hatch{stroke-width:2.5}"+ ]+ ++ colourRules False lightcolours+ ++ (if dark then ["@media (prefers-color-scheme:dark){"] ++ colourRules True darkcolours ++ ["}"] else [])+ where+ -- the chart chrome's colours, and the series' colours (from "Hledger.Write.Chart.Palette")+ colourRules isdark cs =+ [ ".hledger-chart " <> sel <> "{" <> prop <> ":" <> colour <> "}"+ | (sel, prop, role) <- rules, Just colour <- [lookup role cs] ]+ ++ concat [ [ ".hledger-chart .fill." <> cls <> "{fill:" <> hex <> "}", ".hledger-chart .line." <> cls <> "{stroke:" <> hex <> "}" ]+ | c <- seriescolours, let cls = colourClass c, let hex = colourHex isdark c ]+ -- value labels' gains and losses (see 'vlabelClass')+ ++ [ ".hledger-chart .vlabel." <> cls <> "{fill:" <> colourHex isdark (TypeColour at 0) <> "}"+ | (cls, at) <- [("gain", Revenue), ("loss", Expense)] ]+ seriescolours =+ [TypeColour at k | at <- [Asset, Liability, Equity, Revenue, Expense], k <- [0 .. maxTints - 1]]+ ++ map IndexColour [0 .. 7] ++ [OtherColour t | t <- Nothing : map Just [Asset, Liability, Equity, Revenue, Expense]] ++ [LoneColour, NeutralColour]+ rules =+ [ (".bg", "fill", "surface"), (".title", "fill", "ink"), (".heading", "fill", "ink")+ , (".label", "fill", "ink2"), (".value", "fill", "ink2"), (".tick", "fill", "muted"), (".note", "fill", "muted")+ , (".grid", "stroke", "grid"), (".axis", "stroke", "axis")+ , (".line.total", "stroke", "ink"), (".mark.total", "stroke", "ink"), (".average", "stroke", "ink"), (".clip", "fill", "ink"), (".hatch", "stroke", "surface")+ ]+ -- the shading as of today (see 'SvgOptions'), tinted with the expenses' red where values are below zero+ ++ (if shaded+ then [ (".shade.past-negative", "fill", "pastnegative"), (".shade.future", "fill", "future"), (".shade.future-negative", "fill", "futurenegative")+ , (".axis.zero", "stroke", "zero") ]+ else [])+ lightcolours :: [(Text, Text)]+ lightcolours =+ [ ("surface", "#fcfcfb"), ("ink", "#0b0b0b"), ("ink2", "#52514e"), ("muted", "#898781"), ("grid", "#e1e0d9"), ("axis", "#c3c2b7")+ , ("pastnegative", "#fbe4e4"), ("future", "#f1f0ec"), ("futurenegative", "#f0dcda"), ("zero", "#e34948") ]+ darkcolours =+ [ ("surface", "#1a1a19"), ("ink", "#ffffff"), ("ink2", "#c3c2b7"), ("muted", "#898781"), ("grid", "#2c2c2a"), ("axis", "#383835")+ , ("pastnegative", "#432929"), ("future", "#252524"), ("futurenegative", "#3a2a28"), ("zero", "#e66767") ]++tests_Hledger_Write_Chart_Svg :: TestTree+tests_Hledger_Write_Chart_Svg = testGroup "Write.Chart.Svg" [+ testCase "num" $ do+ map num [0, -0.04, 1, 1.26, -3.14159, 760] @?= ["0", "0", "1", "1.3", "-3.1", "760"]+ ,testCase "niceScale" $ do+ niceScale 5 0 87 @?= (0, 100, [0, 20, 40, 60, 80, 100], 0)+ niceScale 5 (-15) 100 @?= (-20, 100, [-20, 0, 20, 40, 60, 80, 100], 0)+ niceScale 5 0 0 @?= (0, 1, [0, 0.2, 0.4, 0.6000000000000001, 0.8, 1], 1)+ niceScale 5 0 7.3 @?= (0, 8, [0, 2, 4, 6, 8], 0)+ -- fewer intervals, for a shorter plot+ niceScale 5 0 117 @?= (0, 120, [0, 20, 40, 60, 80, 100, 120], 0)+ niceScale 3 0 117 @?= (0, 150, [0, 50, 100, 150], 0)+ ,testCase "plotIntervals" $ do+ map plotIntervals [260, 150, 100, 40] @?= [5, 3, 2, 2]+ ,testCase "barPath" $ do+ barPath True 10 100 20 (-50) True @?= "M 10 100 V 53 Q 10 50 13 50 H 27 Q 30 50 30 53 V 100 Z"+ barPath False 10 5 12 (-30) False @?= "M 10 5 H -20 Q -20 5 -20 5 V 17 Q -20 17 -20 17 H 10 Z"+ ,testCase "a long line has tooltips all along it, at most one per 4px column" $ do+ let hits = T.count "<circle class=\"hit" $ svgText defaultSvgOptions $ lineChart 1000+ assertBool ("tooltip targets: " ++ show hits) (hits >= 150 && hits <= 220)+ ,testCase "a line by date has tooltips where it changes" $ do+ T.count "<circle class=\"hit" (svgText defaultSvgOptions $ lineChartOf [1, 1, 1, 2, 2, 2]) @?= 2+ ,testCase "dropFlat" $ do+ dropFlat [(0, 1), (1, 1), (1, 1), (2, 1), (2, 2), (3, 2)] @?= [(0, 1), (2, 1), (2, 2), (3, 2)]+ ,testCase "a line's points can link somewhere, out of the tab order" $ do+ let svg = svgText defaultSvgOptions{svgPointLink = \j -> if even j then Just ("#t" <> T.pack (show j)) else Nothing} $ lineChart 3+ assertBool "the third point links" $ "<a href=\"#t2\" tabindex=\"-1\">" `T.isInfixOf` svg+ assertBool "the second point does not" $ not $ "#t1" `T.isInfixOf` svg+ ,testCase "a plot by date can give its date scale" $ do+ let svg = svgText defaultSvgOptions{svgDateScale = True} $ lineChart 3+ assertBool "its first and last dates" $ "data-d0=\"2024-01-01\" data-d1=\"2024-01-03\"" `T.isInfixOf` svg+ ,testCase "a chart can be drawn at another width, its plot filling it" $ do+ let svg = svgText defaultSvgOptions{svgWidth = 600, svgDateScale = True} $ lineChart 3+ assertBool "its width" $ "viewBox=\"0 0 600 " `T.isInfixOf` svg+ -- the last date is drawn 8px inside the plot's right edge, which is 16px inside the chart's+ assertBool "its plot" $ "data-x1=\"576\"" `T.isInfixOf` svg+ ,testCase "a plot by date can be shaded as of today: the future, and the past below zero" $ do+ -- a line falling below zero, today being its second day+ let shading today = svgText defaultSvgOptions{svgToday = Just today} $ lineChartOf [1, -1, -2]+ svg = shading (fromGregorian 2024 1 2)+ assertBool "the past below zero" $ "class=\"shade past-negative\"" `T.isInfixOf` svg+ assertBool "the future" $ "class=\"shade future\"" `T.isInfixOf` svg+ assertBool "the future below zero" $ "class=\"shade future-negative\"" `T.isInfixOf` svg+ assertBool "the zero line" $ "class=\"axis zero\"" `T.isInfixOf` svg+ -- with today after the last day, it's all past+ assertBool "no future" $ not $ "shade future" `T.isInfixOf` shading (fromGregorian 2024 1 9)+ ,testCase "a net total is marked across each period's bars, unless the periods are too narrow" $ do+ let marks = T.count "class=\"mark total\"" . svgText defaultSvgOptions . netChart MarkMarker+ -- one per period, and one in the legend+ marks 12 @?= 13+ -- at 880px, 100 periods are 8.8px each, too narrow: neither the marks nor their legend entry+ marks 100 @?= 0+ ,testCase "a single period's net line is marked across its bars, since a line of one point would not show" $ do+ let svg = svgText defaultSvgOptions $ netChart MarkLine 1+ -- one across the bars, and one in the legend+ T.count "class=\"mark total\"" svg @?= 2+ assertBool "no line" $ not $ "line total" `T.isInfixOf` svg+ ,testCase "a line over periods has tooltips all along it, each point's from halfway to its neighbours" $ do+ let svg = svgText defaultSvgOptions $ netChart MarkLine 3+ -- each target's path: from its point, a line to each end+ targets = map (T.takeWhile (/= '"') . T.drop (T.length "d=\"")) $ drop 1 $ T.splitOn "class=\"hit-line total\" " svg+ map (T.count "M") targets @?= [1, 2, 1]+ assertBool "no circles" $ not $ "class=\"hit" `T.isInfixOf` T.replace "hit-line" "" svg+ ,testCase "a chart's ids have the given prefix, and each of its panels drawn separately its own" $ do+ let svg = svgText defaultSvgOptions{svgIds = "x"} $ netChart MarkLine 2+ assertBool "the prefix" $ "id=\"x-clip-bar" `T.isInfixOf` svg+ assertBool "not the default" $ not $ "hledger-chart-clip" `T.isInfixOf` svg+ let chart = netChart MarkLine 2+ panels = map (TL.toStrict . renderSvg) $ chartPanelsSvgMarkupWith defaultSvgOptions chart{chPanels = chPanels chart ++ chPanels chart}+ map ("id=\"hledger-chart-0-clip-bar" `T.isInfixOf`) panels @?= [True, False]+ map ("id=\"hledger-chart-1-clip-bar" `T.isInfixOf`) panels @?= [False, True]+ ,testCase "a line of one point is drawn as a short dash, so that it shows" $ do+ let points = T.takeWhile (/= '"') . T.drop (T.length "points=\"") . snd . T.breakOn "points=\"" . svgText defaultSvgOptions+ length (T.words $ points $ lineChartOf [5]) @?= 2+ ]+ where+ svgText opts = TL.toStrict . renderSvg . chartSvgMarkupWith opts+ -- a chart of one line, rising by 1 a day for n days from 2024-01-01+ lineChart n = lineChartOf [fromIntegral k | k <- [1 .. n]]+ -- a chart of one line, with these values on successive days from 2024-01-01+ lineChartOf qs = Chart "" (XDates $ take (length qs) $ iterate (addDays 1) (fromGregorian 2024 1 1))+ [Panel nullamt [Series (ChartLabel "a" "a" 0 Nothing True []) SeriesItem MarkLine (map Just qs) 0 0] [] Nothing Diverging False [] []] []+ -- a chart of n periods, each with a positive and a negative bar, and their net total, drawn with the given mark+ netChart mk n = Chart "" (XPeriods $ replicate n (nulldatespan, "p"))+ [Panel nullamt [ Series (ChartLabel "a" "a" 0 Nothing True []) SeriesItem MarkBar (replicate n (Just 3)) 0 0+ , Series (ChartLabel "b" "b" 0 Nothing True []) SeriesItem MarkBar (replicate n (Just (-1))) 0 0+ , Series (ChartLabel "net" "net" 0 Nothing True []) SeriesTotal mk (replicate n (Just 2)) 0 0+ ] [] Nothing Diverging False [] []] []
+ Hledger/Write/Chart/Text.hs view
@@ -0,0 +1,414 @@+{- |+Draw a 'Chart' as text, for terminals.++Every chart is drawn as horizontal bars, one row per x position,+with an aligned value column before the bars. Several series are drawn as stacked segments,+positive values growing right from a zero axis and negative values growing left.+Lines are drawn as bars too, since text has no good way to draw lines.++The output is a list of styled lines, so that different frontends can apply the styles in their own way:+'styledLinesAsText' turns them into plain or ANSI-coloured text.+-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Chart.Text (+ TextChartOpts(..),+ Style(..),+ ColourMode(..),+ StyledLine,+ chartAsStyledLines,+ styledLinesAsText,+ tests_Hledger_Write_Chart_Text,+) where++import Data.List (find, nub, partition, sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Control.Monad (join, mfilter)+import Data.Maybe (fromMaybe, isJust, isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Safe (atMay, maximumDef)+import Data.Colour.SRGB (sRGB24read)+import System.Console.ANSI (Color(..), ColorIntensity(..), ConsoleLayer(..), SGR(..), setSGRCode)+import Text.DocLayout (realLength)++import Hledger.Data.Amount (nullamt, oneLineNoCostFmt, showAmountWith)+import Hledger.Data.Dates (showDate)+import Hledger.Data.Types (AccountType(..), Amount(..), Quantity)+import Hledger.Utils.IO (color, faint')+import Hledger.Utils.Test+import Hledger.Utils.Text (fitText)+import Hledger.Write.Chart+import Hledger.Write.Chart.Palette (colourHex)+++-- | Options for drawing a text chart.+data TextChartOpts = TextChartOpts+ { tcWidth :: Int -- ^ the width to fill, in characters (eg the terminal width)+ , tcUnicode :: Bool -- ^ use unicode block characters (otherwise ASCII)+ }++-- | How a piece of text should be shown.+data Style+ = StylePlain+ | StyleSeries Int -- ^ the colour of the Nth ordinary series in a panel+ | StyleType AccountType Int -- ^ the colour of a main account type, in its Nth variant+ | StyleOther (Maybe AccountType) -- ^ the colour of a series combining several items ("other"), of this main account type if any+ | StyleLone -- ^ the colour of a chart's only series, when it is not an account+ | StyleNegative -- ^ a negative value+ deriving (Show, Eq)++-- | A line of text made of styled pieces.+type StyledLine = [(Style, Text)]++-- | How to colour a text chart.+data ColourMode+ = NoColour+ | BasicColour -- ^ with the terminal's basic ANSI colours (whose exact shades depend on its colour theme)+ | RgbColour Bool -- ^ with exact 24-bit colours, the same as SVG charts'; their variants for a dark background if true+ deriving (Show, Eq)++-- | Render styled lines as text, with ANSI colours or without.+styledLinesAsText :: ColourMode -> [StyledLine] -> TL.Text+styledLinesAsText mode = TL.fromChunks . concatMap (\l -> map piece l ++ ["\n"])+ where+ piece (st, t) = case mode of+ NoColour -> t+ BasicColour -> case st of+ StylePlain -> t+ StyleSeries n -> T.pack $ uncurry color (cyclicAt (Dull, Blue) indexColours n) $ T.unpack t+ StyleType at n -> T.pack $ color (if even n then Dull else Vivid) (typeColour at) $ T.unpack t+ StyleOther _ -> T.pack $ faint' $ T.unpack t+ StyleLone -> T.pack $ color Dull Cyan $ T.unpack t+ StyleNegative -> negative t+ RgbColour dark -> case st of+ StylePlain -> t+ StyleSeries n -> rgb (colourHex dark $ IndexColour n) t+ StyleType at n -> rgb (colourHex dark $ TypeColour at n) t+ StyleOther mt -> rgb (colourHex dark $ OtherColour mt) t+ StyleLone -> rgb (colourHex dark LoneColour) t+ StyleNegative -> negative t+ -- negative values are red, as elsewhere in hledger's output+ negative t = T.pack $ color Dull Red $ T.unpack t+ rgb hex t = T.pack (setSGRCode [SetRGBColor Foreground $ sRGB24read $ T.unpack hex]) <> t <> T.pack (setSGRCode [])+ -- Conventional colours for the main account types, in the terminal's palette.+ typeColour at = case at of+ Asset -> Blue+ Liability -> Yellow+ Equity -> Magenta+ Revenue -> Green+ Expense -> Red+ _ -> Magenta+ -- For series of no account type. Avoiding red, used for negative values. Repeated after this many series (more than the usual series limit).+ indexColours =+ [(Dull, Blue), (Dull, Yellow), (Dull, Magenta), (Dull, Cyan), (Dull, Green), (Vivid, Blue), (Vivid, Yellow), (Vivid, Magenta)]++-- | Draw a chart as styled lines of text: the title (if any), then each panel,+-- with a heading naming its commodity when there are several (and it has a commodity symbol),+-- and a legend (see 'legendListsSeries') listing the series that are visible (a series too small to fill a character cell is not).+-- A chart of dates (eg a register) has a row per date, however many there are.+-- A chart with no panels (nothing to show, eg in an empty period) says so.+chartAsStyledLines :: TextChartOpts -> Chart -> [StyledLine]+chartAsStyledLines opts c@Chart{chTitle, chXAxis, chPanels, chNotes} =+ titlelines ++ [[(StylePlain, "No data")] | null chPanels] ++ concatMap (\(i, p) -> [[] | i > 0] ++ panelLines opts chXAxis (chartColouring c) (length chPanels > 1) p) (zip [0 :: Int ..] chPanels)+ ++ notelines+ where+ titlelines = if T.null chTitle then [] else [[(StylePlain, chTitle)], []]+ -- the notes, after a blank line+ notelines = if null chNotes then [] else [] : [[(StylePlain, n)] | n <- chNotes]++-- | A row of a text chart: a label, an optional value, and the bar segments (style, fill character, quantity).+data Row = Row+ { rowLabel :: Text+ , rowSubLabel :: Text -- ^ a second label, eg the name of the group this row shows (empty for none)+ , rowValue :: Maybe Quantity+ , rowSegments :: [(Style, Char, Quantity)]+ , rowMark :: Maybe Quantity -- ^ a value to mark with a vertical line, over the bar segments if any (eg a net total)+ , rowSides :: (Maybe Quantity, Maybe Quantity) -- ^ in a diverging chart, the totals of the series usually right and left of the axis+ , rowNote :: Maybe Text -- ^ text to show after the value (see 'pnValueLabels'), eg a gain percent+ }++panelLines :: TextChartOpts -> XAxis -> Colouring -> Bool -> Panel -> [StyledLine]+panelLines TextChartOpts{tcWidth, tcUnicode} xaxis colouring showheading Panel{pnUnit, pnSeries, pnGroupNames, pnScale, pnLayout, pnCounts, pnSummary, pnValueLabels} =+ [[(StylePlain, acommodity pnUnit)] | showheading, not $ T.null $ acommodity pnUnit]+ ++ legend+ ++ [trimEnd headerline | diverging, not $ all T.null [posname, negname, netname]]+ ++ map trimEnd rowlines+ ++ (if null pnSummary then [] else [[], [(StylePlain, summaryline)]])+ where+ -- the summary values, eg "Total 11, Average 0.9"+ summaryline = T.intercalate ", " [suLabel su <> " " <> T.pack (showAmountWith oneLineNoCostFmt $ suValue su) | su <- pnSummary]+ -- The series drawn as bars: all but totals (shown as the value) and markers (not drawn in text).+ drawn = [s | s <- pnSeries, seRole s /= SeriesTotal, seMark s `notElem` [MarkMarker, MarkNone]]+ mtotal = find ((== SeriesTotal) . seRole) pnSeries+ single = length drawn == 1+ -- each series' style, fill character (chosen by its name, like its colour, so that it stays the same in other charts) and values+ styled = zipWith3 seriesStyle [fromMaybe 0 $ lookup i fillslots | i <- [0 .. length drawn - 1]] (seriesColours colouring drawn) drawn+ -- each series' fill character, chosen by name: for accounts, favouring the first (best looking) characters,+ -- so that the others are used mainly when there are more series; for "other" series, which are grey,+ -- so their texture matters less, favouring the last ones.+ -- Chosen among the series drawn in the same bar (with the grouped layout, each group's); a series alone in its bar gets the first.+ fillslots = concat+ [ if length bar == 1 then [(i, 0) | (i, _) <- bar] else slotsfor id items ++ slotsfor (\k -> length fillchars - 1 - k) others+ | bar <- bars, let (items, others) = partition ((== SeriesItem) . seRole . snd) bar ]+ where+ bars = if grouped then [[(i, s) | (i, s) <- indexed, seGroup s == g] | g <- nub $ map (seGroup . snd) indexed] else [indexed]+ indexed = zip [0 :: Int ..] drawn+ slotsfor f ss = zip (map fst ss) $ map f $ stableSlotsFavouringFirst 0.5 (length fillchars) [(lbFull $ seLabel s, seriesSize s) | (_, s) <- ss]+ styledseries = zip styled drawn+ -- The groups of series (see 'seGroup'), in order, and each group's name and usual sign (if its series have one; otherwise 1).+ groups = nub $ map seGroup drawn+ groupName k = fromMaybe "" $ pnGroupNames `atMay` k+ groupSign k = fromMaybe 1 $ find (/= 0) [seSign s | s <- drawn, seGroup s == k]+ -- With the grouped layout and several groups (even if only one has series drawn here), each x position has a row for each group (named, showing its total),+ -- and the total is shown (and marked) on a row of its own, after them.+ grouped = pnLayout == Grouped && length pnGroupNames > 1+ -- Otherwise, a chart with series with usual signs (see 'seSign'), and a total (eg of a compound report), is diverging:+ -- each row shows the totals of each side's groups at that end of the bar (with their names in a header line),+ -- and the total as a mark over the bar.+ -- In any chart, contra amounts (of the opposite sign to their series' usual sign) are drawn nearest the axis, with a hatched fill character.+ diverging = not grouped && isJust mtotal && any ((/= 0) . seSign) drawn+ -- The total is marked at every x position (even where it is just the end of the bars, or zero), and is then in the legend.+ -- A total that isn't to be drawn (MarkNone, eg without --chart=net) is shown only as the value.+ marktotal = mfilter ((/= MarkNone) . seMark) mtotal+ marked = isJust marktotal+ seriesStyle i colour s = (colourStyle colour, fillChar i, seriesValues s)+ colourStyle colour = case colour of+ TypeColour at k -> StyleType at k+ IndexColour k -> StyleSeries k+ LoneColour -> StyleLone+ NeutralColour -> StylePlain+ OtherColour mt -> StyleOther mt+ TotalColour -> StylePlain+ -- in a chart of categories (eg accounts) with a single series, each category's bar has its own account type's colour, if known+ categoryStyle j st = case (xaxis, single) of+ (XCategories ls, True) | Just l <- ls `atMay` j, Just at <- lbType l -> StyleType (mainAccountType at) (fromMaybe 0 $ categorytints `atMay` j)+ _ -> st+ -- with a single series of categories, each category's tint of its type's colour+ categorytints = case (xaxis, drawn) of+ (XCategories ls, [s]) -> categoryTints ls (seValues s)+ _ -> []+ mtotalvals = seriesValues <$> mtotal+ fillchars = if tcUnicode then "█▓▒░" else "#=+:" -- best looking first+ fillChar = cyclicAt ' ' fillchars++ xlabels = case xaxis of+ XCategories ls -> [T.replicate (2 * lbIndent l) " " <> lbShort l | l <- ls]+ XPeriods ps -> map snd ps+ XDates ds -> map showDate ds+ -- contra amounts are drawn nearest the axis; they and shortfalls are drawn hatched+ segmentsAt j sers = map snd $ sortOn (not . fst)+ [ (isContra s q, (categoryStyle j st, if isHatched s q then contrachar else c, q))+ | ((st, c, vals), s) <- sers, Just q <- [valueAt vals j], q /= 0 ]+ contrachar = if tcUnicode then '╱' else '/'++ rows+ | grouped =+ concat+ [ [ Row (if i == 0 then lbl else "") (groupName k) (groupTotal j k) (segmentsAt j [ss | ss@(_, s) <- styledseries, seGroup s == k]) Nothing (Nothing, Nothing) Nothing+ | (i, k) <- zip [0 :: Int ..] groups ]+ ++ [ Row "" (lbShort $ seLabel t) tval [] (if marked then tval else Nothing) (Nothing, Nothing) Nothing | Just t <- [mtotal], let tval = valueAt (seriesValues t) j ]+ | (j, lbl) <- zip [0 ..] xlabels ]+ | otherwise =+ [ Row lbl "" rowval (segmentsAt j styledseries) (if marked then rowval else Nothing) (sideTotal j 1, sideTotal j (-1)) (join $ pnValueLabels `atMay` j)+ | (j, lbl) <- zip [0 ..] xlabels+ , let rowval = case (mtotalvals, styled) of+ (Just tvals, _) -> valueAt tvals j+ (_, [(_, _, vals)]) -> valueAt vals j+ _ -> Nothing+ -- categories with no values at all (eg accounts without this commodity) are left out+ , not (isCategories && all (\(_, _, vals) -> isNothing $ valueAt vals j) styled)+ ]+ isCategories = case xaxis of XCategories _ -> True; _ -> False++ rowlines = map rowLine rows+ -- the styles of the bar segments actually drawn (a series too small to show at this scale has none)+ drawnstyles = nub [st | l <- rowlines, (st, t) <- l, st /= StylePlain, not $ T.null $ T.strip t]+ -- a legend for the series, omitting any not drawn+ legend+ | legendListsSeries isCategories drawn = wrapLegend (+ [ [(st, T.singleton $ if hatchedSeries s then contrachar else c), (StylePlain, " " <> lbFull (seLabel s))]+ | ((st, c, _), s) <- zip styled drawn, st `elem` drawnstyles ]+ ++ [ [(StylePlain, markchar), (StylePlain, " " <> lbFull (seLabel t))] | Just t <- [marktotal] ]+ ++ [ [(StylePlain, T.singleton contrachar), (StylePlain, " contra")]+ | or [isContra s q | s <- drawn, Just q <- seValues s] ]+ ) ++ [[]]+ | otherwise = []+ -- Lay out legend items left to right, two spaces apart, starting a new line when the next item won't fit.+ wrapLegend = reverse . foldl' addItem []+ where+ addItem [] item = [item]+ addItem (l:ls) item+ | lineWidth l + 2 + lineWidth item <= tcWidth = (l ++ [(StylePlain, " ")] ++ item) : ls+ | otherwise = item : l : ls+ lineWidth = sum . map (realLength . snd)++ -- Column widths and scale.+ showValue q = T.pack $ showAmountWith oneLineNoCostFmt pnUnit{aquantity = q}+ labelw = min (tcWidth `div` 3) $ maximumDef 0 $ map (realLength . rowLabel) rows+ sublabelw = min (tcWidth `div` 4) $ maximumDef 0 $ map (realLength . rowSubLabel) rows+ valuew = maximumDef 0 [realLength (showValue q) | Row{rowValue = Just q} <- rows]+ hasvalues = any (isJust . rowValue) rows+ -- the notes column, after the values, if any rows have notes+ notew = maximumDef 0 [realLength t | Row{rowNote = Just t} <- rows]+ -- (a negative one, eg a loss's gain percent, in the negative style, like the values;+ -- a positive one, eg a gain's, in the revenue colour, like gains)+ notecolumn t = if notew > 0 then [(StylePlain, " "), (noteStyle t, fitText (Just notew) Nothing False False t)] else []+ noteStyle t+ | "-" `T.isPrefixOf` t = StyleNegative+ | "+" `T.isPrefixOf` t = StyleType Revenue 0+ | otherwise = StylePlain+ -- In a diverging chart, the totals of each side's series (eg a compound report's sections), shown at that end of the bar.+ -- They are shown with their usual sign as positive, like the report's tables (eg expenses as positive),+ -- and include contra amounts (eg a refund counts in expenses, though it is drawn on the other side).+ sideTotal j sign = signedTotal sign j [s | s <- drawn, seSign s == sign]+ -- the same for a group's series (shown in the grouped layout)+ groupTotal j k = signedTotal (groupSign k) j [s | s <- drawn, seGroup s == k]+ signedTotal sign j sers = case [q | s <- sers, Just q <- [valueAt (seriesValues s) j]] of+ [] -> Nothing+ qs -> Just $ fromIntegral sign * sum qs+ posSum = fst . rowSides+ negSum = snd . rowSides+ negsumw = if diverging then maximumDef 0 (realLength negname : [realLength (showValue q) | Just q <- map negSum rows]) else 0+ possumw = if diverging then maximumDef 0 (realLength posname : [realLength (showValue q) | Just q <- map posSum rows]) else 0+ -- In a diverging chart, a header line names the total and the side totals' columns (eg the sections on each side).+ sideName sign = T.intercalate ", " $ filter (not . T.null) [groupName k | k <- groups, groupSign k == sign]+ (posname, negname) = (sideName 1, sideName (-1))+ netname = if hasvalues then maybe "" (lbShort . seLabel) mtotal else ""+ headerline = drop 1 $+ (if labelw > 0 then [(StylePlain, " "), (StylePlain, T.replicate labelw " ")] else [])+ ++ (if hasvalues then [(StylePlain, " "), (StylePlain, fitText (Just valuew) Nothing False False netname)] else [])+ ++ notecolumn ""+ ++ [(StylePlain, " ")]+ ++ (if negsumw > 0 then [(StylePlain, fitText (Just negsumw) Nothing False False negname), (StylePlain, " ")] else [])+ ++ (if possumw > 0 then [(StylePlain, T.replicate barw " "), (StylePlain, " "), (StylePlain, posname)] else [])+ barw = max 10 $ tcWidth - (if labelw > 0 then labelw + 2 else 0) - (if sublabelw > 0 then sublabelw + 2 else 0) - (if hasvalues then valuew + 2 else 0) - (if notew > 0 then notew + 2 else 0)+ - (if negsumw > 0 then negsumw + 1 else 0) - (if possumw > 0 then possumw + 1 else 0)+ posTotal r = sum [q | (_, _, q) <- rowSegments r, q > 0] `max` maybe 0 (max 0) (rowMark r)+ negTotal r = sum [abs q | (_, _, q) <- rowSegments r, q < 0] `max` maybe 0 (abs . min 0) (rowMark r)+ maxpos = maximumDef 0 $ map posTotal rows+ maxneg = maximumDef 0 $ map negTotal rows+ hasaxis = maxneg > 0+ -- the amounts that fill each side: the largest there, or the parts of a fixed scale+ (posspan, negspan) = case pnScale of+ Just s | s > 0 -> scaleSpans s maxpos maxneg+ _ -> (maxpos, maxneg)+ area = if hasaxis then barw - 1 else barw+ -- cells per unit of value, shared by both sides: enough for the values to fill the area+ -- (but for counts, at most one cell per unit, unless the scale is fixed)+ scale :: Double+ scale+ | posspan + negspan == 0 = 0+ | pnCounts && isNothing pnScale = min 1 fillscale+ | otherwise = fillscale+ where fillscale = fromIntegral area / realToFrac (posspan + negspan)+ leftw+ | not hasaxis = 0+ | otherwise = round (scale * realToFrac negspan)+ rightw = area - leftw+ axischar = if tcUnicode then "│" else "|"+ markchar = if tcUnicode then "┃" else "!"+ -- marks for bars clipped at the right or left edge (beyond a fixed scale's span on that side)+ clippedRight q = isJust pnScale && q > posspan+ clippedLeft q = isJust pnScale && q > negspan+ clipright = if tcUnicode then "▸" else ">"+ clipleft = if tcUnicode then "◂" else "<"++ -- the label column, value column and bars, separated by two spaces (columns with nothing in them are left out)+ rowLine r@Row{rowLabel, rowSubLabel, rowValue, rowNote} =+ drop 1 $+ (if labelw > 0 then [(StylePlain, " "), (StylePlain, fitText (Just labelw) (Just labelw) True True rowLabel)] else [])+ ++ (if sublabelw > 0 then [(StylePlain, " "), (StylePlain, fitText (Just sublabelw) (Just sublabelw) True True rowSubLabel)] else [])+ ++ (if hasvalues+ then [(StylePlain, " "), (maybe StylePlain valueStyle rowValue, fitText (Just valuew) Nothing False False $ maybe "" showValue rowValue)]+ else [])+ ++ notecolumn (fromMaybe "" rowNote)+ ++ [(StylePlain, " ")]+ ++ (if negsumw > 0 then [(maybe StylePlain valueStyle (negSum r), fitText (Just negsumw) Nothing False False $ maybe "" showValue (negSum r)), (StylePlain, " ")] else [])+ ++ (if possumw > 0 then padTo barw bars ++ [(StylePlain, " "), (maybe StylePlain valueStyle (posSum r), maybe "" showValue (posSum r))] else bars)+ where+ bars = maybe id overlayMark (rowMark r) $ (if hasaxis then negativeBar r ++ [(StylePlain, axischar)] else []) ++ positiveBar r+ -- Pad a styled line with spaces to a width.+ padTo w l = l ++ [(StylePlain, T.replicate (w - sum (map (realLength . snd) l)) " ")]+ -- Draw a mark over the bar at a value's position (on the axis if zero).+ overlayMark q = overlayAt col (StylePlain, markchar)+ where+ col | q > 0 = leftw + (if hasaxis then 1 else 0) + max 1 (min rightw $ cells 1 q) - 1+ | q < 0 = leftw - max 1 (min leftw $ cells 1 (abs q))+ | otherwise = if hasaxis then leftw else 0+ valueStyle q = if q < 0 then StyleNegative else StylePlain++ -- The positive segments, growing right from the axis.+ -- A single segment uses eighth-block characters for finer resolution (in unicode mode); several use whole cells.+ positiveBar Row{rowSegments} = case [(st, c, q) | (st, c, q) <- rowSegments, q > 0] of+ [(st, c, q)] | tcUnicode && c == '█' && length rowSegments == 1 ->+ let eighths = cells 8 q+ in if clippedRight q+ then [(st, T.replicate (rightw - 1) "█" <> clipright)]+ else let e = min (rightw * 8) eighths in [(st, T.replicate (e `div` 8) "█" <> partialBlock (e `mod` 8))]+ segs -> segmentPieces rightw clippedRight (\t -> T.dropEnd 1 t <> clipright) segs+ -- The negative segments, growing left from the axis, first series nearest the axis.+ negativeBar Row{rowSegments} =+ let pieces = segmentPieces leftw clippedLeft (\t -> clipleft <> T.drop 1 t) [(st, c, abs q) | (st, c, q) <- rowSegments, q < 0]+ used = sum $ map (realLength . snd) pieces+ in (StylePlain, T.replicate (leftw - used) " ") : reverse pieces+ -- Segments as whole cells, rounding the cumulative boundaries so the total length is preserved, within a maximum width.+ -- If their total is clipped (by the given test), the outermost cell is replaced by a clip mark (with the given function).+ segmentPieces maxw clipped clip segs =+ let bounds = map (min maxw . cells 1) $ scanl1 (+) [q | (_, _, q) <- segs]+ widths = zipWith (-) bounds (0 : bounds)+ pieces = [(st, T.replicate w (T.singleton c)) | ((st, c, _), w) <- zip segs widths, w > 0]+ in case (reverse pieces, clipped $ sum [q | (_, _, q) <- segs]) of+ ((st, t) : rest, True) -> reverse ((st, clip t) : rest)+ _ -> pieces+ cells :: Int -> Quantity -> Int+ cells perunit q = round (realToFrac q * scale * fromIntegral perunit)+ partialBlock n = fromMaybe "" $ ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] `atMay` n++-- | The Nth item of a list, repeating the list as needed; or the default if the list is empty.+cyclicAt :: a -> [a] -> Int -> a+cyclicAt d xs n = if null xs then d else fromMaybe d $ xs `atMay` (n `mod` length xs)++-- | Replace the character at a column of a styled line (of single-width characters) with some styled text,+-- padding the line with spaces if it is shorter.+overlayAt :: Int -> (Style, Text) -> StyledLine -> StyledLine+overlayAt i new = go 0+ where+ go col [] = [(StylePlain, T.replicate (i - col) " "), new]+ go col ((st, t) : rest)+ | i < col + n = [(st, T.take (i - col) t) | i > col] ++ [new] ++ [(st, T.drop (i - col + 1) t) | i - col + 1 < n] ++ rest+ | otherwise = (st, t) : go (col + n) rest+ where n = T.length t++-- | Remove trailing spaces from a styled line.+trimEnd :: StyledLine -> StyledLine+trimEnd = reverse . dropSpaces . reverse+ where+ dropSpaces ((st, t) : rest)+ | T.null (T.stripEnd t) = dropSpaces rest+ | otherwise = (st, T.stripEnd t) : rest+ dropSpaces [] = []++tests_Hledger_Write_Chart_Text :: TestTree+tests_Hledger_Write_Chart_Text = testGroup "Write.Chart.Text" [+ testCase "trimEnd" $ do+ trimEnd [(StylePlain, "a "), (StylePlain, " ")] @?= [(StylePlain, "a")]+ trimEnd [] @?= []+ ,testCase "single series, scaled to the width" $ do+ let lbl t = ChartLabel t t 0 Nothing True []+ chart = Chart "" (XCategories [lbl "a", lbl "b"])+ [Panel nullamt [Series (lbl "s") SeriesItem MarkBar [Just 1, Just 2] 0 0] [] Nothing Diverging False [] []] []+ map (T.concat . map snd) (chartAsStyledLines (TextChartOpts 20 True) chart)+ @?= ["a 1 ███████", "b 2 ██████████████"]+ ,testCase "mixed signs grow from an axis" $ do+ let lbl t = ChartLabel t t 0 Nothing True []+ chart = Chart "" (XCategories [lbl "a", lbl "b"])+ [Panel nullamt [Series (lbl "s") SeriesItem MarkBar [Just (-1), Just 2] 0 0] [] Nothing Diverging False [] []] []+ map (T.concat . map snd) (chartAsStyledLines (TextChartOpts 21 False) chart)+ @?= ["a -1 ####|", "b 2 |#########"]+ ]
+ Hledger/Write/Csv.hs view
@@ -0,0 +1,56 @@+--- * -*- outline-regexp:"--- \\*"; -*-+--- ** doc+{-|++CSV utilities.++-}++--- ** language+{-# LANGUAGE OverloadedStrings #-}++--- ** exports+module Hledger.Write.Csv (+ CSV, CsvRecord, CsvValue,+ printCSV,+ printTSV,+ -- * Tests+ tests_CsvUtils,+)+where++--- ** imports+import Prelude hiding (Applicative(..))+import Data.List (intersperse)+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 Hledger.Utils++--- ** doctest setup+-- $setup+-- >>> :set -XOverloadedStrings++type CSV = [CsvRecord]+type CsvRecord = [CsvValue]+type CsvValue = Text++printCSV :: CSV -> TL.Text+printCSV = TB.toLazyText . unlinesB . map printRecord+ where printRecord = foldMap TB.fromText . intersperse "," . map printField+ printField = wrap "\"" "\"" . T.replace "\"" "\"\""++printTSV :: CSV -> TL.Text+printTSV = TB.toLazyText . unlinesB . map printRecord+ where printRecord = foldMap TB.fromText . intersperse "\t" . map printField+ printField = T.map replaceWhitespace+ replaceWhitespace c | c `elem` ['\t', '\n', '\r'] = ' '+ replaceWhitespace c = c++--- ** tests++tests_CsvUtils :: TestTree+tests_CsvUtils = testGroup "CsvUtils" [+ ]
+ Hledger/Write/Html.hs view
@@ -0,0 +1,219 @@+{- |+HTML writing helpers, using blaze-html, whose markup type is also the one+hledger-web's pages are made of.++They render "Hledger.Write.Spreadsheet" tables as HTML tables: the CLI's+@-O html@ output uses 'styledTableHtml' and 'titledTableHtml', and+hledger-web's report pages use 'formatCell' inside their own table markup.+blaze's text renderer writes everything on one line, so for human readability+we inject raw newlines between elements (see 'nl').+-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Html (+ Html,+ toHtml,+ Lines(..),+ borderClasses,+ formatCell,+ formatRow,+ formatTitle,+ htmlAsText,+ htmlAsLazyText,+ nl,+ styledTableHtml,+ titledTableHtml,+ tests_Hledger_Write_Html+ ) where++import Control.Monad (unless)+import Data.Foldable (traverse_)+import Data.List (intersperse)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Lazy qualified as TL+import Text.Blaze.Html5 (Html, toHtml, (!))+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A+import Text.Blaze.Html.Renderer.Text (renderHtml)++import Hledger.Data.Amount (nullamt)+import Hledger.Utils.Test+import Hledger.Write.Html.Attribute qualified as Attr+import Hledger.Write.Spreadsheet (Type(..), Style(..), Emphasis(..), Cell(..))+import Hledger.Write.Spreadsheet qualified as Spr+++htmlAsText :: Html -> Text+htmlAsText = TL.toStrict . renderHtml++htmlAsLazyText :: Html -> TL.Text+htmlAsLazyText = renderHtml++-- | A literal newline, to make the HTML output more human-readable.+-- Emit it only between elements, never inside cell content,+-- so it doesn't affect rendering.+nl :: Html+nl = H.preEscapedToHtml ("\n" :: Text)++-- | Export spreadsheet table data as HTML table.+-- This is derived from <https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs>+styledTableHtml :: (Lines border) => [[Cell border Html]] -> Html+styledTableHtml = titledTableHtml Text.empty++-- | Like 'styledTableHtml', but with the given report title, if non-empty,+-- as a heading above the table.+titledTableHtml :: (Lines border) => Text -> [[Cell border Html]] -> Html+titledTableHtml title table = do+ -- the builtin styles, then the optional user stylesheet so it can override them+ H.style $ H.preEscapedToHtml Attr.tableStylesheet+ nl+ H.link ! A.rel "stylesheet" ! A.href "hledger.css"+ nl+ unless (Text.null title) $ formatTitle title+ H.table $ nl <> traverse_ formatRow table++formatRow :: (Lines border) => [Cell border Html] -> Html+formatRow row = H.tr (traverse_ formatCell row) <> nl++-- | Render a report title as an HTML heading.+formatTitle :: Text -> Html+formatTitle title = (H.h3 ! A.class_ "report-title") (toHtml title) <> nl++formatCell :: (Lines border) => Cell border Html -> Html+formatCell cell =+ -- Wrap amounts in <span class="amount">, one per amount,+ -- so eg wrapping within amounts can be prevented with css.+ let amountSpan = H.span ! A.class_ "amount" in+ let str =+ case cellParts cell of+ [] -> case cellType cell of+ TypeAmount _ -> amountSpan $ cellContent cell+ _ -> cellContent cell+ parts ->+ mconcat $ intersperse (toHtml (", "::Text)) $+ map amountSpan parts in+ let content =+ if Text.null $ cellAnchor cell+ then str+ else foldl (!) H.a+ (A.href (H.textValue $ cellAnchor cell) :+ [A.title (H.textValue $ cellTitle cell) | not $ Text.null $ cellTitle cell])+ str in+ -- Mark date cells with a "date" class, so eg wrapping within dates+ -- can be prevented with css; borders are classes too.+ let class_ =+ map (A.class_ . H.textValue . Text.unwords) $+ filter (not . null) $+ [filter (not . Text.null) $+ Spr.textFromClass (cellClass cell) :+ ["date" | cellType cell == TypeDate] +++ borderClasses cell] in+ let addSpan spanAttr n attrs =+ if n==1+ then attrs+ else spanAttr (H.stringValue $ show n) : attrs in+ let span_ makeCell attrs cont =+ case Spr.cellSpan cell of+ Spr.NoSpan -> foldl (!) makeCell attrs cont+ Spr.Covered -> pure ()+ Spr.SpanHorizontal n ->+ foldl (!) makeCell (addSpan A.colspan n attrs) cont+ Spr.SpanVertical n ->+ foldl (!) makeCell (addSpan A.rowspan n attrs) cont+ in+ case cellStyle cell of+ Head -> span_ H.th class_ content+ Body emph ->+ let align =+ case cellType cell of+ TypeString -> []+ TypeDate -> []+ _ -> [H.customAttribute "align" "right"]+ valign =+ case Spr.cellSpan cell of+ Spr.SpanVertical n ->+ if n>1+ then [H.customAttribute "valign" "top"]+ else []+ _ -> []+ withEmph =+ case emph of+ Item -> id+ Total -> H.b+ in span_ H.td (align++valign++class_) $+ withEmph content+++-- | The CSS classes marking a cell's borders, eg @border-top-double@.+-- Borders are expressed as classes rather than inline styles so that the+-- HTML can be served under a Content Security Policy which forbids inline+-- styles; the matching rules are in "Hledger.Write.Html.Attribute".+borderClasses :: Lines border => Cell border text -> [Text]+borderClasses cell =+ [ "border-" <> side <> "-" <> cls+ | (side, access) <-+ [ ("left", Spr.borderLeft)+ , ("right", Spr.borderRight)+ , ("top", Spr.borderTop)+ , ("bottom", Spr.borderBottom)+ ]+ , Just cls <- [borderClass $ access $ cellBorder cell]+ ]++class (Spr.Lines border) => Lines border where+ -- | The class suffix naming this kind of border line, if it is drawn.+ borderClass :: border -> Maybe Text++instance Lines () where+ borderClass () = Nothing++instance Lines Spr.NumLines where+ borderClass prop =+ case prop of+ Spr.NoLine -> Nothing+ Spr.SingleLine -> Just "single"+ Spr.DoubleLine -> Just "double"+++tests_Hledger_Write_Html = testGroup "Write.Html" [++ testCase "formatCell" $ do+ let cell = htmlAsText . formatCell . fmap toHtml+ str = Spr.defaultCell :: Text -> Cell Spr.NumLines Text+ cell (str "a") @?= "<td>a</td>"+ cell (str "a<b>&\"c\"") @?= "<td>a<b>&"c"</td>"+ cell (Spr.headerCell "h") @?= "<th>h</th>"+ cell (str "2026-01-01") {cellType = TypeDate} @?= "<td class=\"date\">2026-01-01</td>"+ -- an amount is wrapped in a span; a multi-commodity amount gets one span per amount+ cell (str "$1") {cellType = TypeAmount nullamt, cellClass = Spr.Class "amount"}+ @?= "<td align=\"right\" class=\"amount\"><span class=\"amount\">$1</span></td>"+ cell (str "$1, 2 €") {cellType = TypeMixedAmount, cellParts = ["$1", "2 €"]}+ @?= "<td align=\"right\"><span class=\"amount\">$1</span>, <span class=\"amount\">2 €</span></td>"+ -- links, totals, borders+ cell (str "a") {cellAnchor = "register?q=a&b"} @?= "<td><a href=\"register?q=a&b\">a</a></td>"+ cell (str "a") {cellAnchor = "register?q=a", cellTitle = "Show \"a\""}+ @?= "<td><a href=\"register?q=a\" title=\"Show "a"\">a</a></td>"+ -- a title without an anchor has nothing to describe+ cell (str "a") {cellTitle = "t"} @?= "<td>a</td>"+ cell (str "Total:") {cellStyle = Body Total, cellBorder = Spr.noBorder {Spr.borderTop = Spr.DoubleLine}}+ @?= "<td class=\"border-top-double\"><b>Total:</b></td>"+ cell (Spr.headerCell "h" :: Cell Spr.NumLines Text) {cellClass = Spr.Class "account", cellBorder = Spr.noBorder {Spr.borderBottom = Spr.SingleLine}}+ @?= "<th class=\"account border-bottom-single\">h</th>"+ -- merged cells: a span of 1 is not written, covered cells are not written at all+ cell (str "a") {cellSpan = Spr.SpanHorizontal 2} @?= "<td colspan=\"2\">a</td>"+ cell (str "a") {cellSpan = Spr.SpanHorizontal 1} @?= "<td>a</td>"+ cell (str "a") {cellSpan = Spr.SpanVertical 2} @?= "<td rowspan=\"2\" valign=\"top\">a</td>"+ cell (str "a") {cellSpan = Spr.Covered} @?= ""++ ,testCase "formatRow" $+ htmlAsText (formatRow $ map (fmap toHtml) [Spr.defaultCell "a", Spr.defaultCell "b" :: Cell () Text])+ @?= "<tr><td>a</td><td>b</td></tr>\n"++ ,testCase "titledTableHtml" $ do+ let html = htmlAsText $ titledTableHtml "T & U" [map (fmap toHtml) [Spr.headerCell "h" :: Cell () Text]]+ Text.isPrefixOf "<style>\ntable {" html @?= True+ Text.isSuffixOf "</style>\n<link rel=\"stylesheet\" href=\"hledger.css\">\n<h3 class=\"report-title\">T & U</h3>\n<table>\n<tr><th>h</th></tr>\n</table>" html @?= True++ ]
+ Hledger/Write/Html/Attribute.hs view
@@ -0,0 +1,69 @@+{-# LANGUAGE OverloadedStrings #-}+{- |+Helpers and CSS styles for HTML output.+-}+module Hledger.Write.Html.Attribute (+ stylesheet,+ tableStylesheet,+ tableStyle,+ borderStyle,+ bold,+ alignright,+ alignleft,+ aligncenter,+ collapse,+ lpad,+ rpad,+ hpad,+ vpad,+ ) where++import Data.Text qualified as Text+import Data.Text (Text)+++stylesheet :: [(Text,Text)] -> Text+stylesheet elstyles =+ Text.unlines $+ "" : [el<>" {"<>styles<>"}" | (el,styles) <- elstyles]++tableStylesheet :: Text+tableStylesheet = stylesheet tableStyle++tableStyle :: [(Text, Text)]+tableStyle =+ [("table", collapse),+ ("th, td", lpad),+ ("th.account, td.account", "padding-left:0;"),+ -- prevent wrapping within dates and individual amounts+ ("td.date, span.amount", "white-space:nowrap")]+ ++ borderStyle++-- | Rules for the border classes emitted by "Hledger.Write.Html",+-- one per side and line kind, eg @.border-top-double@. No color is given,+-- so the lines take the text color and stay visible on any background.+borderStyle :: [(Text, Text)]+borderStyle =+ [ ("." <> cls, side <> ":" <> line)+ | (side, sideCls) <- [("border-left","left"), ("border-right","right"),+ ("border-top","top"), ("border-bottom","bottom")]+ , (line, lineCls) <- [("1px solid","single"), ("3px double","double")]+ , let cls = "border-" <> sideCls <> "-" <> lineCls+ ]++bold :: Text+bold = "font-weight:bold"++alignright, alignleft, aligncenter :: Text+alignright = "text-align:right"+alignleft = "text-align:left"+aligncenter = "text-align:center"++collapse :: Text+collapse = "border-collapse:collapse"++lpad, rpad, hpad, vpad :: Text+lpad = "padding-left:1em"+rpad = "padding-right:1em"+hpad = "padding-left:1em; padding-right:1em"+vpad = "padding-top:1em; padding-bottom:1em"
+ Hledger/Write/Journal.hs view
@@ -0,0 +1,108 @@+{-|+Rendering a journal's items back to journal format, reproducing the+original journal file(s). Used by print --export.+-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}++module Hledger.Write.Journal (+ ItemRenderer(..),+ journalItemRenderer,+ journalItemsAsText,+) where++import Data.List (mapAccumL)+import Data.Map qualified as M+import Data.Maybe (fromMaybe)+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 Text.Megaparsec.Pos (SourcePos(..), unPos)++import Hledger.Data.Types++-- | How to render each kind of journal item in some output format.+data ItemRenderer = ItemRenderer+ { irTransaction :: Transaction -> Text -- ^ render a transaction, without a trailing blank line+ , irDirective :: Text -> Maybe Text -- ^ render a directive given as source text, or drop it (Nothing)+ , irComment :: Text -> Text -- ^ render a top-level comment line+ , irCommentBlock :: Text -> Text -- ^ render a comment ... end comment block+ }++-- | An item renderer for hledger's journal format, reproducing directives and comments as written,+-- and rendering transactions with the given showTransaction-like function+-- (whose trailing blank line is removed).+journalItemRenderer :: (Transaction -> Text) -> ItemRenderer+journalItemRenderer showtxn = ItemRenderer+ { irTransaction = \t -> let s = showtxn t in fromMaybe s $ T.stripSuffix "\n" s+ , irDirective = Just+ , irComment = id+ , irCommentBlock = id+ }++-- | Render journal items as journal text, reproducing the journal file(s) they were parsed from,+-- with transactions rendered from the given (possibly filtered and processed) transactions.+--+-- Directive, comment line and comment block items are rendered as the item renderer specifies+-- (verbatim, for hledger's journal format).+-- Non-exported directives are dropped. Include lines are dropped too, and the included file's+-- items follow inline, beginning a new block (so eg there is a blank line between the entries+-- of adjacent included files).+-- Each transaction placeholder is replaced by the rendering of the next given transaction+-- with that source position, or by nothing if there is none (eg it was filtered out).+-- Any transactions not matching a placeholder (eg from non-journal files) are added at the end,+-- in source position order.+--+-- Blank lines are normalised: each transaction, and each group of adjacent directive/comment+-- items (as delimited by blank lines in the source), is a block, and blocks are separated+-- by exactly one blank line. A final transaction is also followed by a blank line, as in+-- ordinary print output.+journalItemsAsText :: ItemRenderer -> [JournalItem] -> [Transaction] -> TL.Text+journalItemsAsText ItemRenderer{..} items txns =+ TB.toLazyText $ renderBlocks $ mergeGroups $ concat blockss <> map txnBlock (concat $ M.elems remaining)+ where+ -- transactions queued by source position, in the given order+ txnsbypos = M.map reverse $ M.fromListWith (++) [(posKey $ fst $ tsourcepos t, [t]) | t <- txns]+ -- A map key comparing line and column before the file path, since comparing+ -- SourcePos directly compares the (usually identical) file paths first, which is slow.+ posKey (SourcePos f l c) = (unPos l, unPos c, f)+ txnBlock = Txn . TB.fromText . irTransaction+ linesBlock = Lines . TB.fromText++ -- Convert each item to a block (or none), consuming the queued transactions.+ -- (Keep this pattern binding flat, so the final state doesn't retain the blocks list.)+ (remaining, blockss) = mapAccumL toBlock txnsbypos items+ toBlock m item = case item of+ JITransaction pos -> case M.lookup k m of+ Just (t:ts) -> (M.insert k ts m, [txnBlock t])+ _ -> (m, [Break])+ where k = posKey pos+ JIBlank -> (m, [Break])+ JIComment t -> (m, [linesBlock $ irComment t])+ JICommentBlock t -> (m, [linesBlock $ irCommentBlock t])+ JIDirective t -> (m, map linesBlock $ maybe [] pure $ irDirective t)+ JINonExportedDirective _ -> (m, [])+ JIInclude _ -> (m, [Break]) -- the included file's items begin a new block++-- | An output block: a group of directive/comment lines, a transaction, or a break between groups.+data Block = Lines TB.Builder | Txn TB.Builder | Break++-- | Merge adjacent line groups, and drop the breaks.+mergeGroups :: [Block] -> [Block]+mergeGroups (Lines a : Lines b : bs) = mergeGroups (Lines (a <> b) : bs)+mergeGroups (Break : bs) = mergeGroups bs+mergeGroups (b : bs) = b : mergeGroups bs+mergeGroups [] = []++-- | Render blocks separated by single blank lines. A final transaction is also+-- followed by a blank line, like ordinary print output; a final line group is not.+renderBlocks :: [Block] -> TB.Builder+renderBlocks [] = mempty+renderBlocks [Lines b] = b+renderBlocks (b : bs) = blockBuilder b <> TB.singleton '\n' <> renderBlocks bs+ where+ blockBuilder (Lines b') = b'+ blockBuilder (Txn b') = b'+ blockBuilder Break = mempty
+ Hledger/Write/Ledger.hs view
@@ -0,0 +1,74 @@+{-|+Helpers for Ledger-compatible output.+-}++{-# LANGUAGE OverloadedStrings #-}++module Hledger.Write.Ledger (+ showTransactionLedger,+ ledgerItemRenderer,+)+where++import Data.Char (isDigit)+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 Hledger.Data.Amount (defaultFmt, AmountFormat(..))+import Hledger.Data.Posting (postingsAsLines, renderCommentLines)+import Hledger.Data.Transaction (showTransactionLineFirstPart)+import Hledger.Data.Types (Transaction(..), tdescription)+import Hledger.Write.Journal (ItemRenderer(..), journalItemRenderer)++ledgerFmt :: AmountFormat+ledgerFmt = defaultFmt{displayLedgerLotSyntax = True}++-- | Like showTransaction, but renders cost basis using Ledger-style lot syntax+-- ({COST} [DATE] (LABEL)) instead of hledger consolidated syntax.+showTransactionLedger :: Transaction -> Text+showTransactionLedger t =+ TL.toStrict . TB.toLazyText $+ TB.fromText (tprecedingcomment t)+ <> TB.fromText descriptionline <> newline+ <> foldMap ((<> newline) . TB.fromText) newlinecomments+ <> foldMap ((<> newline) . TB.fromText) (postingsAsLines ledgerFmt False $ tpostings t)+ <> newline+ where+ descriptionline = T.stripEnd $ showTransactionLineFirstPart t <> T.concat [desc, samelinecomment]+ desc = if T.null d then "" else " " <> d where d = tdescription t+ (samelinecomment, newlinecomments) =+ case renderCommentLines (tcomment t) of [] -> ("",[])+ c:cs -> (c,cs)+ newline = TB.singleton '\n'++-- | An item renderer for Ledger output (print --export -O ledger): like the journal one,+-- but transactions use Ledger lot syntax, and directives which hledger accepts but Ledger+-- (detectably) does not are commented out, with an explanatory comment.+ledgerItemRenderer :: ItemRenderer+ledgerItemRenderer = (journalItemRenderer showTransactionLedger){ irDirective = Just . ledgerDirective }++-- | Reproduce a directive for Ledger, commenting it out with a note if it is one of+-- the hledger directive forms known not to be supported by Ledger.+ledgerDirective :: Text -> Text+ledgerDirective txt+ | isLedgerIncompatible txt = "; not supported as-is:\n" <> T.unlines (map ("; " <>) $ T.lines txt)+ | otherwise = txt++-- | Detect some hledger directive forms which Ledger does not support:+-- the decimal-mark directive; a one-line commodity directive with an amount+-- (Ledger uses a format subdirective); a periodic transaction rule with a description+-- (Ledger would read it as part of the period expression); and auto posting rules+-- using hledger's *N amount multipliers.+isLedgerIncompatible :: Text -> Bool+isLedgerIncompatible txt = case T.lines txt of+ [] -> False+ firstline : otherlines -> case T.words firstline of+ "decimal-mark" : _ -> True+ "commodity" : sym : _ -> T.any isDigit sym+ "~" : _ -> " " `T.isInfixOf` (T.strip $ T.takeWhile (/=';') $ T.drop 1 firstline)+ "=" : _ -> any hasMultiplier otherlines+ _ -> False+ where+ hasMultiplier l = T.any isDigit $ T.take 1 $ T.drop 1 $ snd $ T.breakOn "*" l
+ Hledger/Write/Ods.hs view
@@ -0,0 +1,401 @@+{- |+Export table data as OpenDocument Spreadsheet+<https://docs.oasis-open.org/office/OpenDocument/v1.3/>.+This format supports character encodings, fixed header rows and columns,+number formatting, text styles, merged cells, formulas, hyperlinks.+Currently we support Flat ODS, a plain uncompressed XML format.++This is derived from <https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs>++-}+module Hledger.Write.Ods (+ printFods,+ ) where++import Prelude hiding (Applicative(..))+import Control.Monad (guard)+import Control.Applicative (Applicative(..))++import Data.Text.Lazy qualified as TL+import Data.Text qualified as T+import Data.Text (Text)++import Data.Foldable qualified as Fold+import Data.List qualified as List+import Data.Map qualified as Map+import Data.Set qualified as Set+import Data.Foldable (fold)+import Data.Map (Map)+import Data.Set (Set)+import Data.Maybe (catMaybes)++import System.IO qualified as IO+import Text.Printf (printf)++import Hledger.Write.Spreadsheet qualified as Spr+import Hledger.Write.Spreadsheet (Type(..), Style(..), Emphasis(..), Cell(..))+import Hledger.Data.Types+ (Amount, CommoditySymbol, AmountPrecision(..), DigitGroupStyle(..),+ acommodity, aquantity, astyle, asprecision, asdigitgroups,+ )++printFods ::+ IO.TextEncoding ->+ Map Text ((Int, Int), [[Cell Spr.NumLines Text]]) -> TL.Text+printFods encoding tables =+ let fileOpen customStyles =+ map (map (\c -> case c of '\'' -> '"'; _ -> c)) $+ printf "<?xml version='1.0' encoding='%s'?>" (show encoding) :+ "<office:document" :+ " office:mimetype='application/vnd.oasis.opendocument.spreadsheet'" :+ " office:version='1.3'" :+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" :+ " xmlns:xsd='http://www.w3.org/2001/XMLSchema'" :+ " xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0'" :+ " xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0'" :+ " xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0'" :+ " xmlns:config='urn:oasis:names:tc:opendocument:xmlns:config:1.0'" :+ " xmlns:xlink='http://www.w3.org/1999/xlink'" :+ " xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'" :+ " xmlns:ooo='http://openoffice.org/2004/office'" :+ " xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0'" :+ " xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0'" :+ " xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'" :+ " xmlns:of='urn:oasis:names:tc:opendocument:xmlns:of:1.2'" :+ " xmlns:field='urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'" :+ " xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0'>" :+ "<office:styles>" :+ " <number:date-style style:name='iso-date'>" :+ " <number:year number:style='long'/>" :+ " <number:text>-</number:text>" :+ " <number:month number:style='long'/>" :+ " <number:text>-</number:text>" :+ " <number:day number:style='long'/>" :+ " </number:date-style>" :+ " <number:number-style style:name='integer'>" :+ " <number:number number:min-integer-digits='1'/>" :+ " </number:number-style>" :+ customStyles +++ "</office:styles>" :+ []++ fileClose =+ "</office:document>" :+ []++ tableConfig tableNames =+ " <office:settings>" :+ " <config:config-item-set config:name='ooo:view-settings'>" :+ " <config:config-item-map-indexed config:name='Views'>" :+ " <config:config-item-map-entry>" :+ " <config:config-item-map-named config:name='Tables'>" :+ (fold $+ flip Map.mapWithKey tableNames $ \tableName (topRow,leftColumn) ->+ printf " <config:config-item-map-entry config:name='%s'>" tableName :+ ((guard (leftColumn>0) >>) $+ " <config:config-item config:name='HorizontalSplitMode' config:type='short'>2</config:config-item>" :+ printf " <config:config-item config:name='HorizontalSplitPosition' config:type='int'>%d</config:config-item>" leftColumn :+ printf " <config:config-item config:name='PositionRight' config:type='int'>%d</config:config-item>" leftColumn :+ []) +++ ((guard (topRow>0) >>) $+ " <config:config-item config:name='VerticalSplitMode' config:type='short'>2</config:config-item>" :+ printf " <config:config-item config:name='VerticalSplitPosition' config:type='int'>%d</config:config-item>" topRow :+ printf " <config:config-item config:name='PositionBottom' config:type='int'>%d</config:config-item>" topRow :+ []) +++ " </config:config-item-map-entry>" :+ []) +++ " </config:config-item-map-named>" :+ " </config:config-item-map-entry>" :+ " </config:config-item-map-indexed>" :+ " </config:config-item-set>" :+ " </office:settings>" :+ []++ tableOpen name =+ "<office:body>" :+ "<office:spreadsheet>" :+ printf "<table:table table:name='%s'>" name :+ []++ tableClose =+ "</table:table>" :+ "</office:spreadsheet>" :+ "</office:body>" :+ []++ in TL.unlines $ map (TL.fromStrict . T.pack) $+ fileOpen+ (let styles = cellStyles (foldMap (concat.snd) tables) in+ (numberConfig =<< Set.toList (foldMap (numberParams.snd) styles))+ +++ (cellConfig =<< Set.toList styles)) +++ tableConfig (fmap fst tables) +++ (Map.toAscList tables >>= \(name,(_,table)) ->+ tableOpen name +++ (table >>= \row ->+ "<table:table-row>" :+ (row >>= formatCell) +++ "</table:table-row>" :+ []) +++ tableClose) +++ fileClose+++dataStyleFromType :: Type -> DataStyle+dataStyleFromType typ =+ case typ of+ TypeString -> DataString+ TypeInteger -> DataInteger+ TypeDate -> DataDate+ TypeAmount amt -> DataAmount $ commodityStyleFromAmount amt+ TypeMixedAmount -> DataMixedAmount++cellStyles ::+ (Ord border) =>+ [Cell border Text] ->+ Set ((Spr.Border border, Style), DataStyle)+cellStyles =+ Set.fromList .+ map (\cell ->+ ((cellBorder cell, cellStyle cell),+ dataStyleFromType $ cellType cell))++data CommodityStyle =+ CommodityStyle {+ commodityStyle :: CommoditySymbol,+ commodityPrecision :: AmountPrecision,+ commodityGrouping :: Bool+ } deriving (Eq, Ord, Show)++commodityStyleFromAmount :: Amount -> CommodityStyle+commodityStyleFromAmount amt =+ CommodityStyle+ (acommodity amt)+ (asprecision $ astyle amt)+ (case asdigitgroups $ astyle amt of+ Just (DigitGroups _ (_:_)) -> True+ _ -> False)++numberStyleName :: CommodityStyle -> String+numberStyleName (CommodityStyle comm prec grp) =+ printf "%s-%s%s"+ comm+ (case prec of+ NaturalPrecision -> "natural"+ Precision k -> show k)+ (if grp then "-grouping" else "")++numberParams :: DataStyle -> Set CommodityStyle+numberParams (DataAmount commStyle) = Set.singleton commStyle+numberParams _ = Set.empty++numberConfig :: CommodityStyle -> [String]+numberConfig commStyle@(CommodityStyle comm prec grp) =+ let precStr =+ case prec of+ NaturalPrecision -> ""+ Precision k -> printf " number:decimal-places='%d'" k+ grpStr =+ if grp+ then " number:grouping='true'"+ else ""+ name = numberStyleName commStyle+ in+ printf " <number:number-style style:name='number-%s'>" name :+ printf " <number:number number:min-integer-digits='1'%s%s/>"+ precStr grpStr :+ printf " <number:text>%s%s</number:text>"+ (if T.null comm then "" else " ") comm :+ " </number:number-style>" :+ []++emphasisName :: Emphasis -> String+emphasisName emph =+ case emph of+ Item -> "item"+ Total -> "total"++cellStyleName :: Style -> String+cellStyleName style =+ case style of+ Head -> "head"+ Body emph -> emphasisName emph++linesName :: Spr.NumLines -> Maybe String+linesName prop =+ case prop of+ Spr.NoLine -> Nothing+ Spr.SingleLine -> Just "single"+ Spr.DoubleLine -> Just "double"++linesStyle :: Spr.NumLines -> String+linesStyle prop =+ case prop of+ Spr.NoLine -> "none"+ Spr.SingleLine -> "1.5pt solid #000000"+ Spr.DoubleLine -> "1.5pt double-thin #000000"++borderLabels :: Spr.Border String+borderLabels = Spr.Border "left" "right" "top" "bottom"++borderName :: Spr.Border Spr.NumLines -> String+borderName border =+ (\bs ->+ case bs of+ [] -> "noborder"+ _ ->+ ("border="++) $ List.intercalate "," $+ map (\(name,num) -> name ++ ':' : num) bs) $+ catMaybes $ Fold.toList $+ liftA2+ (\name numLines -> (,) name <$> linesName numLines)+ borderLabels+ border++borderStyle :: Spr.Border Spr.NumLines -> [String]+borderStyle border =+ if border == Spr.noBorder+ then []+ else (:[]) $+ printf " <style:table-cell-properties%s/>" $+ (id :: String -> String) $ fold $+ liftA2 (printf " fo:border-%s='%s'") borderLabels $+ fmap linesStyle border++data DataStyle =+ DataString+ | DataInteger+ | DataDate+ | DataAmount CommodityStyle+ | DataMixedAmount+ deriving (Eq, Ord, Show)++cellConfig :: ((Spr.Border Spr.NumLines, Style), DataStyle) -> [String]+cellConfig ((border, cstyle), dataStyle) =+ let boldStyle = " <style:text-properties fo:font-weight='bold'/>"+ alignTop =+ " <style:table-cell-properties style:vertical-align='top'/>"+ alignParagraph =+ printf " <style:paragraph-properties fo:text-align='%s'/>"+ moreStyles =+ borderStyle border+ +++ (+ case cstyle of+ Body Item ->+ alignTop :+ []+ Body Total ->+ alignTop :+ boldStyle :+ []+ Head ->+ alignParagraph "center" :+ boldStyle :+ []+ )+ +++ (+ case dataStyle of+ DataMixedAmount -> [alignParagraph "end"]+ _ -> []+ )+ style :: String+ style =+ let (styleName,dataStyleName) = styleNames cstyle border dataStyle+ in printf "style:name='%s'" styleName+ +++ foldMap (printf " style:data-style-name='%s'") dataStyleName+ in+ case moreStyles of+ [] ->+ printf " <style:style style:family='table-cell' %s/>" style :+ []+ _ ->+ printf " <style:style style:family='table-cell' %s>" style :+ moreStyles +++ " </style:style>" :+ []+++formatCell :: Cell Spr.NumLines Text -> [String]+formatCell cell =+ let style, valueType :: String+ style =+ printf " table:style-name='%s'" $ fst $+ styleNames+ (cellStyle cell)+ (cellBorder cell)+ (dataStyleFromType $ cellType cell)++ valueType =+ case cellType cell of+ TypeInteger ->+ printf+ "office:value-type='float' office:value='%s'"+ (cellContent cell)+ TypeAmount amt ->+ printf+ "office:value-type='float' office:value='%s'"+ (show $ aquantity amt)+ TypeDate ->+ printf+ "office:value-type='date' office:date-value='%s'"+ (cellContent cell)+ _ -> "office:value-type='string'"++ covered =+ case cellSpan cell of+ Spr.Covered -> "covered-"+ _ -> ""++ span_ =+ case cellSpan cell of+ Spr.SpanHorizontal n | n>1 ->+ printf " table:number-columns-spanned='%d'" n+ Spr.SpanVertical n | n>1 ->+ printf " table:number-rows-spanned='%d'" n+ _ -> ""++ anchor text =+ if T.null $ Spr.cellAnchor cell+ then text+ else printf "<text:a xlink:href='%s'>%s</text:a>"+ (escape $ T.unpack $ Spr.cellAnchor cell) text++ in+ printf "<table:%stable-cell%s%s %s>" covered style span_ valueType :+ printf "<text:p>%s</text:p>"+ (anchor $ escape $ T.unpack $ cellContent cell) :+ printf "</table:%stable-cell>" covered :+ []++styleNames ::+ Style -> Spr.Border Spr.NumLines -> DataStyle -> (String, Maybe String)+styleNames cstyle border dataStyle =+ let cstyleName = cellStyleName cstyle in+ let bordName = borderName border in+ case dataStyle of+ DataDate ->+ (printf "%s-%s-date" cstyleName bordName, Just "iso-date")+ DataInteger ->+ (printf "%s-%s-integer" cstyleName bordName, Just "integer")+ DataAmount commStyle ->+ let name = numberStyleName commStyle in+ (printf "%s-%s-%s" cstyleName bordName name,+ Just $ printf "number-%s" name)+ DataMixedAmount ->+ (printf "%s-%s-mixedamount" cstyleName bordName, Nothing)+ DataString -> (printf "%s-%s" cstyleName bordName, Nothing)++escape :: String -> String+escape =+ concatMap $ \c ->+ case c of+ '\n' -> " "+ '&' -> "&"+ '<' -> "<"+ '>' -> ">"+ '"' -> """+ '\'' -> "'"+ _ -> [c]
+ Hledger/Write/Spreadsheet.hs view
@@ -0,0 +1,300 @@+{- |+Rich data type to describe data in a table.+This is the basis for ODS and HTML export.+-}+module Hledger.Write.Spreadsheet (+ Type(..),+ Style(..),+ Emphasis(..),+ Cell(..),+ Class(Class), textFromClass,+ Span(..),+ Border(..),+ Lines(..),+ NumLines(..),+ noBorder,+ defaultCell,+ headerCell,+ emptyCell,+ transposeCell,+ transpose,+ horizontalSpan,+ addHeaderBorders,+ addRowSpanHeader,+ addRowSpanHeaderNE,+ rawTableContent,+ cellFromMixedAmount,+ cellsFromMixedAmount,+ cellFromAmount,+ integerCell,+ ) where++import Hledger.Data.Amount qualified as Amt+import Hledger.Data.Types (Amount, MixedAmount, acommodity)+import Hledger.Data.Amount (AmountFormat)++import Data.Foldable qualified as Fold+import Data.List.NonEmpty (NonEmpty((:|)))+import Data.List qualified as List+import Data.Maybe (isNothing)+import Data.Text qualified as Text+import Data.Text (Text)+import Text.WideString (WideBuilder)++import Prelude hiding (span)+++data Type =+ TypeString+ | TypeInteger+ | TypeAmount !Amount+ | TypeMixedAmount+ | TypeDate+ deriving (Eq, Ord, Show)++data Style = Body Emphasis | Head+ deriving (Eq, Ord, Show)++data Emphasis = Item | Total+ deriving (Eq, Ord, Show)+++class Lines border where noLine :: border+instance Lines () where noLine = ()+instance Lines NumLines where noLine = NoLine++{- |+The same as Tab.Properties, but has 'Eq' and 'Ord' instances.+We need those for storing 'NumLines' in 'Set's.+-}+data NumLines = NoLine | SingleLine | DoubleLine+ deriving (Eq, Ord, Show)++data Border lines =+ Border {+ borderLeft, borderRight,+ borderTop, borderBottom :: lines+ }+ deriving (Eq, Ord, Show)++instance Functor Border where+ fmap f (Border left right top bottom) =+ Border (f left) (f right) (f top) (f bottom)++instance Applicative Border where+ pure a = Border a a a a+ Border fLeft fRight fTop fBottom <*> Border left right top bottom =+ Border (fLeft left) (fRight right) (fTop top) (fBottom bottom)++instance Foldable Border where+ foldMap f (Border left right top bottom) =+ f left <> f right <> f top <> f bottom++noBorder :: (Lines border) => Border border+noBorder = pure noLine++transposeBorder :: Border lines -> Border lines+transposeBorder (Border left right top bottom) =+ Border top bottom left right+++newtype Class = Class Text++textFromClass :: Class -> Text+textFromClass (Class cls) = cls+++{- |+* 'NoSpan' means a single unmerged cell.++* 'Covered' is a cell if it is part of a horizontally or vertically merged cell.+ We maintain these cells although they are ignored in HTML output.+ In contrast to that, FODS can store covered cells+ and allows to access the hidden cell content via formulas.+ CSV does not support merged cells+ and thus simply writes the content of covered cells.+ Maintaining 'Covered' cells also simplifies transposing.++* @'SpanHorizontal' n@ denotes the first cell in a row+ that is part of a merged cell.+ The merged cell contains @n@ atomic cells, including the first one.+ That is @SpanHorizontal 1@ is actually like @NoSpan@.+ The content of this cell is shown as content of the merged cell.++* @'SpanVertical' n@ starts a vertically merged cell.++The writer functions expect consistent data,+that is, 'Covered' cells must actually be part of a merged cell+and merged cells must only cover 'Covered' cells.+-}+data Span =+ NoSpan+ | Covered+ | SpanHorizontal Int+ | SpanVertical Int+ deriving (Eq)++transposeSpan :: Span -> Span+transposeSpan span =+ case span of+ NoSpan -> NoSpan+ Covered -> Covered+ SpanHorizontal n -> SpanVertical n+ SpanVertical n -> SpanHorizontal n++data Cell border text =+ Cell {+ cellType :: Type,+ cellBorder :: Border border,+ cellStyle :: Style,+ cellSpan :: Span,+ cellAnchor :: Text,+ -- | A whole-phrase description of where 'cellAnchor' leads, for+ -- writers that can attach one to a link (HTML's title attribute).+ -- Ignored when there is no anchor.+ cellTitle :: Text,+ cellClass :: Class,+ -- | The cell content split into parts to be joined with ", ":+ -- individual amounts of a multi-commodity amount, for writers+ -- (eg HTML) that want to style each amount separately.+ -- Empty for other cells and writers; 'cellContent' is always complete.+ cellParts :: [text],+ cellContent :: text+ }++instance Functor (Cell border) where+ fmap f (Cell typ border style span anchor title class_ parts content) =+ Cell typ border style span anchor title class_ (map f parts) (f content)++defaultCell :: (Lines border) => text -> Cell border text+defaultCell text =+ Cell {+ cellType = TypeString,+ cellBorder = noBorder,+ cellStyle = Body Item,+ cellSpan = NoSpan,+ cellAnchor = mempty,+ cellTitle = mempty,+ cellClass = Class mempty,+ cellParts = [],+ cellContent = text+ }++headerCell :: (Lines borders) => Text -> Cell borders Text+headerCell text = (defaultCell text) {cellStyle = Head}++emptyCell :: (Lines border, Monoid text) => Cell border text+emptyCell = defaultCell mempty++transposeCell :: Cell border text -> Cell border text+transposeCell cell =+ cell {+ cellBorder = transposeBorder $ cellBorder cell,+ cellSpan = transposeSpan $ cellSpan cell+ }++transpose :: [[Cell border text]] -> [[Cell border text]]+transpose = List.transpose . map (map transposeCell)+++addHeaderBorders :: (Functor f) => f (Cell () text) -> f (Cell NumLines text)+addHeaderBorders =+ fmap (\c -> c {cellBorder = noBorder {borderBottom = DoubleLine}})++horizontalSpan ::+ (Lines border, Monoid text) =>+ [a] -> Cell border text -> [Cell border text]+horizontalSpan subCells cell =+ zipWith const+ (cell{cellSpan = SpanHorizontal $ length subCells}+ : repeat (emptyCell {cellSpan = Covered}))+ subCells++addRowSpanHeader ::+ Cell border text ->+ [[Cell border text]] -> [[Cell border text]]+addRowSpanHeader header = map Fold.toList . addRowSpanHeaderNE header++addRowSpanHeaderNE ::+ Cell border text ->+ [[Cell border text]] -> [NonEmpty (Cell border text)]+addRowSpanHeaderNE header rows =+ case rows of+ [] -> []+ [row] -> [header:|row]+ _ ->+ zipWith (:|)+ (header{cellSpan = SpanVertical (length rows)} :+ repeat header{cellSpan = Covered})+ rows++rawTableContent :: (Functor f) => [f (Cell border text)] -> [f text]+rawTableContent = map (fmap cellContent)++++-- | Add the "negative" class to a negative amount's cell, so that writers+-- with a stylesheet (HTML) can color it. A cell whose rendering rounds to+-- zero is not marked+markNegative :: Bool -> Class -> Class+markNegative False cls = cls+markNegative True (Class cls) =+ Class $ Text.unwords $ filter (not . Text.null) [cls, Text.pack "negative"]++cellFromMixedAmount ::+ (Lines border) =>+ AmountFormat -> (Class, MixedAmount) -> Cell border WideBuilder+cellFromMixedAmount bopts (cls, mixedAmt) =+ (defaultCell $ Amt.showMixedAmountB bopts mixedAmt) {+ cellClass =+ markNegative+ (Amt.isNegativeMixedAmount mixedAmt == Just True+ && not (Amt.mixedAmountLooksZero mixedAmt)) cls,+ cellType =+ case Amt.unifyMixedAmount mixedAmt of+ Just amt -> amountType bopts amt+ Nothing -> TypeMixedAmount,+ -- Individual amounts, for writers that style them separately (eg HTML).+ -- Only when they can be recovered exactly from the one-line rendering+ -- (padding to displayMinWidth is insignificant in those writers).+ cellParts =+ if Amt.displayOneLine bopts && isNothing (Amt.displayMaxWidth bopts)+ then map fst $ Amt.showMixedAmountOneLinePartsB bopts mixedAmt+ else []+ }++cellsFromMixedAmount ::+ (Lines border) =>+ AmountFormat -> (Class, MixedAmount) -> [Cell border WideBuilder]+cellsFromMixedAmount bopts (cls, mixedAmt) =+ map+ (\(str,amt) ->+ (defaultCell str) {+ cellClass =+ markNegative+ (Amt.isNegativeAmount amt && not (Amt.amountLooksZero amt)) cls,+ cellType = amountType bopts amt+ })+ (Amt.showMixedAmountLinesPartsB bopts mixedAmt)++cellFromAmount ::+ (Lines border) =>+ AmountFormat -> (Class, (wb, Amount)) -> Cell border wb+cellFromAmount bopts (cls, (str,amt)) =+ (defaultCell str) {+ cellClass =+ markNegative+ (Amt.isNegativeAmount amt && not (Amt.amountLooksZero amt)) cls,+ cellType = amountType bopts amt+ }++amountType :: AmountFormat -> Amount -> Type+amountType bopts amt =+ TypeAmount $+ if Amt.displayCommodity bopts+ then amt+ else amt {acommodity = Text.empty}+++integerCell :: (Lines border) => Integer -> Cell border Text+integerCell k = (defaultCell $ Text.pack $ show k) {cellType = TypeInteger}
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-lib++A reusable library containing hledger's core functionality.+This is used by most hledger* packages so that they support the same+common file formats, command line options, reports etc.++See also:+the [project README](https://hledger.org/README.html)+and [home page](https://hledger.org).
+ Text/Tabular/AsciiWide.hs view
@@ -0,0 +1,323 @@+-- | Text.Tabular.AsciiArt from tabular-0.2.2.7, modified to treat+-- wide characters as double width.++{-# LANGUAGE OverloadedStrings #-}++module Text.Tabular.AsciiWide+( module Text.Tabular++, TableOpts(..)+, render+, renderTable+, renderTableB+, renderTableByRowsB+, renderRow+, renderRowB+, renderColumns++, Cell(..)+, Align(..)+, emptyCell+, textCell+, textsCell+, cellWidth+, concatTables+) where++import Data.Bifunctor (bimap)+import Data.Maybe (fromMaybe)+import Data.Default (Default(..))+import Data.List (intersperse, transpose)+import Data.Semigroup (stimesMonoid)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder (Builder, fromString, fromText, singleton, toLazyText)+import Safe (maximumMay)+import Text.Tabular+import Text.WideString (WideBuilder(..), wbFromText)+++-- | The options to use for rendering a table.+data TableOpts = TableOpts+ { prettyTable :: Bool -- ^ Pretty tables+ , tableBorders :: Bool -- ^ Whether to display the outer borders+ , borderSpaces :: Bool -- ^ Whether to display spaces around bars+ } deriving (Show)++instance Default TableOpts where+ def = TableOpts { prettyTable = False+ , tableBorders = True+ , borderSpaces = True+ }++-- | Cell contents along an alignment+data Cell = Cell Align [WideBuilder]++-- | How to align text in a cell+data Align = TopRight | BottomRight | BottomLeft | TopLeft+ deriving (Show)++emptyCell :: Cell+emptyCell = Cell TopRight []++-- | Create a single-line cell from the given contents with its natural width.+textCell :: Align -> Text -> Cell+textCell a x = Cell a . map wbFromText $ if T.null x then [""] else T.lines x++-- | Create a multi-line cell from the given contents with its natural width.+textsCell :: Align -> [Text] -> Cell+textsCell a = Cell a . fmap wbFromText++-- | Return the width of a Cell.+cellWidth :: Cell -> Int+cellWidth (Cell _ xs) = fromMaybe 0 . maximumMay $ map wbWidth xs+++-- | Render a table according to common options, for backwards compatibility+render :: Show a => Bool -> (rh -> Text) -> (ch -> Text) -> (a -> Text) -> Table rh ch a -> TL.Text+render pretty fr fc f = renderTable def{prettyTable=pretty} (cell . fr) (cell . fc) (cell . f)+ where cell = textCell TopRight++-- | Render a table according to various cell specifications>+renderTable :: Show a =>+ TableOpts -- ^ Options controlling Table rendering+ -> (rh -> Cell) -- ^ Rendering function for row headers+ -> (ch -> Cell) -- ^ Rendering function for column headers+ -> (a -> Cell) -- ^ Function determining the string and width of a cell+ -> Table rh ch a+ -> TL.Text+renderTable topts fr fc f = toLazyText . renderTableB topts fr fc f++-- | A version of renderTable which returns the underlying Builder.+renderTableB :: Show a =>+ TableOpts -- ^ Options controlling Table rendering+ -> (rh -> Cell) -- ^ Rendering function for row headers+ -> (ch -> Cell) -- ^ Rendering function for column headers+ -> (a -> Cell) -- ^ Function determining the string and width of a cell+ -> Table rh ch a+ -> Builder+renderTableB topts fr fc f = renderTableByRowsB topts (fmap fc) $ bimap fr (fmap f)++-- | A version of renderTable that operates on rows (including the 'row' of+-- column headers) and returns the underlying Builder.+renderTableByRowsB :: Show a =>+ TableOpts -- ^ Options controlling Table rendering+ -> ([ch] -> [Cell]) -- ^ Rendering function for column headers+ -> ((rh, [a]) -> (Cell, [Cell])) -- ^ Rendering function for row and row header+ -> Table rh ch a+ -> Builder+renderTableByRowsB topts@TableOpts{prettyTable=pretty, tableBorders=borders} fc f (Table rh ch cells) =+ unlinesB . addBorders $+ renderColumns topts sizes ch2+ : bar VM DoubleLine -- +======================================++ : renderRs (renderR <$> zipHeader [] cellContents rowHeaders)+ where+ renderR :: ([Cell], Cell) -> Builder+ renderR (cs,h) = renderColumns topts sizes $ Group DoubleLine+ [ Header h+ , fst <$> zipHeader emptyCell cs colHeaders+ ]++ rows = unzip . fmap f $ zip (headerContents rh) cells+ rowHeaders = fst <$> zipHeader emptyCell (fst rows) rh+ colHeaders = fst <$> zipHeader emptyCell (fc $ headerContents ch) ch+ cellContents = snd rows++ -- ch2 and cell2 include the row and column labels+ ch2 = Group DoubleLine [Header emptyCell, colHeaders]+ cells2 = headerContents ch2 : zipWith (:) (headerContents rowHeaders) cellContents++ -- maximum width for each column+ sizes = map (fromMaybe 0 . maximumMay . map cellWidth) $ transpose cells2+ renderRs =+ concatMap (either (renderHLine VM borders pretty sizes ch2) (:[])) .+ flattenHeader++ -- borders and bars+ addBorders xs = if borders then bar VT SingleLine : xs ++ [bar VB SingleLine] else xs+ bar vpos prop = mconcat $ renderHLine vpos borders pretty sizes ch2 prop+ unlinesB = foldMap (<> singleton '\n')++-- | Render a single row according to cell specifications.+renderRow :: TableOpts -> Header Cell -> TL.Text+renderRow topts = toLazyText . renderRowB topts++-- | A version of renderRow which returns the underlying Builder.+renderRowB:: TableOpts -> Header Cell -> Builder+renderRowB topts h = renderColumns topts ws h where ws = map cellWidth $ headerContents h++verticalBar :: Bool -> Char+verticalBar pretty = if pretty then '│' else '|'++leftBar :: Bool -> Bool -> Builder+leftBar pretty True = fromString $ verticalBar pretty : " "+leftBar pretty False = singleton $ verticalBar pretty++rightBar :: Bool -> Bool -> Builder+rightBar pretty True = fromString $ ' ' : [verticalBar pretty]+rightBar pretty False = singleton $ verticalBar pretty++midBar :: Bool -> Bool -> Builder+midBar pretty True = fromString $ ' ' : verticalBar pretty : " "+midBar pretty False = singleton $ verticalBar pretty++doubleMidBar :: Bool -> Bool -> Builder+doubleMidBar pretty True = fromText $ if pretty then " ║ " else " || "+doubleMidBar pretty False = fromText $ if pretty then "║" else "||"++-- | We stop rendering on the shortest list!+renderColumns :: TableOpts -- ^ rendering options for the table+ -> [Int] -- ^ max width for each column+ -> Header Cell+ -> Builder+renderColumns TableOpts{prettyTable=pretty, tableBorders=borders, borderSpaces=spaces} is h =+ mconcat . intersperse "\n" -- Put each line on its own line+ . map (addBorders . finishLine) -- Add borders+ . foldr (zipWith ($)) (replicate nLines (PartialLine 0 mempty)) -- Build each line, from right to left+ . map (either hsep cellLines) . flattenHeader+ . zipHeader 0 is $ h -- Add width marker+ where+ -- Each column's contribution to each line (having the same number of lines as the others,+ -- with blank lines added according to the cell's vertical alignment).+ cellLines (w, Cell TopLeft ls) = map (leftAligned w) ls ++ blankLines w ls+ cellLines (w, Cell BottomLeft ls) = blankLines w ls ++ map (leftAligned w) ls+ cellLines (w, Cell TopRight ls) = map (rightAligned w) ls ++ blankLines w ls+ cellLines (w, Cell BottomRight ls) = blankLines w ls ++ map (rightAligned w) ls++ blankLines w ls = replicate (nLines - length ls) (addSpaces w)++ hsep :: Properties -> [PartialLine -> PartialLine]+ hsep NoLine = replicate nLines $ if spaces then addSpaces 2 else id+ hsep SingleLine = replicate nLines $ addText $ midBar pretty spaces+ hsep DoubleLine = replicate nLines $ addText $ doubleMidBar pretty spaces++ addBorders xs | borders = leftBar pretty spaces <> xs <> rightBar pretty spaces+ | spaces = fromText " " <> xs <> fromText " "+ | otherwise = xs++ nLines = fromMaybe 0 . maximumMay . map (\(Cell _ ls) -> length ls) $ headerContents h++-- | A table line being built from right to left: some leading spaces, kept as a count so that+-- runs of them from blank cells can be merged, and the text after those. Table rows are often+-- mostly blank (eg a register row with a many-commodity balance), so this saves a lot of work.+data PartialLine = PartialLine !Int Builder++addSpaces :: Int -> PartialLine -> PartialLine+addSpaces w (PartialLine n b) = PartialLine (n + w) b++addText :: Builder -> PartialLine -> PartialLine+addText t l = PartialLine 0 (t <> finishLine l)++leftAligned, rightAligned :: Int -> WideBuilder -> PartialLine -> PartialLine+leftAligned w x = addText (wbBuilder x) . addSpaces (max 0 $ w - wbWidth x)+rightAligned w x = addSpaces (max 0 $ w - wbWidth x) . addText (wbBuilder x)++finishLine :: PartialLine -> Builder+finishLine (PartialLine n b)+ | n <= 0 = b+ | otherwise = fromText (T.replicate n " ") <> b++renderHLine :: VPos+ -> Bool -- ^ show outer borders+ -> Bool -- ^ pretty+ -> [Int] -- ^ width specifications+ -> Header a+ -> Properties+ -> [Builder]+renderHLine _ _ _ _ _ NoLine = []+renderHLine vpos borders pretty w h prop = [renderHLine' vpos borders pretty prop w h]++renderHLine' :: VPos -> Bool -> Bool -> Properties -> [Int] -> Header a -> Builder+renderHLine' vpos borders pretty prop is hdr = addBorders $ sep <> coreLine <> sep+ where+ addBorders xs = if borders then edge HL <> xs <> edge HR else xs+ edge hpos = boxchar vpos hpos SingleLine prop pretty+ coreLine = foldMap helper $ flattenHeader $ zipHeader 0 is hdr+ helper = either vsep dashes+ dashes (i,_) = stimesMonoid i sep+ sep = boxchar vpos HM NoLine prop pretty+ vsep v = case v of+ NoLine -> sep <> sep+ _ -> sep <> cross v prop <> sep+ cross v h = boxchar vpos HM v h pretty++data VPos = VT | VM | VB -- top middle bottom+data HPos = HL | HM | HR -- left middle right++boxchar :: VPos -> HPos -> Properties -> Properties -> Bool -> Builder+boxchar vpos hpos vert horiz = lineart u d l r+ where+ u = case vpos of+ VT -> NoLine+ _ -> vert+ d = case vpos of+ VB -> NoLine+ _ -> vert+ l = case hpos of+ HL -> NoLine+ _ -> horiz+ r = case hpos of+ HR -> NoLine+ _ -> horiz++pick :: Text -> Text -> Bool -> Builder+pick x _ True = fromText x+pick _ x False = fromText x++lineart :: Properties -> Properties -> Properties -> Properties -> Bool -> Builder+-- up down left right+lineart SingleLine SingleLine SingleLine SingleLine = pick "┼" "+"+lineart SingleLine SingleLine SingleLine NoLine = pick "┤" "+"+lineart SingleLine SingleLine NoLine SingleLine = pick "├" "+"+lineart SingleLine NoLine SingleLine SingleLine = pick "┴" "+"+lineart NoLine SingleLine SingleLine SingleLine = pick "┬" "+"+lineart SingleLine NoLine NoLine SingleLine = pick "└" "+"+lineart SingleLine NoLine SingleLine NoLine = pick "┘" "+"+lineart NoLine SingleLine SingleLine NoLine = pick "┐" "+"+lineart NoLine SingleLine NoLine SingleLine = pick "┌" "+"+lineart SingleLine SingleLine NoLine NoLine = pick "│" "|"+lineart NoLine NoLine SingleLine SingleLine = pick "─" "-"++lineart DoubleLine DoubleLine DoubleLine DoubleLine = pick "╬" "++"+lineart DoubleLine DoubleLine DoubleLine NoLine = pick "╣" "++"+lineart DoubleLine DoubleLine NoLine DoubleLine = pick "╠" "++"+lineart DoubleLine NoLine DoubleLine DoubleLine = pick "╩" "++"+lineart NoLine DoubleLine DoubleLine DoubleLine = pick "╦" "++"+lineart DoubleLine NoLine NoLine DoubleLine = pick "╚" "++"+lineart DoubleLine NoLine DoubleLine NoLine = pick "╝" "++"+lineart NoLine DoubleLine DoubleLine NoLine = pick "╗" "++"+lineart NoLine DoubleLine NoLine DoubleLine = pick "╔" "++"+lineart DoubleLine DoubleLine NoLine NoLine = pick "║" "||"+lineart NoLine NoLine DoubleLine DoubleLine = pick "═" "="++lineart DoubleLine NoLine NoLine SingleLine = pick "╙" "++"+lineart DoubleLine NoLine SingleLine NoLine = pick "╜" "++"+lineart NoLine DoubleLine SingleLine NoLine = pick "╖" "++"+lineart NoLine DoubleLine NoLine SingleLine = pick "╓" "++"++lineart SingleLine NoLine NoLine DoubleLine = pick "╘" "+"+lineart SingleLine NoLine DoubleLine NoLine = pick "╛" "+"+lineart NoLine SingleLine DoubleLine NoLine = pick "╕" "+"+lineart NoLine SingleLine NoLine DoubleLine = pick "╒" "+"++lineart DoubleLine DoubleLine SingleLine NoLine = pick "╢" "++"+lineart DoubleLine DoubleLine NoLine SingleLine = pick "╟" "++"+lineart DoubleLine NoLine SingleLine SingleLine = pick "╨" "++"+lineart NoLine DoubleLine SingleLine SingleLine = pick "╥" "++"++lineart SingleLine SingleLine DoubleLine NoLine = pick "╡" "+"+lineart SingleLine SingleLine NoLine DoubleLine = pick "╞" "+"+lineart SingleLine NoLine DoubleLine DoubleLine = pick "╧" "+"+lineart NoLine SingleLine DoubleLine DoubleLine = pick "╤" "+"++lineart SingleLine SingleLine DoubleLine DoubleLine = pick "╪" "+"+lineart DoubleLine DoubleLine SingleLine SingleLine = pick "╫" "++"++lineart _ _ _ _ = const mempty+++-- | Add the second table below the first, discarding its column headings.+concatTables :: Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a+concatTables prop (Table hLeft hTop dat) (Table hLeft' _ dat') =+ Table (Group prop [hLeft, hLeft']) hTop (dat ++ dat')
+ Text/WideString.hs view
@@ -0,0 +1,39 @@+-- | Calculate the width of String and Text, being aware of wide characters.++module Text.WideString (+ -- * Text Builders which keep track of length+ WideBuilder(..),+ wbUnpack,+ wbToText,+ wbFromText+ ) where++import Data.Text (Text)+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Text.DocLayout (realLength)+++-- | Helper for constructing Builders while keeping track of text width.+data WideBuilder = WideBuilder+ { wbBuilder :: !TB.Builder+ , wbWidth :: !Int+ } deriving (Show)++instance Semigroup WideBuilder where+ WideBuilder x i <> WideBuilder y j = WideBuilder (x <> y) (i + j)++instance Monoid WideBuilder where+ mempty = WideBuilder mempty 0++-- | Convert a WideBuilder to a strict Text.+wbToText :: WideBuilder -> Text+wbToText = TL.toStrict . TB.toLazyText . wbBuilder++-- | Convert a strict Text to a WideBuilder.+wbFromText :: Text -> WideBuilder+wbFromText t = WideBuilder (TB.fromText t) (realLength t)++-- | Convert a WideBuilder to a String.+wbUnpack :: WideBuilder -> String+wbUnpack = TL.unpack . TB.toLazyText . wbBuilder
hledger-lib.cabal view
@@ -1,82 +1,328 @@+cabal-version: 2.2++-- This file has been generated from package.yaml by hpack version 0.39.6.+--+-- see: https://github.com/sol/hpack+ name: hledger-lib-version: 0.16.1+version: 2.0+synopsis: A library providing the core functionality of hledger+description: This library contains hledger's core functionality.+ It is used by most hledger* packages so that they support the same+ command line options, file formats, reports, etc.+ .+ 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.+ .+ See also:+ .+ - https://hledger.org - hledger's home page+ .+ - https://hledger.org/dev.html - starting point for hledger's developer docs+ .+ - https://hackage.haskell.org/package/hledger-lib/docs/Hledger.html - starting point for hledger's haddock docs category: Finance-synopsis: Core data types, parsers and utilities 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.--license: GPL-license-file: LICENSE+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.6+license: GPL-3.0-or-later+license-file: LICENSE build-type: Simple--- data-dir: data--- data-files:--- extra-tmp-files:--- extra-source-files:--- README--- sample.ledger--- sample.timelog+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:+ CHANGES.md+ README.md+ locale/hledger.pot+ locale/de.po+ locale/es.po+ locale/fr.po+ locale/ga.po+ locale/haw.po+ locale/it.po+ locale/ja.po+ locale/pt-BR.po+ locale/ru.po+ locale/uk.po+ locale/zh-Hans.po+ test/unittest.hs+ test/doctests.hs +source-repository head+ type: git+ location: https://github.com/hledgerorg/hledger++flag debug+ description: Build with GHC 9.10+ stack traces enabled+ manual: True+ default: False+ library- -- should set patchlevel here as in Makefile- cpp-options: -DPATCHLEVEL=0 exposed-modules:- Hledger- Hledger.Data- Hledger.Data.Account- Hledger.Data.AccountName- Hledger.Data.Amount- Hledger.Data.Commodity- Hledger.Data.Dates- Hledger.Data.Transaction- Hledger.Data.Journal- Hledger.Data.Ledger- Hledger.Data.Matching- Hledger.Data.Posting- Hledger.Data.TimeLog- Hledger.Data.Types- Hledger.Read- Hledger.Read.JournalReader- Hledger.Read.TimelogReader- Hledger.Read.Utils- Hledger.Reports- Hledger.Utils- Hledger.Utils.UTF8- Build-Depends:- base >= 3 && < 5- ,bytestring- ,cmdargs >= 0.8 && < 0.9- ,containers- ,directory- ,filepath- ,mtl- ,old-locale- ,old-time- ,parsec- ,regexpr >= 0.5.1- ,safe >= 0.2- ,split == 0.1.*- ,time- ,utf8-string >= 0.3.5 && < 0.4- ,HUnit--source-repository head- type: darcs- location: http://joyful.com/repos/hledger+ Hledger+ Hledger.Data+ Hledger.Data.Account+ Hledger.Data.AccountName+ Hledger.Data.AccountType+ Hledger.Data.Amount+ Hledger.Data.BalanceData+ Hledger.Data.Balancing+ Hledger.Data.Currency+ Hledger.Data.Dates+ Hledger.Data.DayPartition+ Hledger.Data.Errors+ Hledger.Data.Journal+ Hledger.Data.JournalChecks+ Hledger.Data.JournalChecks.Assert+ Hledger.Data.JournalChecks.Ordereddates+ Hledger.Data.JournalChecks.Uniqueleafnames+ Hledger.Data.Json+ Hledger.Data.Ledger+ Hledger.Data.Lots+ Hledger.Data.Period+ Hledger.Data.PeriodData+ Hledger.Data.PeriodicTransaction+ Hledger.Data.Posting+ Hledger.Data.RawOptions+ Hledger.Data.StringFormat+ Hledger.Data.Timeclock+ Hledger.Data.Transaction+ Hledger.Data.TransactionModifier+ Hledger.Data.Types+ Hledger.Data.Valuation+ Hledger.Query+ Hledger.Read+ Hledger.Read.Common+ Hledger.Read.CsvReader+ Hledger.Read.InputOptions+ Hledger.Read.JournalReader+ Hledger.Read.LatestDates+ Hledger.Read.RulesReader+ Hledger.Read.TimeclockReader+ Hledger.Read.TimedotReader+ Hledger.Reports+ Hledger.Reports.AccountTransactionsReport+ Hledger.Reports.BalanceReport+ Hledger.Reports.BudgetReport+ Hledger.Reports.EntriesReport+ Hledger.Reports.MultiBalanceReport+ Hledger.Reports.PostingsReport+ Hledger.Reports.ReportOptions+ Hledger.Reports.ReportTypes+ Hledger.Utils+ Hledger.Utils.Debug+ Hledger.Utils.I18n+ Hledger.Utils.IO+ Hledger.Utils.Parse+ Hledger.Utils.Regex+ Hledger.Utils.String+ Hledger.Utils.Test+ Hledger.Utils.Text+ Hledger.Write.Beancount+ Hledger.Write.Chart+ Hledger.Write.Chart.Palette+ Hledger.Write.Chart.Svg+ Hledger.Write.Chart.Text+ Hledger.Write.Csv+ Hledger.Write.Html+ Hledger.Write.Html.Attribute+ Hledger.Write.Journal+ Hledger.Write.Ledger+ Hledger.Write.Ods+ Hledger.Write.Spreadsheet+ Text.Tabular.AsciiWide+ Text.WideString+ other-modules:+ Paths_hledger_lib+ autogen-modules:+ Paths_hledger_lib+ hs-source-dirs:+ ./+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind+ cpp-options: -DVERSION="2.0"+ build-depends:+ Decimal >=0.5.1+ , Glob >=0.9+ , aeson >=2.2.5.1 && <2.4+ , aeson-pretty+ , ansi-terminal >=0.9+ , array+ , base >=4.18 && <4.23+ , blaze-html+ , blaze-markup >=0.5.1+ , blaze-svg >=0.3.7+ , bytestring+ , call-stack+ , cassava+ , cassava-megaparsec+ , cmdargs >=0.10+ , colour >=2.3.6+ , containers >=0.5.9+ , data-default >=0.5+ , deepseq+ , directory >=1.2.6.1+ , doclayout >=0.3 && <0.7+ , encoding >=0.10+ , extra >=1.7.11+ , file-embed >=0.0.10+ , filepath+ , hashtables >=1.2.3.1 && <1.3 || >=1.4.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , microlens-th >=0.4+ , mtl >=2.2.1+ , parser-combinators >=0.4.0+ , pretty-simple ==4.*+ , process+ , regex-tdfa+ , safe >=0.3.20+ , safe-exceptions+ , tabular >=0.2+ , tasty >=1.2.3+ , tasty-hunit >=0.10.0.2+ , template-haskell+ , temporary+ , terminal-size >=0.3.3+ , text >=1.2.4.1+ , these >=1.0.0+ , time >=1.5+ , timeit+ , transformers >=0.2+ , uglymemo+ , unordered-containers >=0.2+ , utf8-string >=0.3.5+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG --- cf http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html+test-suite doctest+ type: exitcode-stdio-1.0+ main-is: doctests.hs+ hs-source-dirs:+ test+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind+ cpp-options: -DVERSION="2.0"+ build-depends:+ Decimal >=0.5.1+ , Glob >=0.7+ , aeson >=2.2.5.1 && <2.4+ , aeson-pretty+ , ansi-terminal >=0.9+ , array+ , base >=4.18 && <4.23+ , blaze-html+ , blaze-markup >=0.5.1+ , blaze-svg >=0.3.7+ , bytestring+ , call-stack+ , cassava+ , cassava-megaparsec+ , cmdargs >=0.10+ , colour >=2.3.6+ , containers >=0.5.9+ , data-default >=0.5+ , deepseq+ , directory >=1.2.6.1+ , doclayout >=0.3 && <0.7+ , doctest >=0.18.1+ , encoding >=0.10+ , extra >=1.7.11+ , file-embed >=0.0.10+ , filepath+ , hashtables >=1.2.3.1 && <1.3 || >=1.4.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , microlens-th >=0.4+ , mtl >=2.2.1+ , parser-combinators >=0.4.0+ , pretty-simple ==4.*+ , process+ , regex-tdfa+ , safe >=0.3.20+ , safe-exceptions+ , tabular >=0.2+ , tasty >=1.2.3+ , tasty-hunit >=0.10.0.2+ , template-haskell+ , temporary+ , terminal-size >=0.3.3+ , text >=1.2.4.1+ , these >=1.0.0+ , time >=1.5+ , timeit+ , transformers >=0.2+ , uglymemo+ , unordered-containers >=0.2+ , utf8-string >=0.3.5+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG --- Additional dependencies:--- required for make test: test-framework, test-framework-hunit--- required for make bench: tabular-0.1+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+ cpp-options: -DVERSION="2.0"+ build-depends:+ Decimal >=0.5.1+ , Glob >=0.9+ , aeson >=2.2.5.1 && <2.4+ , aeson-pretty+ , ansi-terminal >=0.9+ , array+ , base >=4.18 && <4.23+ , blaze-html+ , blaze-markup >=0.5.1+ , blaze-svg >=0.3.7+ , bytestring+ , call-stack+ , cassava+ , cassava-megaparsec+ , cmdargs >=0.10+ , colour >=2.3.6+ , containers >=0.5.9+ , data-default >=0.5+ , deepseq+ , directory >=1.2.6.1+ , doclayout >=0.3 && <0.7+ , encoding >=0.10+ , extra >=1.7.11+ , file-embed >=0.0.10+ , filepath+ , hashtables >=1.2.3.1 && <1.3 || >=1.4.0+ , hledger-lib+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , microlens-th >=0.4+ , mtl >=2.2.1+ , parser-combinators >=0.4.0+ , pretty-simple ==4.*+ , process+ , regex-tdfa+ , safe >=0.3.20+ , safe-exceptions+ , tabular >=0.2+ , tasty >=1.2.3+ , tasty-hunit >=0.10.0.2+ , template-haskell+ , temporary+ , terminal-size >=0.3.3+ , text >=1.2.4.1+ , these >=1.0.0+ , time >=1.5+ , timeit+ , transformers >=0.2+ , uglymemo+ , unordered-containers >=0.2+ , utf8-string >=0.3.5+ buildable: True+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG
+ locale/de.po view
@@ -0,0 +1,3053 @@+# German translations for hledger.+# This file is distributed under the same license as hledger.+# Translators: Arthur Cinader, Henning Thielemann.+# Entries marked "machine-translated, please review" were made by machine (Claude Opus 5.5);+# when you have checked one, delete its mark.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: de\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n != 1);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Januar"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Februar"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "März"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "April"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Mai"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Juni"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Juli"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "August"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "September"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Oktober"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "November"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Dezember"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Jan"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Feb"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mär"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Apr"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Mai"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Jun"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Jul"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Aug"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Sep"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Okt"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Nov"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Dez"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Berichtsdetails"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Gesamt"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Vermögen"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Verbindlichkeiten"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Eigenkapital"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Einnahmen"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Ausgaben"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Sonstige"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Saldo"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Gesamt"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Überschuss:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…und {n} weiteres"+msgstr[1] "…und {n} weitere"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "sonstige {parent} ({n} Konto)"+msgstr[1] "sonstige {parent} ({n} Konten)"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "sonstige ({n} Konto)"+msgstr[1] "sonstige ({n} Konten)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Wertänderungen zum Periodenende)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Kumulierte Wertänderungen zum Periodenende)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Inkrementeller Gewinn)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Kumulierter Gewinn)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Historischer Gewinn)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Saldoänderungen)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Kumulierte Endsalden)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Historische Endsalden)"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", zum Transaktionspreis"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", bewertet zum Buchungsdatum"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", bewertet zum Periodenende"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", aktueller Wert"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", bewertet zum {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Soll-Ist-Vergleich"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Saldenbericht nach Perioden"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Saldenbericht"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} in {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Wertänderungen zum Periodenende"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Kumulierte Wertänderungen zum Periodenende"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Inkrementeller Gewinn"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Kumulierter Gewinn"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Historischer Gewinn"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Anzahl der Buchungszeilen"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Kumulierte Anzahl der Buchungszeilen"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Historische Anzahl der Buchungszeilen"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Anzahl der Buchungen"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Saldoänderungen"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Endsalden (kumuliert)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Endsalden (historisch)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Soll-Ist-Vergleich in {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Einheit"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Durchschnitt"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Tägliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Wöchentliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Zweiwöchentliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Monatliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Zweimonatliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Vierteljährliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Halbjährliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Jährliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Zweijährliche Bilanz"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Periodische Bilanz"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Tägliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Wöchentliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Zweiwöchentliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Monatliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Zweimonatliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Vierteljährliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Halbjährliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Jährliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Zweijährliche Bilanz mit Eigenkapital"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Periodische Bilanz mit Eigenkapital"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Tägliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Wöchentliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Zweiwöchentliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Monatliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Zweimonatliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Vierteljährliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Halbjährliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Jährliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Zweijährliche Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Periodische Kapitalflussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Kapitalflüsse"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Werte und Gewinne enthalten keine Bestände ohne Marktpreis: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Realisierter Gewinn"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Nicht realisierter Gewinn"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Realisierter Verlust"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Nicht realisierter Verlust"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Nettogewinn"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Anschaffungskosten"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Kein Marktpreis"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Wert"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Durchschn. Anschaffungskosten"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Anschaffungskosten je Einheit/Durchschn."++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Anschaffungskosten je Einheit"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Die Summen von Gesamtsumme, Unreal. Gew., Unreal. Gew. % und XIRR enthalten keine Bestände ohne Marktpreis: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Die Summen von Real. Gew. und XIRR enthalten {n} nicht angezeigte geschlossene Position"+msgstr[1] "Die Summen von Real. Gew. und XIRR enthalten {n} nicht angezeigte geschlossene Positionen"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, Gewinne je Periode"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, Gewinne seit {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Tägliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Wöchentliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Zweiwöchentliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Monatliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Zweimonatliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Vierteljährliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Halbjährliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Jährliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Zweijährliche Bestände"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Periodische Bestände"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Bestände"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Einheiten"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Preis einer Einheit"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Anschaffungskosten gesamt"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Gesamtsumme"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Unreal. Gew."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Unreal. Gew. %"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Real. Gew."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(keine Bestände)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Datum"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Bestände zum {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Bestände zum {date}, Gewinne in {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(siehe -E)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Alter"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Gewichtung"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Konto"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Gesamt:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Tägliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Wöchentliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Zweiwöchentliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Monatliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Zweimonatliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Vierteljährliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Halbjährliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Jährliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Zweijährliche Einnahmenüberschussrechnung"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Periodische Einnahmenüberschussrechnung"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Register"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Anzeigen:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Titel"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Diagramme"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Alles"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "Kontosalden"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "Kontobewegungen"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "Zahlungsmittelsalden"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "Bilanzsalden"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "GuV-Bewegungen"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Zahlungsmittelkonten"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Bilanzkonten"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "GuV-Konten"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Alle Konten"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Gesamt zum Transaktionspreis:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "Die Summe aller Konten, umgerechnet zum Transaktionspreis. Nicht null, wenn etwas unausgeglichen ist."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Gesamt zum Marktwert:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "Die Summe aller Konten zum Marktwert. Nicht null, wenn sich Werte geändert haben und keine Buchung den Gewinn oder Verlust erfasst, z. B. bei nicht realisierten Kursgewinnen."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "Die Summe aller Konten. Nicht null, wenn etwas unausgeglichen ist, z. B. bei Umrechnungen mit @ ohne --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Salden zum {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Der Saldo jedes Kontos am Ende dieses Tages: am Ende des Suchzeitraums, sonst am letzten Datum des Journals"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Journal"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Journalbuchungen anzeigen, neueste zuerst"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Bilanz"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Vermögen, Verbindlichkeiten und Reinvermögen anzeigen"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Einnahmenüberschussrechnung"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Einnahmen und Ausgaben anzeigen"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Kapitalflussrechnung"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Veränderungen der liquiden Mittel anzeigen"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Zeige Anlagebestände, Tranchen und Gewinne"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Zeige die Stände aller Konten unterteilt in Intervalle, wie beim balance-Befehl"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Buchungen {first} bis {last} von {total}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Seite {n} anzeigen"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Seite {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Nur {year} anzeigen"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Shift+Maustaste wählt einen Bereich von Jahren aus."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Intervall:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Eine Spalte für den ganzen Zeitraum anzeigen"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Keins"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Jährlich"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Eine Spalte pro Jahr anzeigen"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Vierteljährlich"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Eine Spalte pro Quartal anzeigen"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Monatlich"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Eine Spalte pro Monat anzeigen"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Wöchentlich"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Eine Spalte pro Woche anzeigen"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Täglich"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Eine Spalte pro Tag anzeigen"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Anzeigen, wie sich jeder Saldo in jeder Periode verändert hat"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Kumulierte Gesamtsumme"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Zeigt Änderungen bezogen auf den Beginn des Berichtszeitraums (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Endsalden"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Jeden Saldo am Ende jeder Periode anzeigen, einschließlich allem davor"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Berechnung:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Zeige Summen der Buchungszeilen"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Summen"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Wertänderung"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Zeige, wie sich die Marktwerte zum Periodenende verändert haben (--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Nicht realisierter Gewinn"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Zeige nicht realisierte Kursgewinne: Marktwert minus Anschaffungskosten (--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Zähle die Buchungszeilen, statt sie zu summieren (--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Konten:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Zeige Konten als flache Liste (--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Liste"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Zeige Konten als Baum (--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Baum"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Sortierung:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Nach Konto"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Sortiere die Zeilen in der Anzeigereihenfolge der Konten"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Nach Betrag"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Sortiere die Zeilen nach ihren Beträgen, größte zuerst (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Diagramm:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Divergierend"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Zeige die Beträge jeder Periode in einem Balken, über und unter null (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Gruppiert"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Zeige die Kontentypen jeder Periode in nebeneinander stehenden Balken (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Tiefe {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "unbegrenzt"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Wie verbucht"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Transaktionspreis"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Wert"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Prozentanteile"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Gruppiertes Diagramm"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Gesamt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Durchschnitt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Abgeleitete Preise"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Nullsummen ausgeblendet"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Nullsummen angezeigt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Tranchen angezeigt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Transaktionspreise angezeigt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Geschlossene Positionen angezeigt"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Geschlossene Positionen ausgeblendet"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Zweitdaten"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Eigenkapital angezeigt"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Konnte keine Prozentanteile berechnen:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Unbekannte Bezeichnung für Berichtsintervall:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Unbekannte Betragsumrechnung:"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Der Parameter {name} hat einen Wert, der nicht unterstützt wird:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Wertänderungen und Gewinne werden aus Marktwerten zum Periodenende berechnet: lassen Sie den Parameter value weg, oder verwenden Sie value=end."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Gewinne vergleichen den Marktwert mit den Anschaffungskosten und lassen sich daher nicht mit value=cost kombinieren."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Dieser Bericht gilt für ein einzelnes Datum, daher ist value=then nicht anwendbar: verwenden Sie value=end, value=now oder ein Datum."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Diesen Bericht für diese Periode anzeigen"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Buchung hinzugefügt."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, gefiltert"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "Salden - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Alle"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Shift+Maustaste wählt mehrere Typen aus."++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Shift+Maustaste wählt mehrere Einheiten oder Währungen"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Journal konnte nicht geladen werden: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Journal {file} gespeichert"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Journal bearbeiten"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "Bestände - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Zeige die Buchungen für dieses Konto"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Zeige die Buchungen für diesen Bestand"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Zeige die Bestände zu diesem Datum"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "anzeigen"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Gewinne:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "Je Periode"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Zeige die Gewinne in jeder Periode"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Seit Berichtsbeginn"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Zeige die Gewinne seit dem Beginn des Berichts bis zum Ende jeder Periode"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Seit Anschaffung"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Zeige die Gewinne seit der Anschaffung jedes Bestands bis zum Ende jeder Periode"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Hauptjournal"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Buchungen in {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Buchungen in {account} (ohne Unterkonten)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "Journal - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "alle Konten"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (ohne Unterkonten)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Gesamt (historisch)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Gesamt (Periode)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Zeige die laufende Summe beginnend vom Start dieses Zeitraums"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Zeige die laufende Summe unter Berücksichtigung aller Buchungen vor diesem Zeitraum"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "Buchungen - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "Symbol fehlt"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "Bilanz mit Eigenkapital - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "Bilanz - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "Einnahmenüberschussrechnung - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "Kapitalflussrechnung - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Alle Konten dieses Berichts haben den Saldo null und sind ausgeblendet. Drücken Sie z, um sie anzuzeigen."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Es wurden keine Konten der Typen gefunden, die dieser Bericht zeigt. Deklarieren Sie Kontotypen oder verwenden Sie die Standardnamen der obersten Kontoebene von hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Wie hledger Kontotypen erkennt"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "In diesem Zeitraum passt nichts zu dieser Suche."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Kodierungsfehler: '{error}'. Wenn Ihre Datei nicht UTF-8-kodiert ist, versuchen Sie das Bearbeitungsformular, wo der Browser die Umkodierung übernimmt."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Datei {file} erfolgreich hochgeladen"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Journal hochladen"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Schließen"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Buchung hinzufügen"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Konto {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Betrag {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Ungültiges Datumsformat"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Datum"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Beschreibung"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Betrag fehlt"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Konto fehlt"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Ungültiger Wert: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Prüfung der Buchungszeilen fehlgeschlagen"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Einheit oder Währung"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Diagramm ein-/ausblenden (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Diagramm"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Daten ein-/ausblenden (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Daten"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Zeige die Einstellungen für die Darstellung"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Einstellungen"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} in {dates}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} in {dates}, gefiltert"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Diese Einstellungen beziehen sich auf die Abrechnungen"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Preise:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Deklariert"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Bewerte Beträge nur mit deklarierten Marktpreisen (P-Direktiven)"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Auch abgeleitete"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Leite Marktpreise auch aus Transaktionspreisen ab (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Tiefe:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Zeige nur die Summe (Tiefe 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Zeige Konten ohne Tiefenbeschränkungen"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Zeige Konten bis zur Tiefe {depth}"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Beträge:"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Zeige Beträge in den Währungen, in denen sie verbucht sind"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Zum Transaktionspreis"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Zeige Mengen umgerechnet zum verbuchten Transaktionspreis (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "Zu Marktpreisen"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Zeige Mengen umgerechnet zu ihren Marktpreisen jeweils zum Ende jedes Intervalls (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Nullsummen:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Blende Konten aus, deren Stände null sind"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Ausgeblendet"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Zeige auch Konten, deren Stände null sind"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Angezeigt"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Vermögen:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Zeige Vermögen, Verbindlichkeiten und Reinvermögen, wie der Befehl balancesheet"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Zeige Vermögen, Verbindlichkeiten und Eigenkapital, wie der Befehl balancesheetequity"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Status:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Zeige Buchungen mit jedem Status"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Alle"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Unmarkiert"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Zeige nur unmarkierte Buchungen (status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Ausstehend"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Zeige nur ausstehende Buchungen (status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Beglichen"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Zeige nur beglichene Buchungen (status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Buchungszeilen:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Zeige reale und virtuelle Buchungszeilen"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Alle"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Real"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Zeige nur reale Buchungszeilen, wie -R (real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Virtuell"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Zeige nur virtuelle Buchungszeilen, die eingeklammerten (real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Zusatzspalten:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Füge eine Spalte mit der Summe jeder Zeile hinzu (-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Füge eine Spalte mit dem Durchschnitt jeder Zeile hinzu (-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Zahlen:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Zeige die Beträge"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Beträge"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Zeige jeden Betrag als Prozentanteil an der Summe seiner Spalte (-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Transaktionspreise:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Zeige Beträge ohne ihre Transaktionspreise"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Ausgeblendet"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Zeige Beträge mit den im Journal verbuchten Transaktionspreisen"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Angezeigt"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Tranchen:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Fasse die Tranchen jedes Kontos zusammen"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Ausgeblendet"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Zeige jede Tranche einzeln (--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Angezeigt"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Geschlossene Positionen:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Zeige nur offene Positionen"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Ausgeblendet"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Zeige auch vollständig veräußerte Positionen und ihre realisierten Gewinne (-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Angezeigt"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Werte:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "In Anschaffungswährung"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Bewerte jeden Bestand in seiner eigenen Anschaffungswährung"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Rechne Werte und Anschaffungskosten in die Bewertungswährung um (-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Typ:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Zeige Konten aller Typen"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Alle"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Vermögen"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Zeige nur Vermögenskonten (type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Verbindlichkeiten"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Zeige nur Verbindlichkeitskonten (type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Zeige nur Eigenkapitalkonten (type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Einnahmen"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Zeige nur Einnahmenkonten (type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Ausgaben"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Zeige nur Ausgabenkonten (type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Zahlungsmittel"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Zeige nur Zahlungsmittelkonten (type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Umrechnung"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Zeige nur Umrechnungskonten (type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Kursgewinne"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Zeige nur Konten für Kursgewinne (type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Differenzen"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Zeige nur Differenzkonten (type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Alle Einheiten und Währungen auflisten"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Einheit oder Währung:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Zeige Beträge in allen Einheiten und Währungen"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Alle"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Zeige nur Beträge in {commodity}"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… und {n} weitere"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Datum wählen"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Hinzufügen zu:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Speichern"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Konten um eine Ebene weiter einklappen"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Konten um eine Ebene weiter aufklappen"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Salden ein-/ausblenden"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Salden"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Buchungen dieses Kontos und seiner Unterkonten anzeigen"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Buchungen dieses Kontos ohne Unterkonten anzeigen"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "nur"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Zeige die Buchungen hinter diesem Saldo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Zeige die Buchungen hinter dieser Summe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Seitenleiste ein-/ausblenden (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web läuft nicht mehr. Es beendet sich nach fünfzehn Minuten ohne ein Browserfenster, das es anzeigt, oder wenn es angehalten wird. Zum Weiterarbeiten starten Sie es neu und laden diese Seite erneut."++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Verlasse Vollbildmodus"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Suchen"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "hledger-Suchmuster eingeben, um die Daten unten zu filtern"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Suchbegriffe löschen"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Suchbegriffe anwenden"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Journaldateien verwalten"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Such- und allgemeine Hilfe anzeigen"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Gehe zu"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Hilfe"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Tastenkürzel"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "oder"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "zeige diese Hilfeseite"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "wechsle den Bildschirm"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "zum nächsten oder vorigen Bildschirm wechseln"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "eine Buchung hinzufügen"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "Seitenleiste ein-/ausblenden"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "Kontentiefe der Seitenleiste festlegen"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "Salden der Seitenleiste ein-/ausblenden"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "Berichteinstellungen ein-/ausblenden"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "Diagramme ein-/ausblenden"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "Wähle die Einheit oder Währung für das Diagramm"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "Linie des Überschusses im Diagramm ein-/ausblenden"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "Rechnungsdaten ein-/ausblenden"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "Vollbildmodus ein-/ausschalten"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "zum Suchfeld springen"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "Suche löschen"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "abbrechen"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Berichteinstellungen"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "historische Endsalden / Saldoänderungen"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "jährlich"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "vierteljährlich"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "monatlich"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "wöchentlich"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "täglich"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "unmarkiert"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "ausstehend"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "beglichen"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "nur reale / alle"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Tiefenbeschränkung:"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "festlegen"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "erhöhen oder verringern"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "Baum / Liste"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "zum Transaktionspreis"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "zum Marktpreis"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "zeige oder verberge Nullsummen"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "zeige oder verberge Tranchendetails"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "Gesamt"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "Durchschnitt"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "Sortiere nach Beträgen oder Kontennamen"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Wenn man eine Taste erneut drückt, wird die Einstellung zurückgenommen."++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Suchanfragen"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Suchmuster mit Leerzeichen in Anführungszeichen setzen."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "Kontonamen finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "Kontentypen eingrenzen (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "Daten finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "Status finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "Buchungscodes finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "Buchungsbeschreibungen finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "den Empfängerteil der Beschreibung finden"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "den Notizteil der Beschreibung finden"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "Beträge ohne Vorzeichen finden, oder mit vorzeichenbehaftetem N vorzeichenbehaftete Beträge. N kann ein Währungssymbol haben."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "Berichtszeilen (Konten, Perioden, Buchungen) nach ihrer Änderung oder ihrem Saldo finden, wie amt:. N kann ein Währungssymbol haben."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "Währungen finden. Muss das ganze Symbol treffen. Für das Dollarzeichen schreibe"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "Tags finden, oder Tag und Wert"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "reale/virtuelle Buchungszeilen finden"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "jedes Feld finden (Konto, Betrag, Kommentar, Tag, Beschreibung, Code), oder ein Datum, wenn REGEX auch ein Periodenausdruck ist"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "not: voranstellen, um einen Suchbegriff zu verneinen"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "mit einem booleschen Ausdruck suchen (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "Buchungen finden, bei denen eine Buchungszeile passt"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "Buchungen finden, bei denen alle Buchungszeilen passen"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "Alternative, um die Tiefe zu begrenzen (kann auf Konto bezogen werden)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Mehr Hilfe:"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "hledger-web Handbuch"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Datei bearbeiten"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Sind Sie sicher? Dies überschreibt Ihr Journal!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Hilfe zum Dateiformat"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Zurück"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Eine neue Buchung zum Journal hinzufügen"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Datum"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Beschreibung"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Konto"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Betrag"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Die Journalbuchungen dieses Tages anzeigen"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Die Dateien Ihres Journals"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Datei"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Bearbeiten"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Hochladen"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Herunterladen"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Die neueren Buchungen anzeigen"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Neuere"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Die älteren Buchungen anzeigen"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Ältere"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Von/Nach Konto"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Betrag Aus/Ein"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Diese und die anderen Journalbuchungen dieses Tages anzeigen"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Saldovortrag"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Die Buchungen vor diesem Zeitraum anzeigen"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Hochladen in Datei"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Datei auswählen"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Jahre:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Alle Jahre anzeigen"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Alle"++# Alternativen: Abschluss, Rechnung+#~ msgid "Next report"+#~ msgstr "Nächster Bericht"++#~ msgid "Go to the next report"+#~ msgstr "Wechsle zum nächsten Bericht"++#~ msgid "Previous report"+#~ msgstr "Voriger Bericht"++#~ msgid "Go to the previous report"+#~ msgstr "Wechsle zum vorigen Bericht"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "Überschuss, zum Transaktionspreis:"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "Die Summe aller Konten, zum Transaktionspreis: null bei ausgeglichenen Büchern; ein Rest stammt aus unausgeglichenen virtuellen Buchungszeilen."++#~ msgid "Unbooked gains:"+#~ msgstr "Nicht verbuchte Gewinne:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "Die Summe aller Konten zum Marktpreis: Wertzuwachs, den keine Buchung erfasst. Wenn realisierte Gewinne verbucht sind, sind dies die nicht realisierten Gewinne."++#~ msgid "Net flows:"+#~ msgstr "Nettozuflüsse:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "Die Summe aller Konten: offene Positionen in jeder Einheit und die Zahlungsmittel, mit denen sie bezahlt wurden. Null, wenn keine Buchung mehrere Einheiten verbindet."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Bestände zu den Periodenenden"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Bestände zu den Periodenenden, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Unbekannter Kumulierungsmodus:"++#~ msgid "Show only the total"+#~ msgstr "Zeige nur die Gesamtsumme"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Die Buchungen anzeigen, aus denen sich dieser Saldo zusammensetzt"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Die Buchungen anzeigen, aus denen sich diese Summe zusammensetzt"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "ein beliebiges sichtbares Feld finden (Konto, Betrag, Kommentar, Beschreibung, Code), oder ein Datum, wenn REGEX auch ein Periodenausdruck ist"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "Beträge nach Größe finden, mit vorzeichenbehaftetem N nach Vorzeichen. Nur für Beträge mit einer Währung."++#~ msgid "Balance sheet with equity"+#~ msgstr "Bilanz mit Eigenkapital"++#~ msgid "Show assets, liabilities, and equity"+#~ msgstr "Vermögen, Verbindlichkeiten und Eigenkapital anzeigen"++#~ msgid "Show the running balance from the start of this period"+#~ msgstr "Den laufenden Saldo ab Beginn dieses Zeitraums anzeigen"++#~ msgid "Show the running balance including everything before this period"+#~ msgstr "Den laufenden Saldo einschließlich allem vor diesem Zeitraum anzeigen"++#~ msgid "hide empty accounts"+#~ msgstr "leere Konten ausblenden"++#~ msgid "General"+#~ msgstr "Allgemein"++#~ msgid "The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts"+#~ msgstr "Die Journalansicht zeigt Journalbuchungen: ausgeglichene Bewegungen von Geld (oder anderen Werten) zwischen hierarchischen Konten"++#~ msgid "The sidebar shows the resulting accounts and their final balances"+#~ msgstr "Die Seitenleiste zeigt die Konten und ihre Endsalden"++#~ msgid "The sidebar's report links show the balance sheet, income statement, and cashflow statement, each linking to the other reports"+#~ msgstr "Die Berichtslinks der Seitenleiste zeigen Bilanz, Einnahmenüberschussrechnung und Kapitalflussrechnung, jeweils mit Links zu den anderen Berichten"++#~ msgid "Parent account balances include subaccount balances"+#~ msgstr "Salden übergeordneter Konten schließen die Unterkonten ein"++#~ msgid "Multiple currencies in balances are displayed one above the other"+#~ msgstr "Mehrere Währungen in Salden werden untereinander angezeigt"++#~ msgid "Click account name links to see transactions affecting that account, with running balance"+#~ msgstr "Kontonamen anklicken, um die Buchungen dieses Kontos mit laufendem Saldo zu sehen"++#~ msgid "Click an amount to see the transactions it is made of, in a register ending on that amount"+#~ msgstr "Einen Betrag anklicken, um die Buchungen zu sehen, aus denen er besteht, in einem Register, das mit diesem Betrag endet"++#~ msgid "Click date links to see journal entries on that date"+#~ msgstr "Datumslinks anklicken, um die Journalbuchungen dieses Tages zu sehen"++#~ msgid "The balance sheet and income statement show liabilities, equity, and revenues as positive amounts; their registers show them negative, as hledger does"+#~ msgstr "Bilanz und Einnahmenüberschussrechnung zeigen Verbindlichkeiten, Eigenkapital und Einnahmen als positive Beträge; ihre Register zeigen sie negativ, wie hledger es tut"++#~ msgctxt "help heading"+#~ msgid "Search"+#~ msgstr "Suche"++#~ msgid "match account types"+#~ msgstr "Kontotypen finden"++#~ msgid "clip account names at this depth"+#~ msgstr "Kontonamen auf diese Tiefe kürzen"++#~ msgid "Could not parse the period expression:"+#~ msgstr "Der Periodenausdruck konnte nicht gelesen werden:"++#~ msgid "Report:"+#~ msgstr "Bericht:"++#~ msgid "add a transaction (escape to cancel)"+#~ msgstr "eine Buchung hinzufügen (Escape zum Abbrechen)"++#~ msgid "go to the Journal view (home)"+#~ msgstr "zur Journalansicht (Startseite)"++#~ msgid "or maybe"+#~ msgstr "oder"++#~ msgid "view this help (escape or click to exit)"+#~ msgstr "diese Hilfe anzeigen (Escape oder Klick zum Schließen)"++#~ msgid "Balance report"+#~ msgstr "Saldenbericht"++#~ msgid "Show the balance report: any accounts, by period"+#~ msgstr "Den Saldenbericht anzeigen: beliebige Konten, nach Perioden"
+ locale/es.po view
@@ -0,0 +1,3133 @@+# Spanish translations for hledger.+# This file is distributed under the same license as hledger.+# Neutral Spanish, for Spain and Latin America; see hledger-lib/locale/README.md.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: es\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n != 1);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Enero"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Febrero"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Marzo"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Abril"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Mayo"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Junio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Julio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Agosto"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Septiembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Octubre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Noviembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Diciembre"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Ene"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Feb"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mar"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Abr"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "May"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Jun"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Jul"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Ago"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Sep"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Oct"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Nov"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Dic"++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Detalles del informe"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Total"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Activos"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Pasivos"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Patrimonio"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Ingresos"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Gastos"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Otras"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Saldo"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Total"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Neto:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…y {n} más"+msgstr[1] "…y {n} más"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "otras {parent} ({n} cuenta)"+msgstr[1] "otras {parent} ({n} cuentas)"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "otras ({n} cuenta)"+msgstr[1] "otras ({n} cuentas)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Cambios de valor al cierre de período)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Cambios de valor acumulados al cierre de período)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Ganancia incremental)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Ganancia acumulada)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Ganancia histórica)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Cambios de saldo)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Saldos finales acumulados)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Saldos finales históricos)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", con conversión a costo"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", con valoración a la fecha de cada movimiento"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", con valoración al cierre de cada período"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", a valor actual"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", con valoración al {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Informe de presupuesto"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Informe de saldos por períodos"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Informe de saldos"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} en {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Cambios de valor al cierre de período"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Cambios de valor acumulados al cierre de período"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Ganancia incremental"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Ganancia acumulada"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Ganancia histórica"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Número de movimientos"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Número acumulado de movimientos"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Número histórico de movimientos"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Número de transacciones"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Cambios de saldo"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Saldos finales (acumulados)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Saldos finales (históricos)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Ejecución del presupuesto en {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Unidad"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Promedio"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Balance general"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Balance general diario"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Balance general semanal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Balance general quincenal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Balance general mensual"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Balance general bimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Balance general trimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Balance general semestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Balance general anual"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Balance general bienal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Balance general periódico"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Balance general con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Balance general diario con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Balance general semanal con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Balance general quincenal con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Balance general mensual con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Balance general bimestral con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Balance general trimestral con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Balance general semestral con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Balance general anual con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Balance general bienal con patrimonio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Balance general periódico con patrimonio"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Estado de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Estado diario de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Estado semanal de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Estado quincenal de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Estado mensual de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Estado bimestral de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Estado trimestral de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Estado semestral de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Estado anual de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Estado bienal de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Estado periódico de flujos de efectivo"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Flujos de efectivo"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Los valores y las ganancias excluyen las posiciones sin precio de mercado: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Ganancia realizada"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Ganancia no realizada"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Pérdida realizada"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Pérdida no realizada"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Ganancia neta"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Costo"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Sin precio de mercado"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Valor"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Costo promedio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Costo unitario/promedio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Costo unitario"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Los totales de Valor total, Gan. NR, Gan. NR % y TIR excluyen las posiciones sin precio de mercado: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Los totales de Gan. R y TIR incluyen {n} posición cerrada, que no se muestra"+msgstr[1] "Los totales de Gan. R y TIR incluyen {n} posiciones cerradas, que no se muestran"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, ganancias de cada período"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, ganancias desde {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Posiciones diarias"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Posiciones semanales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Posiciones quincenales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Posiciones mensuales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Posiciones bimestrales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Posiciones trimestrales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Posiciones semestrales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Posiciones anuales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Posiciones bienales"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Posiciones periódicas"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Posiciones"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Unidades"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Precio unitario"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Costo total"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Valor total"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Gan. NR"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Gan. NR %"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Gan. R"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "TIR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(sin posiciones)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Fecha"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Posiciones al {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Posiciones al {date}, ganancias en {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(véase -E)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Antigüedad"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Peso"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Cuenta"++# machine-translated, please review+#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Total:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Estado de resultados"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Estado de resultados diario"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Estado de resultados semanal"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Estado de resultados quincenal"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Estado de resultados mensual"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Estado de resultados bimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Estado de resultados trimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Estado de resultados semestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Estado de resultados anual"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Estado de resultados bienal"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Estado de resultados periódico"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Registro"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Mostrar:"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Títulos"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Gráficos"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Todo"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "saldos de cuentas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "cambios en cuentas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "saldos de efectivo"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "saldos del balance"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "cambios en resultados"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Cuentas de efectivo"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Cuentas de balance"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Cuentas de resultados"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Todas las cuentas"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Total al costo:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "La suma de todas las cuentas, convertida al costo. No es cero cuando algo no está balanceado."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Total a valor de mercado:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "La suma de todas las cuentas a valor de mercado. No es cero cuando los valores han cambiado y ningún asiento registra la ganancia o la pérdida, p. ej., las ganancias de inversión no realizadas."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "La suma de todas las cuentas. No es cero cuando algo no está balanceado, p. ej., las conversiones con @ sin --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Saldos al {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "El saldo de cada cuenta al final de este día: el final de las fechas de la búsqueda, o si no, la última fecha del diario"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Libro diario"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Mostrar los asientos del libro diario, los más recientes primero"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Balance general"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Mostrar activos, pasivos y patrimonio neto"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Estado de resultados"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Mostrar ingresos y gastos"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Estado de flujos de efectivo"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Mostrar los cambios en los activos líquidos"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Mostrar las posiciones de inversión, los lotes y las ganancias"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Mostrar los saldos de todas las cuentas, por período, como el comando balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Mostrando {first} a {last} de {total} transacciones"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Mostrar la página {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Página {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Mostrar solo {year}"++# machine-translated, please review+#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Mayús+clic selecciona un rango de años."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Intervalo:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Mostrar una columna para todo el período"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Ninguno"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Anual"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Mostrar una columna por año"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Trimestral"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Mostrar una columna por trimestre"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Mensual"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Mostrar una columna por mes"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Semanal"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Mostrar una columna por semana"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Diario"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Mostrar una columna por día"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Mostrar cuánto cambió cada saldo en cada período"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Totales acumulados"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Mostrar el cambio de cada saldo desde el inicio del informe (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Saldos finales"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Mostrar cada saldo al final de cada período, incluyendo todo lo anterior"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Calcular:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Mostrar las sumas de los movimientos"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Sumas"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Cambio de valor"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Mostrar cómo cambiaron los valores de mercado al cierre de cada período (--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Ganancia no realizada"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Mostrar las ganancias de capital no realizadas: valor de mercado menos costo (--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Contar los movimientos en lugar de sumarlos (--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Cuentas:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Mostrar las cuentas como una lista plana (--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Lista"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Mostrar las cuentas como un árbol (--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Árbol"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Orden:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Por cuenta"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Ordenar las filas según el orden de presentación de las cuentas"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Por importe"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Ordenar las filas por sus importes, los mayores primero (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Gráfico:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Divergente"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Mostrar los importes de cada período en una sola barra, por encima y por debajo de cero (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Agrupado"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Mostrar los tipos de cuenta de cada período en barras lado a lado (--chart=grouped)"++# machine-translated, please review+#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Profundidad {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "sin límite"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Como se registraron"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Al costo"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "A valor"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Porcentajes"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Gráfico agrupado"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Total"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Promedio"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Precios inferidos"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Saldos en cero ocultos"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Saldos en cero mostrados"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Lotes mostrados"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Costos mostrados"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Posiciones cerradas mostradas"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Posiciones cerradas ocultas"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Fechas secundarias"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Patrimonio mostrado"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "No se pudieron calcular los porcentajes:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "No se pudo interpretar el intervalo del informe:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Conversión de importes desconocida:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "El parámetro {name} tiene un valor que esta página no reconoce:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Los cambios de valor y las ganancias se calculan con los valores de mercado al cierre de cada período: omita el parámetro value, o use value=end."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Las ganancias comparan el valor de mercado con el costo, por lo que no se combinan con value=cost."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Este informe es a una sola fecha, por lo que value=then no se aplica: use value=end, value=now o una fecha."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Mostrar este informe para este período"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Transacción añadida."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, con filtro"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "saldos - hledger-web"++# machine-translated, please review+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Todas"++# machine-translated, please review+#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Mayús+clic selecciona varios tipos."++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Mayús+clic selecciona varias unidades."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "No se pudo cargar el diario: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Diario {file} guardado"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Editar el diario"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "posiciones - hledger-web"++# machine-translated, please review+#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Mostrar el registro de esta cuenta"++# machine-translated, please review+#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Mostrar el registro de esta posición"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Mostrar las posiciones en esta fecha"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "mostrarlas"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Ganancias:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "En cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Mostrar las ganancias durante cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Desde el inicio del informe"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Mostrar las ganancias desde la fecha de inicio del informe hasta el final de cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Desde la adquisición"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Mostrar las ganancias desde la adquisición de cada posición hasta el final de cada período"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Libro diario"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Transacciones en {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Transacciones en {account} (sin subcuentas)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "libro diario - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "todas las cuentas"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (sin subcuentas)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Total histórico"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Total del período"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Clic para mostrar el saldo acumulado desde el inicio de este período"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Clic para mostrar el saldo acumulado incluyendo todo lo anterior a este período"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "registro - hledger-web"++# machine-translated, please review+#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "sin símbolo"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "balance general con patrimonio - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "balance general - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "estado de resultados - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "estado de flujos de efectivo - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Todas las cuentas de este informe tienen saldo cero, y están ocultas. Presione z para mostrarlas."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "No se encontraron cuentas de los tipos que muestra este informe. Declare los tipos de cuenta, o use los nombres de cuenta de nivel superior estándar de hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Cómo determina hledger los tipos de cuenta"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "Nada coincide con esta búsqueda en este período."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Error de codificación: '{error}'. Si su archivo no está codificado en UTF-8, pruebe el 'formulario de edición', donde el navegador debería encargarse de la conversión."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Archivo {file} subido correctamente"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Subir el diario"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Cerrar"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Añadir una transacción"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Cuenta {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Importe {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Formato de fecha no válido"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Fecha"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Descripción"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Falta el importe"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Falta la cuenta"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Valor no válido: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "La validación de los movimientos falló"++# machine-translated, please review+#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Unidad"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Mostrar u ocultar el gráfico (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Gráfico"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Mostrar u ocultar los datos (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Datos"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Mostrar las opciones que modifican esta vista"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Opciones"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} en {dates}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} en {dates}, con filtro"++# machine-translated, please review+#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Estos controles se aplican en las páginas de informes"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Precios:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Declarados"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Valorar los importes solo con los precios de mercado declarados (directivas P)"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "También inferidos"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Inferir precios de mercado también a partir de los costos de las transacciones (--infer-market-prices)"++# machine-translated, please review+#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Profundidad:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Mostrar solo el total (profundidad 0)"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Mostrar las cuentas de todas las profundidades"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Mostrar las cuentas hasta la profundidad {depth}"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Importes:"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Mostrar los importes en las unidades en que se registraron"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Al costo"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Mostrar los importes convertidos a su costo, según se registró en las transacciones (-B)"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "A valor de mercado"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Mostrar los importes convertidos a su valor de mercado al cierre de cada período, usando los precios de mercado (-V)"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Saldos en cero:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Ocultar las cuentas cuyo saldo es cero"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Ocultos"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Mostrar las cuentas cuyo saldo es cero"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Mostrados"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Patrimonio:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Mostrar activos, pasivos y patrimonio neto, como el comando balancesheet"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Mostrar activos, pasivos y patrimonio, como el comando balancesheetequity"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Estado:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Mostrar las transacciones de cualquier estado"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Todas"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Sin marcar"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Mostrar solo las transacciones sin marcar (status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Pendientes"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Mostrar solo las transacciones pendientes (status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Conciliadas"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Mostrar solo las transacciones conciliadas (status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Movimientos:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Mostrar los movimientos reales y virtuales"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Todos"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Reales"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Mostrar solo los movimientos reales, como -R (real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Virtuales"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Mostrar solo los movimientos virtuales, los que van entre paréntesis (real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Columnas adicionales:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Añadir una columna con el total de cada fila (-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Añadir una columna con el promedio de cada fila (-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Cifras:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Mostrar los importes"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Importes"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Mostrar cada importe como porcentaje del total de su columna (-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Costos:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Mostrar los importes sin sus costos"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Ocultos"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Mostrar los importes con los costos registrados en el diario"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Mostrados"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Lotes:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Agrupar los lotes de cada cuenta"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Ocultos"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Mostrar cada lote por separado (--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Mostrados"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Posiciones cerradas:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Mostrar solo las posiciones abiertas"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Ocultas"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Mostrar también las posiciones totalmente liquidadas y sus ganancias realizadas (-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Mostradas"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Valores:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "Por unidad del costo"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Valorar cada posición en la unidad de su propio costo"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Convertir los valores y costos a la unidad de valoración de mercado (-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Tipo:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Mostrar las cuentas de todos los tipos"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Todos"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Activo"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Mostrar solo las cuentas de activo (type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Pasivo"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Mostrar solo las cuentas de pasivo (type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Mostrar solo las cuentas de patrimonio (type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Ingreso"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Mostrar solo las cuentas de ingresos (type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Gasto"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Mostrar solo las cuentas de gastos (type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Efectivo"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Mostrar solo las cuentas de efectivo (type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Conversión"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Mostrar solo las cuentas de conversión (type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Ganancia"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Mostrar solo las cuentas de ganancias de capital (type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Descuadre"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Mostrar solo las cuentas de descuadre (type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Listar todas las unidades"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Unidad:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Mostrar los importes en todas las unidades"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Todas"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Mostrar solo los importes en {commodity}"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… y {n} más"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Elegir una fecha"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Añadir a:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Guardar"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Contraer las cuentas un nivel más"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Expandir las cuentas un nivel más"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Mostrar u ocultar los saldos"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Saldos"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Mostrar las transacciones que afectan a esta cuenta y sus subcuentas"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Mostrar las transacciones que afectan a esta cuenta, sin sus subcuentasMostrar las transacciones que afectan a esta cuenta, sin sus subcuentas"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "solo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Mostrar las transacciones que forman este saldo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Mostrar las transacciones que forman este total"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Mostrar u ocultar la barra lateral (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web ya no se está ejecutando. Se cierra tras quince minutos sin ninguna ventana del navegador que lo muestre, o al detenerlo. Para continuar, inícielo de nuevo y recargue esta página."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Salir de la ventana completa"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Buscar"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Escriba patrones de búsqueda de hledger para filtrar los datos de abajoIntroduzca patrones de búsqueda de hledger para filtrar los datos de abajo"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Borrar los términos de búsqueda"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Aplicar los términos de búsqueda"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Gestionar los archivos del diario"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Mostrar la ayuda general y de búsqueda"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Ir a"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Ayuda"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Atajos de teclado"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "o"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "ver esta ayuda"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "ir a cualquier pantalla"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "ir a la pantalla siguiente o anterior"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "añadir una transacción"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "mostrar u ocultar la barra lateral"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "fijar la profundidad de las cuentas de la barra lateral"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "mostrar u ocultar los saldos de la barra lateral"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "mostrar u ocultar las opciones del informe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "mostrar u ocultar el gráfico del informe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "elegir la unidad del gráfico"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "mostrar u ocultar la línea del total neto del gráfico"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "mostrar u ocultar los datos del informe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "activar o desactivar la ventana completa"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "ir al formulario de búsqueda"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "borrar la búsqueda"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "cancelar"++# machine-translated, please review+#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Opciones del informe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "saldos finales históricos / cambios de saldo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "anual"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "trimestral"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "mensual"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "semanal"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "diario"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "sin marcar"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "pendientes"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "conciliadas"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "solo reales / todos"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Límite de profundidad:"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "fijarlo"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "reducirlo o aumentarlo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "árbol / lista"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "al costo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "a valor de mercado"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "mostrar u ocultar los saldos en cero"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "mostrar u ocultar el detalle de los lotes"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "total"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "promedio"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "por importe / por orden de presentación de las cuentas"++# machine-translated, please review+#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Al pulsarla de nuevo, la tecla de una opción la desactiva."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Consultas de búsqueda"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Los patrones de búsqueda con espacios deben ir entre comillas."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "buscar por nombre de cuenta"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "buscar por tipo de cuenta (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "buscar por fecha"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "buscar por estado"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "buscar por código de transacción"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "buscar por descripción de transacción"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "buscar por la parte de beneficiario de la descripción"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "buscar por la parte de nota de la descripción"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "buscar por magnitud sin signo, o, con un N con signo, por importe con signo. N puede llevar un símbolo de unidad."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "buscar filas del informe (cuentas, períodos, transacciones) por su cambio o su saldo, como amt:. N puede llevar un símbolo de unidad."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "buscar por moneda o unidad. Debe coincidir con todo el símbolo o nombre. Para buscar el signo de dólar, escriba"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "buscar por etiqueta, o por etiqueta y valor"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "buscar movimientos reales o virtuales"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "buscar en cualquier campo (cuenta, importe, comentario, etiqueta, descripción, código), o por fecha si REGEX también es una expresión de período"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "anteponer not: para negar un término de búsqueda"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "buscar con una consulta booleana (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "buscar transacciones en las que coincida algún movimiento"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "buscar transacciones en las que coincidan todos los movimientos"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "otra forma de fijar el límite de profundidad (puede ser por cuenta)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Más ayuda:"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "manual de usuario de hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Editar el archivo"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "¿Está seguro? ¡Esto sobrescribirá su diario!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Ayuda sobre el formato de archivo"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Volver"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Añadir una nueva transacción al diario"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Fecha"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Descripción"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Cuenta"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Importe"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Mostrar los asientos de esta fecha"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Archivos de su diario"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Archivo"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Editar"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Subir"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Descargar"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Mostrar las transacciones más recientes"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Más recientes"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Mostrar las transacciones más antiguas"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Más antiguas"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Cuenta(s) de origen/destino"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Importe salida/entrada"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Mostrar este asiento y los demás asientos de su fecha"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Saldo anterior"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Mostrar las transacciones anteriores a este período"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Subir al archivo"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Seleccionar archivo"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Años:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Mostrar todos los años"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Todos"++# machine-translated, please review+#~ msgid "Next report"+#~ msgstr "Informe siguiente"++# machine-translated, please review+#~ msgid "Go to the next report"+#~ msgstr "Ir al informe siguiente"++# machine-translated, please review+#~ msgid "Previous report"+#~ msgstr "Informe anterior"++# machine-translated, please review+#~ msgid "Go to the previous report"+#~ msgstr "Ir al informe anterior"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "Neto, al costo:"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "La suma de todas las cuentas, convertida al costo: cero si los libros cuadran; cualquier resto proviene de movimientos virtuales no balanceados."++# machine-translated, please review+#~ msgid "Unbooked gains:"+#~ msgstr "Ganancias no contabilizadas:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "La suma de todas las cuentas a valor de mercado: la apreciación no contabilizada en ningún asiento. Si las ganancias realizadas están contabilizadas, son las ganancias no realizadas."++# machine-translated, please review+#~ msgid "Net flows:"+#~ msgstr "Flujos netos:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "La suma de todas las cuentas: las posiciones abiertas en cada unidad y el efectivo con que se pagaron. Cero cuando nada cruza entre unidades."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Posiciones al cierre de cada período"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Posiciones al cierre de cada período, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Modo de acumulación de saldos desconocido:"++# machine-translated, please review+#~ msgid "Show only the total"+#~ msgstr "Mostrar solo el total"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Mostrar las transacciones que componen este saldo"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Mostrar las transacciones que componen este total"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "buscar en cualquier campo visible (cuenta, importe, comentario, descripción, código), o una fecha si REGEX también es una expresión de período"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "buscar por magnitud sin signo o, con un N con signo, por importe con signo. Solo para importes de una única unidad."++#~ msgid "Balance sheet with equity"+#~ msgstr "Balance general con patrimonio"++#~ msgid "Show assets, liabilities, and equity"+#~ msgstr "Mostrar activos, pasivos y patrimonio"++#~ msgid "Show the running balance from the start of this period"+#~ msgstr "Mostrar el saldo acumulado desde el inicio de este período"++#~ msgid "Show the running balance including everything before this period"+#~ msgstr "Mostrar el saldo acumulado incluyendo todo lo anterior a este período"++#~ msgid "hide empty accounts"+#~ msgstr "ocultar las cuentas vacías"++#~ msgid "General"+#~ msgstr "General"++#~ msgid "The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts"+#~ msgstr "La vista Libro diario muestra los asientos del libro diario, que representan movimientos de suma cero de dinero (u otra unidad) entre cuentas jerárquicas"++#~ msgid "The sidebar shows the resulting accounts and their final balances"+#~ msgstr "La barra lateral muestra las cuentas resultantes y sus saldos finales"++#~ msgid "The sidebar's report links show the balance sheet, income statement, and cashflow statement, each linking to the other reports"+#~ msgstr "Los enlaces de informes de la barra lateral muestran el balance general, el estado de resultados y el estado de flujos de efectivo, cada uno con enlaces a los demás informes"++#~ msgid "Parent account balances include subaccount balances"+#~ msgstr "Los saldos de las cuentas padre incluyen los de sus subcuentas"++#~ msgid "Multiple currencies in balances are displayed one above the other"+#~ msgstr "Las distintas monedas de un saldo se muestran una encima de otra"++#~ msgid "Click account name links to see transactions affecting that account, with running balance"+#~ msgstr "Haga clic en el nombre de una cuenta para ver las transacciones que la afectan, con saldo acumulado"++#~ msgid "Click an amount to see the transactions it is made of, in a register ending on that amount"+#~ msgstr "Haga clic en un importe para ver las transacciones que lo componen, en un registro que termina en ese importe"++#~ msgid "Click date links to see journal entries on that date"+#~ msgstr "Haga clic en una fecha para ver los asientos de ese día"++#~ msgid "The balance sheet and income statement show liabilities, equity, and revenues as positive amounts; their registers show them negative, as hledger does"+#~ msgstr "El balance general y el estado de resultados muestran los pasivos, el patrimonio y los ingresos como importes positivos; sus registros los muestran negativos, como hace hledger"++#~ msgctxt "help heading"+#~ msgid "Search"+#~ msgstr "Búsqueda"++#~ msgid "match account types"+#~ msgstr "buscar por tipo de cuenta"++#~ msgid "clip account names at this depth"+#~ msgstr "recortar los nombres de cuenta a esta profundidad"++#~ msgid "Could not parse the period expression:"+#~ msgstr "No se pudo interpretar la expresión de período:"++#~ msgid "Report:"+#~ msgstr "Informe:"++#~ msgid "add a transaction (escape to cancel)"+#~ msgstr "añadir una transacción (Escape para cancelar)"++#~ msgid "go to the Journal view (home)"+#~ msgstr "ir a la vista Libro diario (inicio)"++#~ msgid "or maybe"+#~ msgstr "o quizás"++#~ msgid "view this help (escape or click to exit)"+#~ msgstr "ver esta ayuda (Escape o clic para salir)"++#~ msgid "Balance report"+#~ msgstr "Informe de saldos"++#~ msgid "Show the balance report: any accounts, by period"+#~ msgstr "Mostrar el informe de saldos: cualquier cuenta, por período"
+ locale/fr.po view
@@ -0,0 +1,2833 @@+# French translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, French.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: fr\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n > 1);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Janvier"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Février"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Mars"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Avril"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Mai"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Juin"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Juillet"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Août"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Septembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Octobre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Novembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Décembre"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Janv."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Févr."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mars"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Avr."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Mai"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Juin"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Juil."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Août"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Sept."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Oct."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Nov."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Déc."++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Détails du rapport"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Total"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Actifs"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Passifs"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Capitaux propres"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Revenus"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Dépenses"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Autres"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Solde"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Total"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Net :"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…et {n} de plus"+msgstr[1] "…et {n} de plus"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "autres {parent} ({n} compte)"+msgstr[1] "autres {parent} ({n} comptes)"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "autres ({n} compte)"+msgstr[1] "autres ({n} comptes)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(variations de valeur en fin de période)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(variations cumulées de valeur en fin de période)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(plus-value de la période)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(plus-value cumulée)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(plus-value historique)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(variations de solde)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(soldes de clôture cumulés)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(soldes de clôture historiques)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", au coût"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", à la valeur de marché à la date du mouvement"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", à la valeur de marché en fin de chaque période"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", à la valeur de marché actuelle"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", à la valeur de marché au {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Rapport budgétaire"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Rapport de soldes multipériode"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Rapport de soldes"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} {dates}{valuation} :"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Variations de valeur en fin de période"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Variations cumulées de valeur en fin de période"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Plus-value de la période"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Plus-value cumulée"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Plus-value historique"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Nombre de mouvements"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Nombre cumulé de mouvements"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Nombre historique de mouvements"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Nombre d'opérations"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Variations de solde"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Soldes de clôture (cumulés)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Soldes de clôture (historiques)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Exécution du budget {dates}{valuation} :"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Unité"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Moyenne"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Bilan"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Bilan quotidien"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Bilan hebdomadaire"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Bilan par quinzaine"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Bilan mensuel"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Bilan bimestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Bilan trimestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Bilan semestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Bilan annuel"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Bilan biennal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Bilan périodique"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Bilan avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Bilan quotidien avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Bilan hebdomadaire avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Bilan par quinzaine avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Bilan mensuel avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Bilan bimestriel avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Bilan trimestriel avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Bilan semestriel avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Bilan annuel avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Bilan biennal avec capitaux propres"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Bilan périodique avec capitaux propres"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Tableau des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Tableau quotidien des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Tableau hebdomadaire des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Tableau des flux de trésorerie par quinzaine"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Tableau mensuel des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Tableau bimestriel des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Tableau trimestriel des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Tableau semestriel des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Tableau annuel des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Tableau biennal des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Tableau périodique des flux de trésorerie"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Flux de trésorerie"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Les valeurs et les plus-values excluent les placements sans prix de marché : {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Plus-value réalisée"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Plus-value latente"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Moins-value réalisée"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Moins-value latente"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Plus-value nette"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Coût"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Pas de prix de marché"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Valeur"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Coût moyen"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Coût unitaire/moyen"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Coût unitaire"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Les totaux de Valeur totale, PV lat., PV lat. % et TRI excluent les placements sans prix de marché : {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Les totaux de PV réal. et TRI incluent {n} position soldée, non affichée"+msgstr[1] "Les totaux de PV réal. et TRI incluent {n} positions soldées, non affichées"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, plus-values de chaque période"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, plus-values depuis le {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Portefeuille quotidien"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Portefeuille hebdomadaire"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Portefeuille par quinzaine"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Portefeuille mensuel"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Portefeuille bimestriel"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Portefeuille trimestriel"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Portefeuille semestriel"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Portefeuille annuel"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Portefeuille biennal"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Portefeuille périodique"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Portefeuille"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Quantité"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Prix unitaire"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Coût total"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Valeur totale"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "PV lat."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "PV lat. %"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "PV réal."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "TRI"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(aucune position)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Date"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Portefeuille au {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Portefeuille au {date}, plus-values sur {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(voir -E)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Âge"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Poids"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Compte"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Total :"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Compte de résultat"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Compte de résultat quotidien"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Compte de résultat hebdomadaire"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Compte de résultat par quinzaine"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Compte de résultat mensuel"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Compte de résultat bimestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Compte de résultat trimestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Compte de résultat semestriel"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Compte de résultat annuel"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Compte de résultat biennal"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Compte de résultat périodique"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Registre"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Afficher :"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Titres"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Graphiques"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Tous"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "soldes des comptes"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "variations des comptes"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "soldes de trésorerie"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "soldes du bilan"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "variations du compte de résultat"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Comptes de trésorerie"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Comptes du bilan"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Comptes du compte de résultat"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Tous les comptes"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Total au coût :"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "La somme de tous les comptes, convertie au coût. Non nulle quand quelque chose n'est pas équilibré."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Total à la valeur de marché :"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "La somme de tous les comptes à la valeur de marché. Non nulle quand des valeurs ont changé sans qu'aucune écriture n'enregistre la plus-value ou la moins-value, par ex. des plus-values latentes sur placements."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "La somme de tous les comptes. Non nulle quand quelque chose n'est pas équilibré, par ex. des conversions avec @ sans --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Soldes au {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Le solde de chaque compte à la fin de ce jour : la fin des dates de la recherche, ou sinon la dernière date du journal"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Journal"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Afficher les écritures du journal général, les plus récentes d'abord"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Bilan"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Afficher les actifs, les passifs et la valeur nette"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Compte de résultat"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Afficher les revenus et les dépenses"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Tableau des flux de trésorerie"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Afficher les variations des actifs liquides"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Afficher les placements détenus, les lots et les plus-values"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Afficher les soldes de tous les comptes, par période, comme la commande balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Opérations {first} à {last} sur {total}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Afficher la page {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Page {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Afficher seulement {year}"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Maj-clic sélectionne une plage d'années."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Intervalle :"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Afficher une seule colonne pour toute la période"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Aucun"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Annuel"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Afficher une colonne par année"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Trimestriel"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Afficher une colonne par trimestre"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Mensuel"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Afficher une colonne par mois"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Hebdomadaire"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Afficher une colonne par semaine"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Quotidien"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Afficher une colonne par jour"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Afficher de combien chaque solde a varié à chaque période"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Totaux cumulés"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Afficher la variation de chaque solde depuis le début du rapport (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Soldes de clôture"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Afficher chaque solde en fin de période, en incluant tout ce qui précède"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Calcul :"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Afficher les sommes des mouvements"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Sommes"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Variation de valeur"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Afficher comment les valeurs de marché en fin de période ont varié (--valuechange)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Plus-value latente"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Afficher les plus-values latentes : valeur de marché moins coût (--gain)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Compter les mouvements au lieu de les additionner (--count)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Comptes :"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Afficher les comptes en liste à plat (--flat)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Liste"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Afficher les comptes en arborescence (--tree)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Arborescence"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Tri :"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Par compte"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Trier les lignes selon l'ordre d'affichage des comptes"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Par montant"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Trier les lignes par montant, du plus grand au plus petit (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Graphique :"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Divergent"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Représenter les montants de chaque période dans une seule barre, au-dessus et au-dessous de zéro (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Groupé"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Représenter les types de compte de chaque période dans des barres côte à côte (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Profondeur {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "illimitée"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Tels qu'enregistrés"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Coût"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Valeur"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Pourcentages"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Graphique groupé"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Total"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Moyenne"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Prix déduits"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Soldes nuls masqués"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Soldes nuls affichés"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Lots affichés"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Coûts affichés"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Positions soldées affichées"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Positions soldées masquées"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Dates secondaires"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Capitaux propres affichés"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Impossible de calculer les pourcentages :"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Impossible d'analyser l'intervalle du rapport :"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Conversion des montants inconnue :"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Le paramètre {name} a une valeur que cette page ne connaît pas :"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Les variations de valeur et les plus-values sont calculées à partir des valeurs de marché en fin de période : omettez le paramètre value, ou utilisez value=end."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Les plus-values comparent la valeur de marché au coût ; elles ne se combinent donc pas avec value=cost."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Ce rapport porte sur une seule date ; value=then ne s'applique donc pas : utilisez value=end, value=now ou une date."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Afficher ce rapport pour cette période"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Opération ajoutée."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, avec filtre"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "soldes - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Tous"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Maj-clic sélectionne plusieurs types."++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Maj-clic sélectionne plusieurs unités."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Échec du chargement du journal : {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Journal {file} enregistré"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Modifier le journal"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "portefeuille - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Afficher le registre de ce compte"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Afficher le registre de ce placement"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Afficher le portefeuille à cette date"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "les afficher"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Plus-values :"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "Sur chaque période"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Afficher les plus-values de chaque période"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Depuis le début du rapport"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Afficher les plus-values depuis la date de début du rapport, jusqu'à la fin de chaque période"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Depuis l'acquisition"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Afficher les plus-values depuis l'acquisition de chaque placement, jusqu'à la fin de chaque période"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Journal général"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Opérations de {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Opérations de {account} (hors sous-comptes)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "journal - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "tous les comptes"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (hors sous-comptes)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Total historique"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Total de la période"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Cliquer pour afficher le solde courant depuis le début de cette période"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Cliquer pour afficher le solde courant en incluant tout ce qui précède cette période"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "registre - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "sans symbole"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "bilan avec capitaux propres - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "bilan - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "compte de résultat - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "tableau des flux de trésorerie - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Tous les comptes affichés par ce rapport ont un solde nul, et sont masqués. Appuyez sur z pour les afficher."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Aucun compte des types affichés par ce rapport n'a été trouvé. Déclarez les types de compte, ou utilisez les noms de comptes de premier niveau standard de hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Comment hledger détermine les types de compte"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "Rien ne correspond à cette recherche sur cette période."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Erreur d'encodage : '{error}'. Si votre fichier n'est pas encodé en UTF-8, essayez le « formulaire de modification », où le navigateur devrait gérer le transcodage."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Fichier {file} téléversé"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Téléverser un journal"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Fermer"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Ajouter une opération"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Compte {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Montant {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Format de date invalide"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Date"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Description"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Montant manquant"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Compte manquant"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Valeur invalide : {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Échec de la validation des mouvements"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Unité"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Afficher / masquer le graphique (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Graphique"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Afficher / masquer les données (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Données"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Afficher les options qui modifient cette vue"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Options"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} {dates}"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} {dates}, avec filtre"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Ces réglages s'appliquent aux pages de rapport"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Prix :"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Déclarés"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Évaluer les montants avec les prix de marché déclarés (directives P) seulement"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Déduits aussi"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Déduire aussi les prix de marché des coûts des opérations (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Profondeur :"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Afficher seulement le total (profondeur 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Afficher les comptes à toutes les profondeurs"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Afficher les comptes jusqu'à la profondeur {depth}"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Montants :"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Afficher les montants dans les unités où ils ont été enregistrés"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Au coût"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Afficher les montants convertis à leur coût, tel qu'enregistré dans les opérations (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "À la valeur de marché"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Afficher les montants convertis à leur valeur de marché en fin de chaque période, d'après les prix de marché (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Soldes nuls :"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Masquer les comptes dont le solde est nul"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Masqués"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Afficher les comptes dont le solde est nul"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Affichés"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Capitaux propres :"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Afficher les actifs, les passifs et la valeur nette, comme la commande balancesheet"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Afficher les actifs, les passifs et les capitaux propres, comme la commande balancesheetequity"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Statut :"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Afficher les opérations de tout statut"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Tous"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Non marquées"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Afficher seulement les opérations non marquées (status:)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "En attente"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Afficher seulement les opérations en attente (status:!)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Rapprochées"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Afficher seulement les opérations rapprochées (status:*)"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Mouvements :"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Afficher les mouvements réels et virtuels"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Tous"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Réels"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Afficher seulement les mouvements réels, comme -R (real:1)"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Virtuels"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Afficher seulement les mouvements virtuels, ceux entre parenthèses (real:0)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Colonnes supplémentaires :"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Ajouter une colonne totalisant chaque ligne (-T)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Ajouter une colonne donnant la moyenne de chaque ligne (-A)"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Nombres :"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Afficher les montants"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Montants"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Afficher chaque montant en pourcentage du total de sa colonne (-%)"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Coûts :"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Afficher les montants sans leur coût"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Masqués"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Afficher les montants avec les coûts enregistrés dans le journal"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Affichés"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Lots :"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Regrouper les lots de chaque compte"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Masqués"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Afficher chaque lot séparément (--lots)"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Affichés"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Positions soldées :"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Afficher seulement les positions ouvertes"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Masquées"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Afficher aussi les positions entièrement cédées et leurs plus-values réalisées (-E)"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Affichées"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Valeurs :"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "Par unité de coût"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Évaluer chaque placement dans sa propre unité de coût"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Convertir les valeurs et les coûts dans l'unité d'évaluation de marché (-V)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Type :"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Afficher les comptes de tous types"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Tous"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Actif"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Afficher seulement les comptes d'actif (type:A)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Passif"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Afficher seulement les comptes de passif (type:L)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Afficher seulement les comptes de capitaux propres (type:E)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Revenu"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Afficher seulement les comptes de revenus (type:R)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Dépense"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Afficher seulement les comptes de dépenses (type:X)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Trésorerie"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Afficher seulement les comptes de trésorerie (type:C)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Conversion"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Afficher seulement les comptes de conversion (type:V)"++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Plus-value"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Afficher seulement les comptes de plus-values (type:G)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Déséquilibre"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Afficher seulement les comptes de déséquilibre (type:M)"++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Lister toutes les unités"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Unité :"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Afficher les montants dans toutes les unités"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Toutes"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Afficher seulement les montants en {commodity}"++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… et {n} de plus"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Choisir une date"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Ajouter à :"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Enregistrer"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Replier les comptes d'un niveau de plus"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Déplier les comptes d'un niveau de plus"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Afficher / masquer les soldes"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Soldes"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Afficher les opérations touchant ce compte et ses sous-comptes"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Afficher les opérations touchant ce compte, mais pas ses sous-comptes"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "seul"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Afficher les opérations qui composent ce solde"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Afficher les opérations qui composent ce total"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Afficher / masquer la barre latérale (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web ne fonctionne plus. Il s'arrête après quinze minutes sans fenêtre de navigateur qui l'affiche, ou quand on l'arrête. Pour continuer, relancez-le et rechargez cette page."++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Quitter le plein écran"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Rechercher"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Saisir des motifs de recherche hledger pour filtrer les données ci-dessous"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Effacer les termes de recherche"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Appliquer les termes de recherche"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Gérer les fichiers du journal"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Afficher l'aide sur la recherche et l'aide générale"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Aller à"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Aide"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Raccourcis clavier"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "ou"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "afficher cette aide"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "aller à n'importe quel écran"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "aller à l'écran suivant ou précédent"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "ajouter une opération"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "afficher / masquer la barre latérale"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "définir la profondeur des comptes de la barre latérale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "afficher / masquer les soldes de la barre latérale"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "afficher / masquer les options du rapport"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "afficher / masquer le graphique du rapport"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "choisir l'unité du graphique"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "afficher / masquer la ligne du total net du graphique"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "afficher / masquer les données du rapport"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "activer / quitter le plein écran"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "aller au formulaire de recherche"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "effacer la recherche"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "annuler"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Options du rapport"++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "soldes de clôture historiques / variations de solde"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "annuel"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "trimestriel"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "mensuel"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "hebdomadaire"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "quotidien"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "non marquées"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "en attente"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "rapprochées"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "réels seulement / tous"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Limite de profondeur :"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "la définir"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "la diminuer ou l'augmenter"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "arborescence / liste"++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "au coût"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "à la valeur de marché"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "afficher / masquer les soldes nuls"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "afficher / masquer le détail des lots"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "total"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "moyenne"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "par montant / selon l'ordre d'affichage des comptes"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Une seconde pression sur la touche d'une option la désactive."++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Requêtes de recherche"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Les motifs de recherche contenant des espaces doivent être mis entre guillemets."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "correspondre aux noms de compte"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "correspondre aux types de compte (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "correspondre aux dates"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "correspondre au statut"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "correspondre aux codes d'opération"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "correspondre aux descriptions des opérations"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "correspondre à la partie bénéficiaire des descriptions"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "correspondre à la partie note des descriptions"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "correspondre aux montants en valeur absolue, ou, avec un N signé, aux montants signés. N peut avoir un symbole d'unité."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "correspondre aux lignes du rapport (comptes, périodes, opérations) selon leur variation ou leur solde, comme amt:. N peut avoir un symbole d'unité."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "correspondre aux devises/unités. Doit correspondre au symbole/nom entier. Pour le signe dollar, écrire"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "correspondre aux étiquettes, ou à une étiquette et sa valeur"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "correspondre au caractère réel/virtuel des mouvements"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "correspondre à n'importe quel champ (compte, montant, commentaire, étiquette, description, code), ou à une date si REGEX est aussi une expression de période"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "préfixer par not: pour exclure un terme de recherche"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "correspondre à une requête booléenne (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "correspondre aux opérations dont au moins un mouvement correspond"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "correspondre aux opérations dont tous les mouvements correspondent"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "une autre façon de fixer la limite de profondeur (possible par compte)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Plus d'aide :"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "Manuel d'utilisation de hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Modifier le fichier"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Êtes-vous sûr ? Cela écrasera votre journal !"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Aide sur le format de fichier"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Retour"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Ajouter une nouvelle opération au journal"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Date"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Description"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Compte"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Montant"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Afficher les écritures du journal à cette date"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Les fichiers de votre journal"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Fichier"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Modifier"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Téléverser"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Télécharger"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Afficher les opérations plus récentes"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Plus récentes"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Afficher les opérations plus anciennes"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Plus anciennes"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Vers/depuis le(s) compte(s)"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Montant sortie/entrée"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Afficher cette écriture et les autres écritures du journal à sa date"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Solde reporté"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Afficher les opérations antérieures à cette période"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Téléverser vers le fichier"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Choisir un fichier"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Années :"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Afficher toutes les années"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Toutes"++#~ msgid "Next report"+#~ msgstr "Rapport suivant"++#~ msgid "Go to the next report"+#~ msgstr "Aller au rapport suivant"++#~ msgid "Previous report"+#~ msgstr "Rapport précédent"++#~ msgid "Go to the previous report"+#~ msgstr "Aller au rapport précédent"++#~ msgid "Net, at cost:"+#~ msgstr "Net, au coût :"++#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "La somme de tous les comptes, au coût : zéro pour une comptabilité équilibrée ; un reste provient de mouvements virtuels non équilibrés."++#~ msgid "Unbooked gains:"+#~ msgstr "Plus-values non comptabilisées :"++#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "La somme de tous les comptes à la valeur de marché : l'appréciation qu'aucune écriture n'a comptabilisée. Si les plus-values réalisées sont comptabilisées, il s'agit des plus-values latentes."++#~ msgid "Net flows:"+#~ msgstr "Flux nets :"++#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "La somme de tous les comptes : les positions ouvertes dans chaque unité, et la trésorerie qui les a payées. Zéro quand rien ne passe d'une unité à une autre."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Portefeuille en fin de période"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Portefeuille en fin de période, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Mode de cumul des soldes inconnu :"++#~ msgid "Show only the total"+#~ msgstr "Afficher seulement le total"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Afficher les opérations qui composent ce solde"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Afficher les opérations qui composent ce total"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "correspondre à n'importe quel champ visible (compte, montant, commentaire, description, code), ou à une date si REGEX est aussi une expression de période"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "correspondre aux montants sans signe, ou, avec un N signé, aux montants signés. Pour les montants à une seule unité seulement."
+ locale/ga.po view
@@ -0,0 +1,2837 @@+# Irish translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, Irish.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: ga\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n==2 ? 1 : 2);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Eanáir"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Feabhra"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Márta"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Aibreán"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Bealtaine"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Meitheamh"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Iúil"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Lúnasa"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Meán Fómhair"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Deireadh Fómhair"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Samhain"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Nollaig"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Ean"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Feabh"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Márta"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Aib"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Beal"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Meith"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Iúil"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Lún"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "MFómh"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "DFómh"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Samh"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Noll"++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Sonraí na tuarascála"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Iomlán"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Sócmhainní"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Dliteanais"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Cothromas"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Ioncam"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Speansais"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Eile"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Iarmhéid"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Iomlán"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Glan:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…agus {n} eile"+msgstr[1] "…agus {n} eile"+msgstr[2] "…agus {n} eile"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "{parent} eile (cuntas: {n})"+msgstr[1] "{parent} eile (cuntais: {n})"+msgstr[2] "{parent} eile (cuntais: {n})"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "eile (cuntas: {n})"+msgstr[1] "eile (cuntais: {n})"+msgstr[2] "eile (cuntais: {n})"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Athruithe Luacha ag Deireadh Tréimhse)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Athruithe Carnacha Luacha ag Deireadh Tréimhse)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Gnóthachan Incriminteach)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Gnóthachan Carnach)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Gnóthachan Stairiúil)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Athruithe Iarmhéide)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Iarmhéideanna Deiridh Carnacha)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Iarmhéideanna Deiridh Stairiúla)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", i gcostas"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", luacháil ar dháta na postála"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", luacháil ag deireadh gach tréimhse"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", luach reatha"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", luacháil ar {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Tuarascáil Bhuiséid"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Tuarascáil Iarmhéideanna Ilthréimhse"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Tuarascáil Iarmhéideanna"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Athruithe luacha ag deireadh tréimhse"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Athruithe carnacha luacha ag deireadh tréimhse"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Gnóthachan incriminteach"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Gnóthachan carnach"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Gnóthachan stairiúil"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Líon postálacha"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Líon carnach postálacha"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Líon stairiúil postálacha"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Líon idirbheart"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Athruithe iarmhéide"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Iarmhéideanna deiridh (carnach)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Iarmhéideanna deiridh (stairiúil)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Feidhmíocht an bhuiséid {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Aonad"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Meán"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Clár Comhardaithe"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Clár Comhardaithe Laethúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Clár Comhardaithe Seachtainiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Clár Comhardaithe Coicísiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Clár Comhardaithe Míosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Clár Comhardaithe Démhíosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Clár Comhardaithe Ráithiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Clár Comhardaithe Leathbhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Clár Comhardaithe Bliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Clár Comhardaithe Débhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Clár Comhardaithe Tréimhsiúil"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Clár Comhardaithe le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Clár Comhardaithe Laethúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Seachtainiúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Coicísiúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Míosúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Démhíosúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Ráithiúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Leathbhliantúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Clár Comhardaithe Bliantúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Clár Comhardaithe Débhliantúil le Cothromas"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Clár Comhardaithe Tréimhsiúil le Cothromas"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Laethúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Seachtainiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Coicísiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Míosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Démhíosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Ráithiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Leathbhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Bliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Débhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Ráiteas Sreabhadh Airgid Tréimhsiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Sreabhadh airgid"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Ní áirítear sealúchais gan praghas margaidh sna luachanna ná sna gnóthachain: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Gnóthachan réadaithe"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Gnóthachan neamhréadaithe"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Caillteanas réadaithe"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Caillteanas neamhréadaithe"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Glanghnóthachan"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Costas"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Gan praghas margaidh"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Luach"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Meánchostas"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Costas aonaid/meánchostas"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Costas aonaid"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Ní áirítear sealúchais gan praghas margaidh in iomláin Luach iomlán, Gnóth. neamhr., Gnóth. neamhr. % agus XIRR: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Áirítear in iomláin Gnóth. réad. agus XIRR suíomh dúnta nach dtaispeántar: {n}"+msgstr[1] "Áirítear in iomláin Gnóth. réad. agus XIRR suíomhanna dúnta nach dtaispeántar: {n}"+msgstr[2] "Áirítear in iomláin Gnóth. réad. agus XIRR suíomhanna dúnta nach dtaispeántar: {n}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, gnóthachain i ngach tréimhse"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, gnóthachain ó {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Sealúchais Laethúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Sealúchais Sheachtainiúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Sealúchais Choicísiúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Sealúchais Mhíosúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Sealúchais Dhémhíosúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Sealúchais Ráithiúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Sealúchais Leathbhliantúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Sealúchais Bhliantúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Sealúchais Dhébhliantúla"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Sealúchais Thréimhsiúla"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Sealúchais"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Aonaid"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Praghas aonaid"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Costas iomlán"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Luach iomlán"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Gnóth. neamhr."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Gnóth. neamhr. %"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Gnóth. réad."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(gan sealúchais)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Dáta"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Sealúchais ar {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Sealúchais ar {date}, gnóthachain sa tréimhse {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(féach -E)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Aois"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Ualach"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Cuntas"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Iomlán:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Ráiteas Ioncaim"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Ráiteas Ioncaim Laethúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Ráiteas Ioncaim Seachtainiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Ráiteas Ioncaim Coicísiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Ráiteas Ioncaim Míosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Ráiteas Ioncaim Démhíosúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Ráiteas Ioncaim Ráithiúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Ráiteas Ioncaim Leathbhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Ráiteas Ioncaim Bliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Ráiteas Ioncaim Débhliantúil"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Ráiteas Ioncaim Tréimhsiúil"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Clár"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Taispeáin:"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Teidil"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Cairteacha"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Uile"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "iarmhéideanna cuntas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "athruithe cuntas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "iarmhéideanna airgid"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "iarmhéideanna an chláir chomhardaithe"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "athruithe an ráitis ioncaim"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Cuntais airgid"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Cuntais an chláir chomhardaithe"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Cuntais an ráitis ioncaim"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Gach cuntas"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Iomlán ag costas:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "Suim gach cuntais, arna tiontú go costas. Ní nialas í nuair a bhíonn rud éigin neamhchothromaithe."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Iomlán ag luach margaidh:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "Suim gach cuntais ag luach margaidh. Ní nialas í nuair a d'athraigh luachanna agus nach dtaifeadann aon iontráil an gnóthachan ná an caillteanas, m.sh. gnóthachain infheistíochta neamhréadaithe."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "Suim gach cuntais. Ní nialas í nuair a bhíonn rud éigin neamhchothromaithe, m.sh. tiontuithe le @ gan --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Iarmhéideanna ar {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Iarmhéid gach cuntais ag deireadh an lae seo: deireadh dhátaí an chuardaigh, nó murach sin, an dáta deireanach sa dialann"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Dialann"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Taispeáin iontrálacha na dialainne ginearálta, an ceann is déanaí ar dtús"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Clár comhardaithe"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Taispeáin sócmhainní, dliteanais, agus glanfhiúchas"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Ráiteas ioncaim"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Taispeáin ioncam agus speansais"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Ráiteas sreabhadh airgid"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Taispeáin athruithe i sócmhainní leachtacha"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Taispeáin sealúchais infheistíochta, lotaí, agus gnóthachain"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Taispeáin iarmhéideanna gach cuntais, de réir tréimhse, mar a dhéanann an t-ordú balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Idirbhearta {first} go {last} as {total} á dtaispeáint"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Taispeáin leathanach {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Leathanach {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Taispeáin {year} amháin"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Roghnaíonn Shift-chliceáil raon blianta."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Eatramh:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Taispeáin colún amháin don tréimhse iomlán"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Dada"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Bliantúil"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Taispeáin colún do gach bliain"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Ráithiúil"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Taispeáin colún do gach ráithe"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Míosúil"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Taispeáin colún do gach mí"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Seachtainiúil"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Taispeáin colún do gach seachtain"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Laethúil"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Taispeáin colún do gach lá"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Taispeáin an méid a d'athraigh gach iarmhéid i ngach tréimhse"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Iomláin charnacha"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Taispeáin athrú gach iarmhéide ó thús na tuarascála (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Iarmhéideanna deiridh"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Taispeáin gach iarmhéid ag deireadh gach tréimhse, lena n-áirítear gach rud roimhe"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Ríomh:"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Taispeáin suimeanna postálacha"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Suimeanna"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Athrú luacha"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Taispeáin conas a d'athraigh luachanna margaidh ag deireadh tréimhse (--valuechange)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Gnóthachan neamhréadaithe"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Taispeáin gnóthachain chaipitiúla neamhréadaithe: luach margaidh lúide costas (--gain)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Comhair na postálacha in ionad iad a shuimiú (--count)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Cuntais:"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Taispeáin cuntais mar liosta cothrom (--flat)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Liosta"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Taispeáin cuntais mar chrann (--tree)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Crann"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Sórtáil:"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "De réir cuntais"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Sórtáil sraitheanna de réir ord taispeána na gcuntas"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "De réir méide"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Sórtáil sraitheanna de réir a méideanna, an ceann is mó ar dtús (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Cairt:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Scartha"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Taispeáin méideanna gach tréimhse i mbarra amháin, os cionn agus faoi bhun nialais (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Grúpáilte"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Taispeáin cineálacha cuntas gach tréimhse i mbarraí taobh le taobh (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Doimhneacht {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "gan teorainn"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Mar a taifeadadh"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Costas"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Luach"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Céatadáin"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Cairt ghrúpáilte"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Iomlán"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Meán"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Praghsanna tátalaithe"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Iarmhéideanna nialasacha i bhfolach"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Iarmhéideanna nialasacha taispeánta"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Lotaí taispeánta"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Costais taispeánta"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Suíomhanna dúnta taispeánta"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Suíomhanna dúnta i bhfolach"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Dátaí tánaisteacha"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Cothromas taispeánta"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Níorbh fhéidir céatadáin a ríomh:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Níorbh fhéidir an t-eatramh tuairiscithe a pharsáil:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Tiontú méide anaithnid:"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Tá luach ag an bparaiméadar {name} nach n-aithníonn an leathanach seo:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Ríomhtar athruithe luacha agus gnóthachain ó luachanna margaidh ag deireadh tréimhse: fág an paraiméadar value ar lár, nó úsáid value=end."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Cuireann gnóthachain luach margaidh i gcomparáid le costas, mar sin ní féidir iad a úsáid le value=cost."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Tá an tuarascáil seo ar dháta amháin, mar sin ní bhaineann value=then léi: úsáid value=end, value=now, nó dáta."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Taispeáin an tuarascáil seo don tréimhse seo"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Idirbheart curtha leis."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, scagtha"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "iarmhéid - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Uile"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Roghnaíonn Shift-chliceáil roinnt cineálacha."++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Roghnaíonn Shift-chliceáil roinnt aonad."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Níorbh fhéidir an dialann a lódáil: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Sábháladh an dialann {file}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Cuir an dialann in eagar"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "sealúchais - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Taispeáin clár an chuntais seo"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Taispeáin clár an tsealúchais seo"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Taispeáin na sealúchais ar an dáta seo"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "taispeáin iad"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Gnóthachain:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "I ngach tréimhse"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Taispeáin na gnóthachain le linn gach tréimhse"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Ó thús na tuarascála"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Taispeáin na gnóthachain ó dháta tosaigh na tuarascála go deireadh gach tréimhse"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Ó éadáil"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Taispeáin na gnóthachain ó éadáil gach sealúchais go deireadh gach tréimhse"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Dialann Ghinearálta"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Idirbhearta: {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Idirbhearta: {account} (gan fochuntais)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "dialann - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "gach cuntas"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (gan fochuntais)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Iomlán Stairiúil"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Iomlán na Tréimhse"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Cliceáil chun an t-iarmhéid reatha ó thús na tréimhse seo a thaispeáint"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Cliceáil chun an t-iarmhéid reatha a thaispeáint, lena n-áirítear gach rud roimh an tréimhse seo"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "clár - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "gan siombail"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "clár comhardaithe le cothromas - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "clár comhardaithe - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "ráiteas ioncaim - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "ráiteas sreabhadh airgid - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Tá iarmhéid nialasach ag gach cuntas a thaispeánann an tuarascáil seo, agus tá siad i bhfolach. Brúigh z chun iad a thaispeáint."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Níor aimsíodh aon chuntas de na cineálacha a thaispeánann an tuarascáil seo. Fógair cineálacha cuntas, nó úsáid ainmneacha caighdeánacha barrleibhéil cuntas hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Conas a aimsíonn hledger cineálacha cuntas"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "Níl aon rud sa tréimhse seo a mheaitseálann an cuardach seo."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Earráid ionchódaithe: '{error}'. Mura bhfuil do chomhad ionchódaithe in UTF-8, bain triail as an 'fhoirm eagarthóireachta', áit ar cheart don bhrabhsálaí an tras-ionchódú a láimhseáil."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Uaslódáladh an comhad {file}"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Uaslódáil dialann"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Dún"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Cuir idirbheart leis"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Cuntas {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Méid {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Formáid dáta neamhbhailí"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Dáta"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Cur síos"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Méid ar iarraidh"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Cuntas ar iarraidh"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Luach neamhbhailí: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Theip ar bhailíochtú na bpostálacha"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Aonad"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Taispeáin nó folaigh an chairt (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Cairt"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Taispeáin nó folaigh na sonraí (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Sonraí"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Taispeáin na roghanna a athraíonn an t-amharc seo"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Roghanna"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title}, {dates}"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title}, {dates}, scagtha"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Bíonn éifeacht ag na rialuithe seo ar leathanaigh na dtuarascálacha"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Praghsanna:"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Fógartha"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Luacháil méideanna le praghsanna margaidh fógartha (treoracha P) amháin"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Tátalaithe freisin"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Bain praghsanna margaidh as costais idirbheart freisin (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Doimhneacht:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Taispeáin an t-iomlán amháin (doimhneacht 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Taispeáin cuntais ag gach doimhneacht"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Taispeáin cuntais síos go doimhneacht {depth}"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Méideanna:"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Taispeáin méideanna sna haonaid inar taifeadadh iad"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Ag costas"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Taispeáin méideanna arna dtiontú go dtí a gcostas, mar a taifeadadh in idirbhearta iad (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "Ag luach margaidh"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Taispeáin méideanna arna dtiontú go dtí a luach margaidh ag deireadh gach tréimhse, le praghsanna margaidh (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Iarmhéideanna nialasacha:"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Folaigh cuntais a bhfuil iarmhéid nialasach acu"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "I bhfolach"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Taispeáin cuntais a bhfuil iarmhéid nialasach acu"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Taispeánta"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Cothromas:"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Taispeáin sócmhainní, dliteanais, agus glanfhiúchas, mar a dhéanann an t-ordú balancesheet"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Taispeáin sócmhainní, dliteanais, agus cothromas, mar a dhéanann an t-ordú balancesheetequity"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Stádas:"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Taispeáin idirbhearta d'aon stádas"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Uile"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Gan mharcáil"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Taispeáin idirbhearta gan mharcáil amháin (status:)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Ar feitheamh"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Taispeáin idirbhearta ar feitheamh amháin (status:!)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Glanta"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Taispeáin idirbhearta glanta amháin (status:*)"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Postálacha:"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Taispeáin postálacha fíora agus fíorúla"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Uile"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Fíor"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Taispeáin postálacha fíora amháin, mar a dhéanann -R (real:1)"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Fíorúil"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Taispeáin postálacha fíorúla amháin, iad siúd idir lúibíní (real:0)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Colúin bhreise:"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Cuir colún leis a thugann iomlán gach sraithe (-T)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Cuir colún leis a thugann meán gach sraithe (-A)"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Uimhreacha:"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Taispeáin na méideanna"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Méideanna"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Taispeáin gach méid mar chéatadán d'iomlán a cholúin (-%)"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Costais:"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Taispeáin méideanna gan a gcostais"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "I bhfolach"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Taispeáin méideanna leis na costais a taifeadadh sa dialann"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Taispeánta"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Lotaí:"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Comhiomlánaigh lotaí gach cuntais"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "I bhfolach"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Taispeáin gach lota ar leith (--lots)"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Taispeánta"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Suíomhanna dúnta:"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Taispeáin suíomhanna oscailte amháin"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "I bhfolach"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Taispeáin freisin suíomhanna a diúscraíodh go hiomlán agus a ngnóthachain réadaithe (-E)"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Taispeánta"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Luachanna:"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "De réir aonad costais"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Luacháil gach sealúchas ina aonad costais féin"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Tiontaigh luachanna agus costais go haonad luachála an mhargaidh (-V)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Cineál:"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Taispeáin cuntais de gach cineál"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Uile"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Sócmhainn"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Taispeáin cuntais shócmhainne amháin (type:A)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Dliteanas"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Taispeáin cuntais dhliteanais amháin (type:L)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Taispeáin cuntais chothromais amháin (type:E)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Ioncam"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Taispeáin cuntais ioncaim amháin (type:R)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Speansas"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Taispeáin cuntais speansais amháin (type:X)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Airgead"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Taispeáin cuntais airgid amháin (type:C)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Tiontú"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Taispeáin cuntais thiontaithe amháin (type:V)"++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Gnóthachan"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Taispeáin cuntais ghnóthachain chaipitiúil amháin (type:G)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Míchothromaíocht"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Taispeáin cuntais mhíchothromaíochta amháin (type:M)"++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Liostaigh na haonaid go léir"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Aonad:"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Taispeáin méideanna i ngach aonad"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Uile"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Taispeáin méideanna in {commodity} amháin"++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… agus {n} eile"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Roghnaigh dáta"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Cuir le:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Sábháil"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Fill na cuntais leibhéal amháin eile"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Oscail na cuntais leibhéal amháin eile"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Taispeáin nó folaigh na hiarmhéideanna"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Iarmhéideanna"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Taispeáin idirbhearta a bhaineann leis an gcuntas seo agus lena fhochuntais"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Taispeáin idirbhearta a bhaineann leis an gcuntas seo ach ní lena fhochuntais"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "amháin"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Taispeáin na hidirbhearta taobh thiar den iarmhéid seo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Taispeáin na hidirbhearta taobh thiar den iomlán seo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Taispeáin nó folaigh an barra taoibh (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "Níl hledger-web ag rith a thuilleadh. Stopann sé tar éis cúig nóiméad déag gan aon fhuinneog brabhsálaí á thaispeáint, nó nuair a stoptar é. Chun leanúint ar aghaidh, tosaigh arís é agus athlódáil an leathanach seo."++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Fág an fhuinneog iomlán"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Cuardaigh"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Cuir isteach patrúin chuardaigh hledger chun na sonraí thíos a scagadh"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Glan na téarmaí cuardaigh"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Cuir na téarmaí cuardaigh i bhfeidhm"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Bainistigh comhaid dialainne"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Taispeáin cabhair chuardaigh agus ghinearálta"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Téigh go"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Cabhair"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Aicearraí méarchláir"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "nó"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "féach ar an gcabhair seo"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "téigh go dtí aon scáileán"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "téigh go dtí an chéad scáileán eile nó an scáileán roimhe"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "cuir idirbheart leis"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "scoránaigh an barra taoibh"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "socraigh doimhneacht cuntas an bharra taoibh"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "taispeáin nó folaigh iarmhéideanna an bharra taoibh"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "scoránaigh roghanna na tuarascála"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "scoránaigh cairt na tuarascála"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "roghnaigh aonad na cairte"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "scoránaigh líne ghlaniomlán na cairte"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "scoránaigh sonraí na tuarascála"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "scoránaigh an fhuinneog iomlán"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "dírigh ar an bhfoirm chuardaigh"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "glan an cuardach"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "cealaigh"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Roghanna tuarascála"++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "iarmhéideanna deiridh stairiúla / athruithe iarmhéide"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "bliantúil"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "ráithiúil"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "míosúil"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "seachtainiúil"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "laethúil"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "gan mharcáil"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "ar feitheamh"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "glanta"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "fíor amháin / uile"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Teorainn doimhneachta:"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "socraigh í"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "laghdaigh nó méadaigh í"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "crann / liosta"++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "ag costas"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "ag luach margaidh"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "taispeáin / folaigh iarmhéideanna nialasacha"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "taispeáin / folaigh sonraí na lotaí"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "iomlán"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "meán"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "de réir méide / de réir ord taispeána na gcuntas"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Má bhrúitear eochair rogha arís, casann sé as í."++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Iarratais chuardaigh"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Ba cheart patrúin chuardaigh ina bhfuil spásanna a chur idir comharthaí athfhriotail."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "meaitseáil ainmneacha cuntas"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "meaitseáil cineálacha cuntas (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "meaitseáil dátaí"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "meaitseáil stádas"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "meaitseáil cóid idirbheart"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "meaitseáil cur síos idirbheart"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "meaitseáil an chuid íocaí den chur síos"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "meaitseáil an chuid nóta den chur síos"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "meaitseáil méideanna gan chomhartha, nó, le N sínithe, méideanna sínithe. Féadfaidh siombail aonaid a bheith ag N."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "meaitseáil rónna tuarascála (cuntais, tréimhsí, idirbhearta) de réir a n-athraithe nó a n-iarmhéide, cosúil le amt:. Féadfaidh siombail aonaid a bheith ag N."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "meaitseáil airgeadraí/tráchtearraí. Caithfidh sé an tsiombail/an t-ainm iomlán a mheaitseáil. Chun an comhartha dollair a mheaitseáil, scríobh"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "meaitseáil clibeanna, nó clib agus luach"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "meaitseáil fíoracht/fíorúlacht postálacha"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "meaitseáil aon réimse (cuntas, méid, nóta tráchta, clib, cur síos, cód), nó dáta más slonn tréimhse é REGEX freisin"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "cuir not: roimh théarma cuardaigh chun é a dhiúltú"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "meaitseáil le hiarratas Boole (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "meaitseáil idirbhearta ina meaitseálann aon phostáil"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "meaitseáil idirbhearta ina meaitseálann gach postáil"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "bealach eile chun teorainn doimhneachta a shocrú (is féidir í a shocrú in aghaidh an chuntais)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Tuilleadh cabhrach:"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "Lámhleabhar úsáideora hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Cuir an comhad in eagar"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "An bhfuil tú cinnte? Forscríobhfaidh sé seo do dhialann!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Cabhair maidir le formáid an chomhaid"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Téigh siar"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Cuir idirbheart nua leis an dialann"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Dáta"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Cur síos"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Cuntas"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Méid"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Taispeáin iontrálacha na dialainne ar an dáta seo"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Comhaid do dhialainne"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Comhad"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Cuir in eagar"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Uaslódáil"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Íoslódáil"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Taispeáin na hidirbhearta níos nuaí"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Níos nuaí"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Taispeáin na hidirbhearta níos sine"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Níos sine"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Chuig/Ó Chuntas"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Méid Amach/Isteach"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Taispeáin an iontráil seo agus iontrálacha eile na dialainne ar a dáta"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Iarmhéid tugtha ar aghaidh"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Taispeáin na hidirbhearta roimh an tréimhse seo"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Uaslódáil chuig comhad"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Roghnaigh comhad"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Blianta:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Taispeáin gach bliain"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Uile"++#~ msgid "Next report"+#~ msgstr "An chéad tuarascáil eile"++#~ msgid "Go to the next report"+#~ msgstr "Téigh go dtí an chéad tuarascáil eile"++#~ msgid "Previous report"+#~ msgstr "An tuarascáil roimhe seo"++#~ msgid "Go to the previous report"+#~ msgstr "Téigh go dtí an tuarascáil roimhe seo"++#~ msgid "Net, at cost:"+#~ msgstr "Glan, i gcostas:"++#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "Suim gach cuntais, i gcostas: nialas do leabhair chothromaithe; tagann aon rud a fhanann ó phostálacha fíorúla neamhchothromaithe."++#~ msgid "Unbooked gains:"+#~ msgstr "Gnóthachain neamhthaifeadta:"++#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "Suim gach cuntais ag luach margaidh: luachmhéadú nach bhfuil taifeadta ag aon iontráil. Má thaifeadtar gnóthachain réadaithe, is iad seo na gnóthachain neamhréadaithe."++#~ msgid "Net flows:"+#~ msgstr "Glansreabhadh:"++#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "Suim gach cuntais: na suíomhanna oscailte i ngach aonad, agus an t-airgead a d'íoc astu. Nialas nuair nach dtrasnaíonn aon rud ó aonad go haonad."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Sealúchais ag deireadh na dtréimhsí"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Sealúchais ag deireadh na dtréimhsí, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Mód carntha iarmhéide anaithnid:"++#~ msgid "Show only the total"+#~ msgstr "Taispeáin an t-iomlán amháin"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Taispeáin na hidirbhearta a dhéanann suas an t-iarmhéid seo"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Taispeáin na hidirbhearta a dhéanann suas an t-iomlán seo"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "meaitseáil aon réimse infheicthe (cuntas, méid, nóta tráchta, cur síos, cód), nó dáta más slonn tréimhse é REGEX freisin"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "meaitseáil méideanna gan chomhartha, nó le N sínithe, méideanna sínithe. Do mhéideanna in aon aonad amháin."
+ locale/haw.po view
@@ -0,0 +1,2833 @@+# Hawaiian translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, Hawaiian.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: haw\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n != 1);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Ianuali"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Pepeluali"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Malaki"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "ʻApelila"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Mei"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Iune"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Iulai"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "ʻAukake"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Kepakemapa"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "ʻOkakopa"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Nowemapa"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Kekemapa"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Ian."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Pep."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mal."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "ʻAp."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Mei"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Iun."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Iul."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "ʻAu."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Kep."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "ʻOk."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Now."++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Kek."++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Nā kikoʻī o ka hōʻike"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Huina"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Nā Waiwai"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Nā ʻAiʻē"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Kumu Waiwai"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Loaʻa"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Hoʻolilo"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "ʻĒ aʻe"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Koena"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Huina"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Maʻemaʻe:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…a me {n} hou aku"+msgstr[1] "…a me {n} hou aku"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "{parent} ʻē aʻe ({n} moʻokālā)"+msgstr[1] "{parent} ʻē aʻe ({n} moʻokālā)"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "ʻē aʻe ({n} moʻokālā)"+msgstr[1] "ʻē aʻe ({n} moʻokālā)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Nā Loli Kumukūʻai ma ka Hopena o ka Wā)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Nā Loli Kumukūʻai Hōʻuluʻulu ma ka Hopena o ka Wā)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Puka o ka Wā)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Puka Hōʻuluʻulu)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Puka Mai ka Hoʻomaka)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Nā Loli Koena)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Nā Koena Hope Hōʻuluʻulu)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Nā Koena Hope Mai ka Hoʻomaka)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", ma ke kumukūʻai"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", ma ke kumukūʻai mākeke o ka lā o ka laina"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", ma ke kumukūʻai mākeke o ka hopena o kēlā me kēia wā"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", ma ke kumukūʻai mākeke o kēia manawa"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", ma ke kumukūʻai mākeke o {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Hōʻike Moho Kālā"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Hōʻike Koena o nā Wā He Nui"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Hōʻike Koena"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Nā loli kumukūʻai ma ka hopena o ka wā"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Nā loli kumukūʻai hōʻuluʻulu ma ka hopena o ka wā"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Puka o ka wā"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Puka hōʻuluʻulu"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Puka mai ka hoʻomaka"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Ka nui o nā laina"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Ka nui o nā laina (hōʻuluʻulu)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Ka nui o nā laina (mai ka hoʻomaka)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Ka nui o nā hana kālā"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Nā loli koena"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Nā koena hope (hōʻuluʻulu)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Nā koena hope (mai ka hoʻomaka)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Ka hoʻokō ʻana i ka moho kālā {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Ana"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Awelika"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Pepa Kaulike"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Pepa Kaulike o ka Lā"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Pepa Kaulike o ka Pule"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Pepa Kaulike o nā Pule ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Pepa Kaulike o ka Mahina"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Pepa Kaulike o nā Mahina ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Pepa Kaulike o ka Hapahā"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Pepa Kaulike o ka Hapalua Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Pepa Kaulike o ka Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Pepa Kaulike o nā Makahiki ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Pepa Kaulike o ka Wā"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Pepa Kaulike me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Lā me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Pule me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Pepa Kaulike o nā Pule ʻElua me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Mahina me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Pepa Kaulike o nā Mahina ʻElua me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Hapahā me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Hapalua Makahiki me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Makahiki me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Pepa Kaulike o nā Makahiki ʻElua me ke Kumu Waiwai"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Pepa Kaulike o ka Wā me ke Kumu Waiwai"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Hōʻike Kahe Kālā"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Lā"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Pule"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o nā Pule ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Mahina"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o nā Mahina ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Hapahā"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Hapalua Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o nā Makahiki ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Hōʻike Kahe Kālā o ka Wā"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Kahe kālā"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "ʻAʻole i helu ʻia nā waiwai paʻa ʻaʻohe kumukūʻai mākeke i loko o nā kumukūʻai mākeke a me nā puka: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Puka i loaʻa"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Puka i loaʻa ʻole"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Poho i loaʻa"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Poho i loaʻa ʻole"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Puka maʻemaʻe"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Kumukūʻai"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "ʻAʻohe kumukūʻai mākeke"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Kumukūʻai mākeke"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Awelika kumukūʻai"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Kumukūʻai kumu o ke ana/awelika"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Kumukūʻai kumu o ke ana"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "ʻAʻole i helu ʻia nā waiwai paʻa ʻaʻohe kumukūʻai mākeke i loko o nā huina o Huina kumukūʻai mākeke, Puka L.ʻO., Puka L.ʻO.% a me XIRR: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Ua helu ʻia i loko o nā huina o Puka L. a me XIRR he {n} kūlana pani ʻia i hōʻike ʻole ʻia"+msgstr[1] "Ua helu ʻia i loko o nā huina o Puka L. a me XIRR he {n} kūlana pani ʻia i hōʻike ʻole ʻia"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, nā puka o kēlā me kēia wā"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, nā puka mai {start} mai"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Nā Waiwai Paʻa o ka Lā"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Nā Waiwai Paʻa o ka Pule"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Nā Waiwai Paʻa o nā Pule ʻElua"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Nā Waiwai Paʻa o ka Mahina"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Nā Waiwai Paʻa o nā Mahina ʻElua"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Nā Waiwai Paʻa o ka Hapahā"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Nā Waiwai Paʻa o ka Hapalua Makahiki"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Nā Waiwai Paʻa o ka Makahiki"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Nā Waiwai Paʻa o nā Makahiki ʻElua"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Nā Waiwai Paʻa o ka Wā"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Nā Waiwai Paʻa"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Nā ana"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Kumukūʻai o ke ana"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Huina kumukūʻai"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Huina kumukūʻai mākeke"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Puka L.ʻO."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Puka L.ʻO.%"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Puka L."++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(ʻaʻohe waiwai paʻa)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Lā"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Nā waiwai paʻa ma {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Nā waiwai paʻa ma {date}, nā puka ma {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(e nānā i -E)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Lōʻihi"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Kaumaha"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Moʻokālā"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Huina:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Lā"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Pule"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o nā Pule ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Mahina"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o nā Mahina ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Hapahā"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Hapalua Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Makahiki"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o nā Makahiki ʻElua"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Hōʻike Loaʻa a me Hoʻolilo o ka Wā"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Papa Helu"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Hōʻike:"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Nā poʻo inoa"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Nā pakuhi"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "A pau"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "nā koena moʻokālā"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "nā loli moʻokālā"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "nā koena kālā"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "nā koena o ka pepa kaulike"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "nā loli o ka hōʻike loaʻa a me hoʻolilo"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Nā moʻokālā kālā"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Nā moʻokālā o ka pepa kaulike"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Nā moʻokālā o ka hōʻike loaʻa a me hoʻolilo"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Nā moʻokālā a pau"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Huina ma ke kumukūʻai:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "Ka huina o nā moʻokālā a pau, ma ke kumukūʻai. ʻAʻole he ʻole inā kaulike ʻole kekahi mea."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Huina ma ke kumukūʻai mākeke:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "Ka huina o nā moʻokālā a pau ma ke kumukūʻai mākeke. ʻAʻole he ʻole inā ua loli nā kumukūʻai a ʻaʻohe komo e kākau i ka puka a i ʻole ka poho, e laʻa me nā puka hoʻopukapuka i loaʻa ʻole."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "Ka huina o nā moʻokālā a pau. ʻAʻole he ʻole inā kaulike ʻole kekahi mea, e laʻa me nā hoʻololi me @ me ka ʻole o --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Nā koena ma {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Ke koena o kēlā me kēia moʻokālā i ka hopena o kēia lā: ka hopena o nā lā o ka huli, a i ʻole ka lā hope o ka puke moʻolelo"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Puke moʻolelo"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Hōʻike i nā komo o ka puke moʻolelo, ka mea hou loa ma mua"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Pepa kaulike"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Hōʻike i nā waiwai, nā ʻaiʻē, a me ka waiwai maʻemaʻe"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Hōʻike loaʻa a me hoʻolilo"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Hōʻike i nā loaʻa a me nā hoʻolilo"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Hōʻike kahe kālā"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Hōʻike i nā loli o nā waiwai kālā"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Hōʻike i nā waiwai paʻa hoʻopukapuka, nā pūʻulu, a me nā puka"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Hōʻike i nā koena o nā moʻokālā a pau, ma kēlā me kēia wā, e like me ke kauoha balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Ke hōʻike nei i nā hana kālā {first} a hiki i {last} o {total}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Hōʻike i ka ʻaoʻao {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "ʻAoʻao {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Hōʻike i {year} wale nō"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Kaomi me Shift e koho i nā makahiki he nui."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Wā:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Hōʻike i hoʻokahi kolamu no ka wā holoʻokoʻa"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "ʻAʻohe"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "I ka makahiki"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Hōʻike i hoʻokahi kolamu no kēlā me kēia makahiki"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "I ka hapahā"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Hōʻike i hoʻokahi kolamu no kēlā me kēia hapahā"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "I ka mahina"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Hōʻike i hoʻokahi kolamu no kēlā me kēia mahina"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "I ka pule"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Hōʻike i hoʻokahi kolamu no kēlā me kēia pule"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "I ka lā"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Hōʻike i hoʻokahi kolamu no kēlā me kēia lā"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Hōʻike i ka nui o ka loli ʻana o kēlā me kēia koena i kēlā me kēia wā"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Nā huina hōʻuluʻulu"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Hōʻike i ka loli o kēlā me kēia koena mai ka hoʻomaka ʻana o ka hōʻike (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Nā koena hope"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Hōʻike i kēlā me kēia koena ma ka hopena o kēlā me kēia wā, me nā mea a pau ma mua"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Helu:"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Hōʻike i nā huina o nā laina"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Nā huina"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Loli kumukūʻai"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Hōʻike i ka loli ʻana o nā kumukūʻai mākeke ma ka hopena o ka wā (--valuechange)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Puka i loaʻa ʻole"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Hōʻike i nā puka kumu waiwai i loaʻa ʻole: ke kumukūʻai mākeke lawe ʻia ke kumukūʻai (--gain)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Helu i nā laina ma kahi o ka hōʻuluʻulu ʻana iā lākou (--count)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Nā moʻokālā:"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Hōʻike i nā moʻokālā ma ka papa inoa (--flat)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Papa inoa"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Hōʻike i nā moʻokālā ma ke kumulāʻau (--tree)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Kumulāʻau"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Hoʻonohonoho:"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Ma ka moʻokālā"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Hoʻonohonoho i nā lālani ma ka hoʻonohonoho hōʻike ʻana o nā moʻokālā"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Ma ka nui"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Hoʻonohonoho i nā lālani ma ko lākou nui, ka mea nui loa ma mua (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Pakuhi:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Kaʻawale"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Hōʻike i nā nui o kēlā me kēia wā ma hoʻokahi kia, ma luna a ma lalo o ka ʻole (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Hui ʻia"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Hōʻike i nā ʻano moʻokālā o kēlā me kēia wā ma nā kia ma ka ʻaoʻao o kekahi i kekahi (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Hohonu {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "a pau"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "E like me ke kākau ʻia"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Kumukūʻai"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Kumukūʻai mākeke"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Nā pakeneka"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Pakuhi hui ʻia"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Huina"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Awelika"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Nā kumukūʻai i kuhi ʻia"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Hūnā ʻia nā koena ʻole"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Hōʻike ʻia nā koena ʻole"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Hōʻike ʻia nā pūʻulu"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Hōʻike ʻia nā kumukūʻai"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Hōʻike ʻia nā kūlana pani ʻia"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Hūnā ʻia nā kūlana pani ʻia"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Nā lā lua"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Hōʻike ʻia ke kumu waiwai"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "ʻAʻole hiki ke helu i nā pakeneka:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "ʻAʻole hiki ke heluhelu i ka wā hōʻike:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "ʻAʻole ʻike ʻia ka hoʻololi kālā:"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "He waiwai ko ka palena {name} i ʻike ʻole ʻia e kēia ʻaoʻao:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Helu ʻia nā loli kumukūʻai a me nā puka mai nā kumukūʻai mākeke o ka hopena o ka wā: waiho i ka palena value, a i ʻole e hoʻohana i value=end."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Hoʻohālikelike nā puka i ke kumukūʻai mākeke me ke kumukūʻai, no laila ʻaʻole hui pū me value=cost."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "No hoʻokahi lā kēia hōʻike, no laila ʻaʻole pili ʻo value=then: e hoʻohana i value=end, value=now, a i ʻole he lā."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Hōʻike i kēia hōʻike no kēia wā"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Ua hoʻohui ʻia ka hana kālā."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, kānana ʻia"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "koena - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "A pau"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Kaomi me Shift e koho i nā ʻano he nui."++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Kaomi me Shift e koho i nā ana he nui."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "ʻAʻole hiki ke hoʻouka i ka puke moʻolelo: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Ua mālama ʻia ka puke moʻolelo {file}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Hoʻoponopono i ka puke moʻolelo"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "nā waiwai paʻa - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Hōʻike i ka papa helu o kēia moʻokālā"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Hōʻike i ka papa helu o kēia waiwai paʻa"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Hōʻike i nā waiwai paʻa ma kēia lā"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "hōʻike iā lākou"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Nā puka:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "I kēlā me kēia wā"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Hōʻike i nā puka i loko o kēlā me kēia wā"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Mai ka hoʻomaka ʻana o ka hōʻike"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Hōʻike i nā puka mai ka lā hoʻomaka o ka hōʻike a hiki i ka hopena o kēlā me kēia wā"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Mai ke kūʻai ʻana mai"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Hōʻike i nā puka mai ke kūʻai ʻia ʻana mai o kēlā me kēia waiwai paʻa a hiki i ka hopena o kēlā me kēia wā"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Puke Moʻolelo"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Nā hana kālā ma {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Nā hana kālā ma {account} (me nā moʻokālā lalo ʻole)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "puke moʻolelo - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "nā moʻokālā a pau"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (me nā moʻokālā lalo ʻole)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Huina Mai ka Hoʻomaka"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Huina o ka Wā"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Kaomi e hōʻike i ke koena holo mai ka hoʻomaka ʻana o kēia wā"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Kaomi e hōʻike i ke koena holo me nā mea a pau ma mua o kēia wā"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "papa helu - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "ʻaʻohe hōʻailona"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "pepa kaulike me ke kumu waiwai - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "pepa kaulike - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "hōʻike loaʻa a me hoʻolilo - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "hōʻike kahe kālā - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "He ʻole nā koena o nā moʻokālā a pau a kēia hōʻike e hōʻike ai, a ua hūnā ʻia. Kaomi i ka z e hōʻike iā lākou."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "ʻAʻole i loaʻa nā moʻokālā o nā ʻano a kēia hōʻike e hōʻike ai. E hōʻike i nā ʻano moʻokālā, a i ʻole e hoʻohana i nā inoa moʻokālā kiʻekiʻe maʻamau o hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Pehea e ʻike ai ʻo hledger i nā ʻano moʻokālā"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "ʻAʻohe mea e kūlike me kēia huli ʻana i kēia wā."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Hewa hoʻopāʻālua: '{error}'. Inā ʻaʻole UTF-8 kāu faila, e hoʻāʻo i ka 'palapala hoʻoponopono', kahi e hoʻololi ai ka polokalamu kele pūnaewele i ka hoʻopāʻālua."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Ua hoʻouka pono ʻia ka faila {file}"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Hoʻouka i ka puke moʻolelo"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Pani"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Hoʻohui i kahi hana kālā"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Moʻokālā {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Ka nui {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "ʻAʻole pololei ke ʻano o ka lā"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Lā"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Wehewehe"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Nele ka nui"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Nele ka moʻokālā"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "ʻAʻole pololei ka waiwai: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "ʻAʻole i kūpono nā laina"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Ana"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Hōʻike / hūnā i ka pakuhi (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Pakuhi"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Hōʻike / hūnā i nā ʻikepili (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "ʻIkepili"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Hōʻike i nā koho e hoʻololi i kēia hiʻohiʻona"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Nā koho"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} {dates}"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} {dates}, kānana ʻia"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Hana kēia mau mana hoʻohana ma nā ʻaoʻao hōʻike"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Kumu o nā kumukūʻai:"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Kuhikuhi ʻia"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Helu i nā nui me nā kumukūʻai mākeke i kuhikuhi ʻia (nā kuhikuhi P) wale nō"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Me nā mea i kuhi ʻia"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Kuhi pū i nā kumukūʻai mākeke mai nā kumukūʻai o nā hana kālā (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Hohonu:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Hōʻike i ka huina wale nō (hohonu 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Hōʻike i nā moʻokālā ma nā hohonu a pau"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Hōʻike i nā moʻokālā a hiki i ka hohonu {depth}"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Nā nui:"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Hōʻike i nā nui ma nā ana i kākau ʻia ai"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Ma ke kumukūʻai"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Hōʻike i nā nui i hoʻololi ʻia i ko lākou kumukūʻai, e like me ke kākau ʻia ma nā hana kālā (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "Ma ke kumukūʻai mākeke"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Hōʻike i nā nui i hoʻololi ʻia i ko lākou kumukūʻai mākeke ma ka hopena o kēlā me kēia wā, me nā kumukūʻai mākeke (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Nā koena ʻole:"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Hūnā i nā moʻokālā he ʻole ko lākou koena"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Hūnā ʻia"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Hōʻike i nā moʻokālā he ʻole ko lākou koena"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Hōʻike ʻia"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Kumu waiwai:"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Hōʻike i nā waiwai, nā ʻaiʻē, a me ka waiwai maʻemaʻe, e like me ke kauoha balancesheet"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Hōʻike i nā waiwai, nā ʻaiʻē, a me ke kumu waiwai, e like me ke kauoha balancesheetequity"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Kūlana:"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Hōʻike i nā hana kālā o nā kūlana a pau"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "A pau"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Kaha ʻole ʻia"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Hōʻike i nā hana kālā kaha ʻole ʻia wale nō (status:)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "E kali ana"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Hōʻike i nā hana kālā e kali ana wale nō (status:!)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Paʻa"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Hōʻike i nā hana kālā paʻa wale nō (status:*)"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Nā laina:"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Hōʻike i nā laina maoli a me nā laina maoli ʻole"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "A pau"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Maoli"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Hōʻike i nā laina maoli wale nō, e like me -R (real:1)"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Maoli ʻole"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Hōʻike i nā laina maoli ʻole wale nō, nā laina i loko o nā kahaapo (real:0)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Nā kolamu hou aʻe:"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Hoʻohui i kahi kolamu me ka huina o kēlā me kēia lālani (-T)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Hoʻohui i kahi kolamu me ka awelika o kēlā me kēia lālani (-A)"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Nā helu:"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Hōʻike i nā nui"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Nā nui"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Hōʻike i kēlā me kēia nui ma ke ʻano he pakeneka o ka huina o kona kolamu (-%)"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Nā kumukūʻai:"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Hōʻike i nā nui me ko lākou kumukūʻai ʻole"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Hūnā ʻia"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Hōʻike i nā nui me nā kumukūʻai i kākau ʻia ma ka puke moʻolelo"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Hōʻike ʻia"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Nā pūʻulu:"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Hōʻuluʻulu i nā pūʻulu o kēlā me kēia moʻokālā"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Hūnā ʻia"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Hōʻike kaʻawale i kēlā me kēia pūʻulu (--lots)"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Hōʻike ʻia"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Nā kūlana pani ʻia:"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Hōʻike i nā kūlana hāmama wale nō"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Hūnā ʻia"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Hōʻike pū i nā kūlana i kūʻai holoʻokoʻa ʻia aku a me ko lākou puka i loaʻa (-E)"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Hōʻike ʻia"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Nā kumukūʻai mākeke:"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "Ma ke ana kumukūʻai"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Helu i kēlā me kēia waiwai paʻa ma kona ana kumukūʻai ponoʻī"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Hoʻololi i nā kumukūʻai mākeke a me nā kumukūʻai i ke ana o ka mākeke (-V)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "ʻAno:"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Hōʻike i nā moʻokālā o nā ʻano a pau"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "A pau"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Waiwai"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Hōʻike i nā moʻokālā waiwai wale nō (type:A)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "ʻAiʻē"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Hōʻike i nā moʻokālā ʻaiʻē wale nō (type:L)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Hōʻike i nā moʻokālā kumu waiwai wale nō (type:E)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Loaʻa"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Hōʻike i nā moʻokālā loaʻa wale nō (type:R)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Hoʻolilo"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Hōʻike i nā moʻokālā hoʻolilo wale nō (type:X)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Kālā"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Hōʻike i nā moʻokālā kālā wale nō (type:C)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Hoʻololi"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Hōʻike i nā moʻokālā hoʻololi wale nō (type:V)"++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Puka"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Hōʻike i nā moʻokālā puka kumu waiwai wale nō (type:G)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Kaulike ʻole"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Hōʻike i nā moʻokālā kaulike ʻole wale nō (type:M)"++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Papa inoa o nā ana a pau"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Ana:"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Hōʻike i nā nui ma nā ana a pau"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "A pau"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Hōʻike i nā nui ma {commodity} wale nō"++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… a me {n} hou aku"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Koho i kahi lā"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Hoʻohui i:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Mālama"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Pelu i nā moʻokālā i hoʻokahi pae hou aku"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Wehe i nā moʻokālā i hoʻokahi pae hou aku"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Hōʻike / hūnā i nā koena"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Nā koena"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Hōʻike i nā hana kālā e pili ana i kēia moʻokālā a me kona mau moʻokālā lalo"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Hōʻike i nā hana kālā e pili ana i kēia moʻokālā, akā ʻaʻole i kona mau moʻokālā lalo"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "wale nō"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Hōʻike i nā hana kālā o kēia koena"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Hōʻike i nā hana kālā o kēia huina"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Hōʻike / hūnā i ka papa ʻaoʻao (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "ʻAʻole holo hou ʻo hledger-web. Pau ia ma hope o nā minuke he ʻumikumamālima me ka ʻole o kekahi puka aniani polokalamu kele pūnaewele e hōʻike ana iā ia, a i ʻole ke hoʻōki ʻia. No ka hoʻomau ʻana, e hoʻomaka hou iā ia a e hoʻouka hou i kēia ʻaoʻao."++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Haʻalele i ka puka aniani piha"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Huli"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Kākau i nā kumu huli hledger e kānana i nā ʻikepili ma lalo"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Holoi i nā huaʻōlelo huli"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Hoʻohana i nā huaʻōlelo huli"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Hoʻokele i nā faila puke moʻolelo"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Hōʻike i ke kōkua huli a me ke kōkua laulā"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Hele i"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Kōkua"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Nā pōkole papa pihi"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "a i ʻole"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "nānā i kēia kōkua"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "hele i kekahi pākū"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "hele i ka pākū aʻe a i ʻole ka pākū ma mua"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "hoʻohui i kahi hana kālā"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "hōʻike / hūnā i ka papa ʻaoʻao"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "hoʻonohonoho i ka hohonu moʻokālā o ka papa ʻaoʻao"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "hōʻike / hūnā i nā koena o ka papa ʻaoʻao"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "hōʻike / hūnā i nā koho hōʻike"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "hōʻike / hūnā i ka pakuhi o ka hōʻike"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "koho i ke ana o ka pakuhi"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "hōʻike / hūnā i ka laina huina maʻemaʻe o ka pakuhi"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "hōʻike / hūnā i nā ʻikepili o ka hōʻike"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "hōʻike / hūnā i ka puka aniani piha"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "kau i ka palapala huli"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "holoi i ka huli"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "hoʻōki"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Nā koho hōʻike"++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "nā koena hope mai ka hoʻomaka / nā loli koena"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "i ka makahiki"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "i ka hapahā"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "i ka mahina"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "i ka pule"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "i ka lā"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "kaha ʻole ʻia"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "e kali ana"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "paʻa"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "maoli wale nō / a pau"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Palena hohonu:"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "hoʻonoho iā ia"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "hoʻēmi a hoʻonui paha iā ia"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "kumulāʻau / papa inoa"++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "ma ke kumukūʻai"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "ma ke kumukūʻai mākeke"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "hōʻike / hūnā i nā koena ʻole"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "hōʻike / hūnā i nā kikoʻī pūʻulu"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "huina"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "awelika"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "ma ka nui / ma ka hoʻonohonoho hōʻike ʻana o nā moʻokālā"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Ke kaomi hou ʻia ke pihi o kekahi koho, pio hou ia."++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Nā nīnau huli"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Pono e hoʻopuni ʻia nā kumu huli me nā hakahaka i loko o nā kaha ʻōlelo."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "kūlike me nā inoa moʻokālā"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "kūlike me nā ʻano moʻokālā (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "kūlike me nā lā"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "kūlike me ke kūlana"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "kūlike me nā helu hana kālā"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "kūlike me nā wehewehe hana kālā"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "kūlike me ka ʻāpana mea i uku ʻia o nā wehewehe"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "kūlike me ka ʻāpana manaʻo o nā wehewehe"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "kūlike me nā nui me ka hōʻailona ʻole, a i ʻole, me ka N me ka hōʻailona, nā nui me ka hōʻailona. Hiki i ka N ke loaʻa ka hōʻailona ana."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "kūlike me nā lālani hōʻike (nā moʻokālā, nā wā, nā hana kālā) ma ko lākou loli a i ʻole koena, e like me amt:. Hiki i ka N ke loaʻa ka hōʻailona ana."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "kūlike me nā kālā/nā ana. Pono e kūlike me ka hōʻailona/ka inoa holoʻokoʻa. No ke kūlike ʻana me ka hōʻailona kālā, kākau"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "kūlike me nā lepili, a i ʻole ka lepili a me ka waiwai"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "kūlike me ka maoli a i ʻole ka maoli ʻole o nā laina"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "kūlike me kekahi kahua (moʻokālā, ka nui, manaʻo, lepili, wehewehe, helu), a i ʻole me kekahi lā inā he ʻōlelo wā nō ʻo REGEX"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "kau i ka not: ma mua o kahi huaʻōlelo huli e hōʻole ai"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "kūlike me kahi nīnau boolean (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "kūlike me nā hana kālā inā kūlike kekahi laina"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "kūlike me nā hana kālā inā kūlike nā laina a pau"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "kekahi ala ʻē aʻe e hoʻonoho ai i ka palena hohonu (hiki ke hana no kēlā me kēia moʻokālā)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Kōkua hou aku:"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "Puke alakaʻi hoʻohana hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Hoʻoponopono i ka faila"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Maopopo anei ʻoe? E kākau ʻia kāu puke moʻolelo ma luna!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Kōkua no ke ʻano faila"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Hoʻi"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Hoʻohui i kahi hana kālā hou i ka puke moʻolelo"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Lā"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Wehewehe"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Moʻokālā"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Ka nui"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Hōʻike i nā komo o ka puke moʻolelo ma kēia lā"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Nā faila o kāu puke moʻolelo"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Faila"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Hoʻoponopono"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Hoʻouka"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Hoʻoiho"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Hōʻike i nā hana kālā hou aʻe"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Hou aʻe"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Hōʻike i nā hana kālā kahiko aʻe"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Kahiko aʻe"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "I/Mai ka Moʻokālā"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Ka nui Puka/Komo"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Hōʻike i kēia komo a me nā komo ʻē aʻe o ka puke moʻolelo ma kona lā"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Koena i lawe ʻia mai"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Hōʻike i nā hana kālā ma mua o kēia wā"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Hoʻouka i ka faila"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Koho i kahi faila"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Nā makahiki:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Hōʻike i nā makahiki a pau"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "A pau"++#~ msgid "Next report"+#~ msgstr "Hōʻike aʻe"++#~ msgid "Go to the next report"+#~ msgstr "Hele i ka hōʻike aʻe"++#~ msgid "Previous report"+#~ msgstr "Hōʻike ma mua"++#~ msgid "Go to the previous report"+#~ msgstr "Hele i ka hōʻike ma mua"++#~ msgid "Net, at cost:"+#~ msgstr "Maʻemaʻe, ma ke kumukūʻai:"++#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "Ka huina o nā moʻokālā a pau, ma ke kumukūʻai: he ʻole no nā puke kaulike; ʻo ke koena, no nā laina maoli ʻole kaulike ʻole ia."++#~ msgid "Unbooked gains:"+#~ msgstr "Nā puka i kākau ʻole ʻia:"++#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "Ka huina o nā moʻokālā a pau ma ke kumukūʻai mākeke: ka piʻi ʻana o ke kumukūʻai i kākau ʻole ʻia e kekahi komo. Inā kākau ʻia nā puka i loaʻa, ʻo kēia nā puka i loaʻa ʻole."++#~ msgid "Net flows:"+#~ msgstr "Kahe maʻemaʻe:"++#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "Ka huina o nā moʻokālā a pau: nā kūlana hāmama ma kēlā me kēia ana, a me ke kālā i uku ʻia no lākou. He ʻole inā ʻaʻohe mea e hele ma waena o nā ana."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Nā waiwai paʻa ma ka pau ʻana o nā manawa"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Nā waiwai paʻa ma ka pau ʻana o nā manawa, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "ʻAʻole ʻike ʻia ke ʻano hōʻuluʻulu koena:"++#~ msgid "Show only the total"+#~ msgstr "Hōʻike i ka huina wale nō"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Hōʻike i nā hana kālā e hana ai i kēia koena"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Hōʻike i nā hana kālā e hana ai i kēia huina"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "kūlike me kekahi kahua ʻike ʻia (moʻokālā, nui, manaʻo, wehewehe, helu), a i ʻole he lā inā he huaʻōlelo wā pū ʻo REGEX"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "kūlike me nā nui me ka hōʻailona ʻole, a i ʻole me ka N me ka hōʻailona, nā nui me ka hōʻailona. No nā nui ma hoʻokahi ana wale nō."
+ locale/hledger.pot view
@@ -0,0 +1,2644 @@+# Translation template for hledger.+# This file is distributed under the same license as hledger.+# "Key term" marks an entry whose mistranslation would mislead about money or data:+# use your country's standard accounting term, and review these first.+#+#, fuzzy+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: \n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr ""++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr ""++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr ""++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr ""++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr ""++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheetequity.hs hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr ""++#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr ""++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr ""++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs hledger/Hledger/Cli/Commands/Balance/Internal.hs hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr ""++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr ""++#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] ""+msgstr[1] ""++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] ""+msgstr[1] ""++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] ""+msgstr[1] ""++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr ""++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr ""++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr ""++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr ""++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr ""++#: hledger/Hledger/Cli/Commands/Balance.hs hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr ""++#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr ""++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr ""++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr ""++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr ""++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr ""++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr ""++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr ""++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr ""++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr ""++#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr ""++#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr ""++#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr ""++#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr ""++#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] ""+msgstr[1] ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr ""++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr ""++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr ""++#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr ""++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr ""++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr ""++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr ""++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr ""++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr ""++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr ""++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr ""++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr ""++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr ""++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr ""++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr ""++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr ""++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr ""++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr ""++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr ""++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr ""++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr ""++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr ""++#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr ""++#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr ""++#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr ""++#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr ""++#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr ""++#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr ""++#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr ""++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr ""++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr ""++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr ""++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr ""++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr ""++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr ""++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr ""++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr ""++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr ""++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr ""++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr ""++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr ""++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr ""++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr ""++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr ""++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr ""++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr ""++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr ""++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr ""++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr ""++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr ""++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr ""++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr ""++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr ""++#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr ""++#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr ""++#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr ""++#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr ""++#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr ""++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr ""++#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr ""++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr ""++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr ""++#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr ""++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr ""++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr ""++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr ""++#: hledger-web/Hledger/Web/Handler/BalanceR.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs hledger-web/Hledger/Web/Handler/StatementsR.hs hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr ""++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr ""++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr ""++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs hledger-web/Hledger/Web/Handler/JournalR.hs hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr ""++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs hledger-web/Hledger/Web/Handler/HoldingsR.hs hledger-web/Hledger/Web/Handler/JournalR.hs hledger-web/Hledger/Web/Handler/RegisterR.hs hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr ""++#: hledger-web/Hledger/Web/Handler/EditR.hs hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr ""++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr ""++#: hledger-web/Hledger/Web/Handler/EditR.hs hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr ""++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr ""++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr ""++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr ""++#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr ""++#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr ""++#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr ""++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr ""++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr ""++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr ""++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr ""++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr ""++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr ""++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr ""++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr ""++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr ""++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr ""++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr ""++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr ""++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr ""++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr ""++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr ""++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr ""++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr ""++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr ""++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr ""++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr ""++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr ""++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr ""++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr ""++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr ""++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr ""++#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr ""++#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr ""++#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr ""++#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr ""++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr ""++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr ""++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr ""++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr ""++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr ""++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr ""++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr ""++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr ""++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr ""++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr ""++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr ""++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr ""++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr ""++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr ""++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr ""++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr ""++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr ""++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr ""++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr ""++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr ""++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr ""++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr ""++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr ""++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr ""++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr ""++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr ""++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr ""++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr ""++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr ""++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr ""++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr ""++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr ""++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr ""++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr ""++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr ""++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr ""++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr ""++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr ""++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr ""++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr ""++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr ""++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr ""++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr ""++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr ""++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr ""++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr ""++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr ""++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr ""++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr ""++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr ""++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr ""++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr ""++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr ""++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr ""++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr ""++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr ""++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr ""++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr ""++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr ""++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr ""++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr ""++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr ""++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr ""++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr ""++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr ""++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr ""++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr ""++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr ""++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr ""++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr ""++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr ""++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr ""++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr ""++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr ""++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr ""++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr ""++#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr ""++#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr ""++#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr ""++#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr ""++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr ""++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr ""++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr ""++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr ""++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr ""++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr ""++#. Key term+#: hledger-web/templates/edit-form.hamlet hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr ""++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr ""++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr ""++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr ""++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr ""++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr ""++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr ""++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr ""++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr ""++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr ""++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr ""++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr ""++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr ""++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr ""++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr ""++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr ""++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr ""++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr ""++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr ""++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr ""++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr ""++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr ""++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr ""++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr ""++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr ""++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr ""++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr ""++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr ""
+ locale/it.po view
@@ -0,0 +1,3264 @@+# Italian translations for hledger.+# This file is distributed under the same license as hledger.+# Translators: Diego Depaoli.+# Terminology and choices to check: see hledger-lib/locale/README.md, Italian.+# Entries marked "machine-translated, please review" were added or changed by machine+# (Claude Opus 5.5) after Diego's draft.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"POT-Creation-Date: \n"+"PO-Revision-Date: \n"+"Last-Translator: \n"+"Language-Team: \n"+"Language: it\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n != 1);\n"+"X-Generator: Poedit 3.7\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Gennaio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Febbraio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Marzo"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Aprile"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Maggio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Giugno"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Luglio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Agosto"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Settembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Ottobre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Novembre"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Dicembre"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Gen"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Feb"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mar"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Apr"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Mag"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Giu"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Lug"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Ago"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Set"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Ott"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Nov"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Dic"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Dettagli del rapporto"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Totale"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Attività"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Passività"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Patrimonio netto"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Entrate"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Uscite"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Altri"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Saldo"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Totale"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Netto:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…e {n} altro"+msgstr[1] "…e altri {n}"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "altri {parent} ({n} conto)"+msgstr[1] "altri {parent} ({n} conti)"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "altri ({n} conto)"+msgstr[1] "altri ({n} conti)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Variazioni del valore a fine periodo)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Variazioni cumulative del valore a fine periodo)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Guadagno incrementale)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Guadagno cumulativo)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Guadagno storico)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Variazioni di saldo)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Saldi finali cumulativi)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Saldi finali storici)"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", al costo"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", al valore alla data del movimento"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", al valore di fine periodo"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", valore corrente"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", al valore del {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Rapporto sul budget"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Rapporto di bilancio multi periodo"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Rapporto di bilancio"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} in {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Variazioni del valore a fine periodo"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Variazioni cumulative del valore a fine periodo"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Guadagno incrementale"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Guadagno cumulativo"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Guadagno storico"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Numero di movimenti"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Numero cumulativo di movimenti"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Numero storico di movimenti"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Numero di registrazioni"++# machine-translated, please review+#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Variazioni di saldo"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Saldi finali (cumulativi)"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Saldi finali (storici)"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Performance del budget in {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Unità di conto"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Media"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Bilancio"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Bilancio giornaliero"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Bilancio settimanale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Bilancio quindicinale"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Bilancio mensile"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Bilancio bimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Bilancio trimestrale"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Bilancio semestrale"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Bilancio annuale"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Bilancio biennale"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Bilancio periodico"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Bilancio con patrimonio netto"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Bilancio giornaliero con patrimonio netto"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Bilancio settimanale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Bilancio quindicinale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Bilancio mensile con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Bilancio bimestrale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Bilancio trimestrale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Bilancio semestrale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Bilancio annuale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Bilancio biennale con patrimonio netto"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Bilancio periodico con patrimonio netto"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Rendiconto finanziario"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Rendiconto finanziario giornaliero"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Rendiconto finanziario settimanale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Rendiconto finanziario quindicinale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Rendiconto finanziario mensile"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Rendiconto finanziario bimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Rendiconto finanziario trimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Rendiconto finanziario semestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Rendiconto finanziario annuale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Rendiconto finanziario biennale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Rendiconto finanziario periodico"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Flussi di cassa"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Valori e plusvalenze escludono gli investimenti senza prezzo di mercato: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Plusvalenza realizzata"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Plusvalenza latente"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Minusvalenza realizzata"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Minusvalenza latente"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Plusvalenza netta"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Costo"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Nessun prezzo di mercato"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Valore"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Costo medio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Costo unitario/medio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Costo unitario"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "I totali di Valore totale, Plusv. lat., Plusv. lat. % e TIR escludono gli investimenti senza prezzo di mercato: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "I totali di Plusv. real. e TIR includono {n} posizione chiusa, non mostrata"+msgstr[1] "I totali di Plusv. real. e TIR includono {n} posizioni chiuse, non mostrate"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, plusvalenze di ogni periodo"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, plusvalenze dal {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Portafoglio giornaliero"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Portafoglio settimanale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Portafoglio quindicinale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Portafoglio mensile"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Portafoglio bimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Portafoglio trimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Portafoglio semestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Portafoglio annuale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Portafoglio biennale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Portafoglio periodico"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Portafoglio"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Quantità"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Prezzo unitario"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Costo totale"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Valore totale"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Plusv. lat."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Plusv. lat. %"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Plusv. real."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "TIR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(nessuna posizione)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Data"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Portafoglio al {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Portafoglio al {date}, plusvalenze in {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(vedi -E)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Età"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Peso"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Conto"++# machine-translated, please review+#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Totale:"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Conto economico"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Conto economico giornaliero"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Conto economico settimanale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Conto economico quindicinale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Conto economico mensile"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Conto economico bimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Conto economico trimestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Conto economico semestrale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Conto economico annuale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Conto economico biennale"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Conto economico periodico"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Registro"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Mostra:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Titoli"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Grafici"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Tutti"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "saldi del conto"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "variazioni del conto"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "saldi di cassa"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "saldi di bilancio"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "variazioni del conto economico"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Conti liquidità"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Conti di bilancio"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Conti del conto economico"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Tutti i conti"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Totale al costo:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "La somma di tutti i conti, convertita al costo. Diversa da zero quando qualcosa non è bilanciato."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Totale al valore di mercato:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "La somma di tutti i conti al valore di mercato. Diversa da zero quando i valori sono cambiati e nessuna registrazione rileva la plusvalenza o la minusvalenza, ad es. le plusvalenze latenti sugli investimenti."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "La somma di tutti i conti. Diversa da zero quando qualcosa non è bilanciato, ad es. le conversioni con @ senza --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Saldi al {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Il saldo di ogni conto alla fine di questo giorno: la fine delle date della ricerca, altrimenti l'ultima data del giornale"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Giornale"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Mostra le registrazioni del libro giornale, prima le più recenti"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Bilancio"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Mostra attività, passività e patrimonio netto"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Conto economico"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Mostra entrate e uscite"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Rendiconto finanziario"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Mostra le variazioni delle attività liquide"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Mostra gli investimenti in portafoglio, i lotti e le plusvalenze"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Mostra i saldi di tutti i conti, per periodo, come il comando balance"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Registrazioni da {first} a {last} di {total}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Mostra la pagina {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Pagina {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Mostra solo il {year}"++# machine-translated, please review+#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Maiusc-clic seleziona un intervallo di anni."++# machine-translated, please review+#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Intervallo:"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Mostra una sola colonna per l'intero periodo"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Nessuno"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Annuale"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Mostra una colonna per anno"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Trimestrale"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Mostra una colonna per trimestre"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Mensile"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Mostra una colonna per mese"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Settimanale"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Mostra una colonna per settimana"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Giornaliero"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Mostra una colonna per giorno"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Mostra di quanto è variato ogni saldo in ogni periodo"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Totali cumulativi"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Mostra la variazione di ogni saldo dall'inizio del rapporto (--cumulative)"++# machine-translated, please review+#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Saldi finali"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Mostra ogni saldo alla fine di ogni periodo, includendo tutto ciò che precede"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Calcola:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Mostra le somme dei movimenti"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Somme"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Variazione di valore"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Mostra come sono variati i valori di mercato di fine periodo (--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Plusvalenza latente"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Mostra le plusvalenze latenti: valore di mercato meno costo (--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Conta i movimenti invece di sommarli (--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Conti:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Mostra i conti come elenco semplice (--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Elenco"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Mostra i conti come albero (--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Albero"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Ordina:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Per conto"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Ordina le righe secondo l'ordine di visualizzazione dei conti"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Per importo"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Ordina le righe per importo, dal più grande (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Grafico:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Divergente"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Rappresenta gli importi di ogni periodo in una sola barra, sopra e sotto lo zero (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Raggruppato"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Rappresenta i tipi di conto di ogni periodo in barre affiancate (--chart=grouped)"++# machine-translated, please review+#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Profondità {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "illimitata"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Come registrati"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Costo"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Valore"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Percentuali"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Grafico raggruppato"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Totale"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Media"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Prezzi dedotti"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Saldi zero nascosti"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Saldi zero mostrati"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Lotti mostrati"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Costi mostrati"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Posizioni chiuse mostrate"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Posizioni chiuse nascoste"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Date secondarie"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Patrimonio netto mostrato"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Impossibile calcolare le percentuali:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Impossibile interpretare l'intervallo del rapporto:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Conversione degli importi sconosciuta:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Il parametro {name} ha un valore che questa pagina non conosce:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Le variazioni di valore e le plusvalenze si calcolano dai valori di mercato di fine periodo: ometti il parametro value, o usa value=end."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Le plusvalenze confrontano il valore di mercato con il costo, quindi non si combinano con value=cost."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Questo rapporto è a una sola data, quindi value=then non si applica: usa value=end, value=now o una data."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Mostra questo rapporto per questo periodo"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Registrazione aggiunta."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, filtrato"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "bilancio - hledger-web"++# machine-translated, please review+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Tutti"++# machine-translated, please review+#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Maiusc-clic seleziona più tipi."++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Maiusc-clic seleziona più unità di conto."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Impossibile caricare il giornale: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Giornale salvato {file}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Modifica il giornale"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "portafoglio - hledger-web"++# machine-translated, please review+#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Mostra il registro di questo conto"++# machine-translated, please review+#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Mostra il registro di questo investimento"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Mostra il portafoglio a questa data"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "mostrale"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Plusvalenze:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "In ogni periodo"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Mostra le plusvalenze durante ogni periodo"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Dall'inizio del rapporto"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Mostra le plusvalenze dalla data di inizio del rapporto fino alla fine di ogni periodo"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Dall'acquisto"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Mostra le plusvalenze dall'acquisto di ogni investimento fino alla fine di ogni periodo"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Giornale generale"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Registrazioni in {account}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Registrazioni in {account} (esclusi i sottoconti)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "giornale - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "tutti i conti"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (con esclusione dei sottoconti)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Totale storico"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Totale del periodo"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Clicca per mostrare il saldo progressivo dall'inizio di questo periodo"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Clicca per mostrare il saldo progressivo includendo tutto ciò che precede questo periodo"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "registro - hledger-web"++# machine-translated, please review+#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "senza simbolo"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "bilancio con patrimonio netto - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "bilancio - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "conto economico - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "rendiconto finanziario - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Tutti i conti mostrati da questo rapporto hanno saldo zero, e sono nascosti. Premi z per mostrarli."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Non sono stati trovati conti dei tipi che questo rapporto mostra. Dichiara i tipi di conto, o usa i nomi standard dei conti di primo livello di hledger. "++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Come hledger determina i tipi di conto"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "Niente corrisponde a questa ricerca in questo periodo."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Errore di codifica: '{error}'. Se il tuo file non è codificato in UTF-8, prova il 'modulo di modifica', dove la conversione dovrebbe essere gestita dal browser."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "File {file} caricato correttamente"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Carica giornale"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Chiudi"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Aggiungi una registrazione"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Conto {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Importo {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Formato data non valido"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Data"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Descrizione"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Importo mancante"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Conto mancante"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Valore non valido: {error}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Validazione dei movimenti non riuscita"++# machine-translated, please review+#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Unità di conto"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Mostra/nascondi il grafico (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Grafico"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Mostra/nascondi i dati (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Dati"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Mostra le opzioni che modificano questa vista"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Opzioni"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} {dates}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} {dates}, filtrato"++# machine-translated, please review+#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Questi controlli hanno effetto nelle pagine dei rapporti"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Prezzi:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Dichiarati"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Valuta gli importi solo con i prezzi di mercato dichiarati (direttive P)"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Anche dedotti"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Deduci i prezzi di mercato anche dai costi delle registrazioni (--infer-market-prices)"++# machine-translated, please review+#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Profondità:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Mostra solo il totale (profondità 0)"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Mostra i conti a ogni profondità"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Mostra i conti fino alla profondità {depth}"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Importi:"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Mostra gli importi nelle unità di conto in cui sono stati registrati"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Al costo"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Mostra gli importi convertiti al loro costo, come registrato nelle registrazioni (-B)"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "Al valore di mercato"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Mostra gli importi convertiti al loro valore di mercato alla fine di ogni periodo, usando i prezzi di mercato (-V)"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Saldi zero:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Nascondi i conti con saldo zero"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Nascondi"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Mostra i conti con saldo zero"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Mostra"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Patrimonio netto:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Mostra attività, passività e patrimonio netto, come il comando balancesheet"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Mostra attività, passività e patrimonio netto come sezione a sé, come il comando balancesheetequity"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Stato:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Mostra le registrazioni di qualsiasi stato"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Tutte"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Non contrassegnate"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Mostra solo le registrazioni non contrassegnate (status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "In sospeso"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Mostra solo le registrazioni in sospeso (status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Riconciliate"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Mostra solo le registrazioni riconciliate (status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Movimenti:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Mostra i movimenti reali e virtuali"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Tutti"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Reali"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Mostra solo i movimenti reali, come fa -R (real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Virtuali"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Mostra solo i movimenti virtuali, quelli tra parentesi (real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Colonne aggiuntive:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Aggiungi una colonna con il totale di ogni riga (-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Aggiungi una colonna con la media di ogni riga (-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Numeri:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Mostra gli importi"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Importi"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Mostra ogni importo come percentuale del totale della sua colonna (-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Costi:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Mostra gli importi senza i loro costi"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Nascondi"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Mostra gli importi con i costi registrati nel giornale"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Mostra"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Lotti:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Aggrega i lotti di ogni conto"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Nascondi"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Mostra ogni lotto separatamente (--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Mostra"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Posizioni chiuse:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Mostra solo le posizioni aperte"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Nascondi"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Mostra anche le posizioni interamente cedute e le loro plusvalenze realizzate (-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Mostra"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Valori:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "Per unità di costo"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Valuta ogni investimento nella sua unità di conto di costo"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Converti valori e costi nell'unità di conto di valutazione di mercato (-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Tipo:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Mostra i conti di ogni tipo"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Tutti"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Attività"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Mostra solo i conti di attività (type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Passività"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Mostra solo i conti di passività (type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Mostra solo i conti di patrimonio netto (type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Entrata"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Mostra solo i conti di entrata (type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Uscita"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Mostra solo i conti di uscita (type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Liquidità"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Mostra solo i conti di liquidità (type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Conversione"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Mostra solo i conti di conversione (type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Plusvalenza"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Mostra solo i conti di plusvalenza (type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Squilibrio"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Mostra solo i conti di squilibrio (type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Elenca tutte le unità di conto"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Unità di conto:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Mostra gli importi in tutte le unità di conto"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Tutte"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Mostra solo gli importi in {commodity}"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… e altri {n}"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Scegli una data"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Aggiungi a:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Salva"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Comprimi i conti di un altro livello"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Espandi i conti di un altro livello"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Mostra/nascondi i saldi"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Saldi"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Mostra le registrazioni che interessano questo conto e i sottoconti"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Mostra le registrazioni che interessano questo conto ma non i sottoconti"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "solo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Mostra le registrazioni che compongono questo saldo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Mostra le registrazioni che compongono questo totale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Mostra/nascondi la barra laterale (s)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web non è più in esecuzione. Si chiude dopo quindici minuti senza finestre del browser che lo mostrano, o quando viene fermato. Per continuare, riavvialo e ricarica questa pagina."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Esci da schermo intero"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Cerca"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Inserisci una chiave di ricerca per filtrare i dati sotto"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Pulisci termini ricerca"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Usa i termini di ricerca"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Gestisci i file giornale"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Mostra la ricerca e l'aiuto generale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Vai a"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Aiuto"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Scorciatoie da tastiera"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "o"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "mostra questo aiuto"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "vai a qualsiasi schermata"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "vai alla schermata successiva o precedente"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "aggiungi una registrazione"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "mostra/nascondi barra laterale"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "imposta la profondità dei conti della barra laterale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "mostra/nascondi i saldi della barra laterale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "mostra/nascondi le opzioni del rapporto"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "mostra/nascondi il grafico del rapporto"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "scegli l'unità di conto del grafico"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "mostra/nascondi la linea del totale netto del grafico"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "mostra/nascondi i dati del rapporto"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "attiva/disattiva lo schermo intero"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "focus sul form di ricerca"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "cancella la ricerca"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "annulla"++# machine-translated, please review+#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Opzioni del rapporto"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "saldi finali storici / variazioni di saldo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "annuale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "trimestrale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "mensile"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "settimanale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "giornaliero"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "non contrassegnate"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "in sospeso"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "riconciliate"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "solo reali / tutti"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Limite di profondità:"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "impostarlo"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "diminuirlo o aumentarlo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "albero / elenco"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "al costo"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "al valore di mercato"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "mostra / nascondi i saldi zero"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "mostra / nascondi i dettagli dei lotti"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "totale"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "media"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "per importo / per ordine di visualizzazione dei conti"++# machine-translated, please review+#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Premuto di nuovo, il tasto di un'opzione la disattiva."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Query di ricerca"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Le chiavi di ricerca contenenti spazi devono essere racchiuse tra virgolette."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "conti corrispondenti"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "tipi di conto corrispondenti (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "date corrispondenti"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "stato corrispondente"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "codici delle registrazioni corrispondenti"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "corrispondenza nella descrizione della registrazione"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "corrispondenza nella parte beneficiario delle descrizioni"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "corrispondenza nella parte nota delle descrizioni"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "corrispondenza con gli importi senza segno, o, con un N con segno, con gli importi con segno. N può avere un simbolo di unità di conto."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "corrispondenza con le righe del rapporto (conti, periodi, registrazioni) per variazione o saldo, come amt:. N può avere un simbolo di unità di conto."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "corrispondenza valute/commodity. Deve corrispondere l'intero simbolo/nome. Per la corrispondenza del segno del dollaro scrivi"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "corrispondenza con tags, o tag e valori"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "corrispondenza con movimenti reali/virtuali"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "corrispondenza con qualsiasi campo (conto, importo, commento, tag, descrizione, codice), o con una data se REGEX è anche un'espressione di periodo"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "inizia con not: per una ricerca negativa"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "corrispondenza con una query booleana (and, or, not, ())"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "corrispondenza con le registrazioni in cui almeno un movimento corrisponde"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "corrispondenza con le registrazioni in cui tutti i movimenti corrispondono"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "un altro modo di impostare il limite di profondità (anche per singolo conto)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Altro aiuto:"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "Manuale utente di hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Modifica file"++# machine-translated, please review+#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Sei sicuro? Questo sovrascriverà il tuo giornale!"++# machine-translated, please review+#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Aiuto sul formato del file"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Indietro"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Aggiungi una registrazione al giornale"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Data"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Descrizione"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Conto"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Importo"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Mostra le registrazioni del giornale in questa data"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "I file del tuo giornale"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "File"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Modifica"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Carica"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Scarica"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Mostra le registrazioni più recenti"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Più recenti"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Mostra le registrazioni più vecchie"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Più vecchie"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Al(i)/Dal(i) Conto(i)"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Importo uscita/entrata"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Mostra questa registrazione e le altre registrazioni del giornale nella sua data"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Saldo riportato"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Mostra le registrazioni precedenti a questo periodo"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Carica sul file"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Seleziona file"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Anni:"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Mostra tutti gli anni"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Tutti"++# machine-translated, please review+#~ msgid "Next report"+#~ msgstr "Rapporto successivo"++# machine-translated, please review+#~ msgid "Go to the next report"+#~ msgstr "Vai al rapporto successivo"++# machine-translated, please review+#~ msgid "Previous report"+#~ msgstr "Rapporto precedente"++# machine-translated, please review+#~ msgid "Go to the previous report"+#~ msgstr "Vai al rapporto precedente"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "Netto, al costo:"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "La somma di tutti i conti, al costo: zero per una contabilità in pareggio; ciò che resta viene da movimenti virtuali non bilanciati."++# machine-translated, please review+#~ msgid "Unbooked gains:"+#~ msgstr "Plusvalenze non contabilizzate:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "La somma di tutti i conti al valore di mercato: l'apprezzamento non contabilizzato da alcuna registrazione. Se le plusvalenze realizzate sono contabilizzate, queste sono le plusvalenze latenti."++# machine-translated, please review+#~ msgid "Net flows:"+#~ msgstr "Flussi netti:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "La somma di tutti i conti: le posizioni aperte in ogni unità di conto, e il denaro che le ha pagate. Zero quando nulla passa da un'unità di conto a un'altra."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Portafoglio a fine periodo"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Portafoglio a fine periodo, {dates}"++# machine-translated, please review+#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Modalità di cumulo dei saldi sconosciuta:"++# machine-translated, please review+#~ msgid "Show only the total"+#~ msgstr "Mostra solo il totale"++# machine-translated, please review+#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Mostra le registrazioni che compongono questo saldo"++# machine-translated, please review+#~ msgid "Show the transactions that make up this total"+#~ msgstr "Mostra le registrazioni che compongono questo totale"++# machine-translated, please review+#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "corrispondenza in qualsiasi campo visibile (conto, importo, commento, descrizione, codice), o in una data se REGEX è anche un'espressione di periodo"++# machine-translated, please review+#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "corrispondenza con grandezze senza segno, o, con N con segno, con importi con segno. Solo per importi in un'unica unità di conto."++#~ msgid "Balance report"+#~ msgstr "Rapporto di bilancio"++#~ msgid "Could not parse the period expression:"+#~ msgstr "Non riesco a elaborare l'espressione del periodo"++#~ msgid "Report:"+#~ msgstr "Rapporto:"++#~ msgid "Show the balance report"+#~ msgstr "Mostra il rapporto di bilancio"++#~ msgid "Show the yearly balance report"+#~ msgstr "Mostra il bilancio annuale"++#~ msgid "Show the quarterly balance report"+#~ msgstr "Mostra il bilancio quadrimestrale"++#~ msgid "Show the monthly balance report"+#~ msgstr "Mostra il bilancio mensile"++#~ msgid "Show the weekly balance report"+#~ msgstr "Mostra il bilancio settimanale"++#~ msgid "Show the daily balance report"+#~ msgstr "Mostra il bilancio giornaliero"++#~ msgid "or maybe"+#~ msgstr "o forse"++#~ msgid "view this help (escape or click to exit)"+#~ msgstr "guarda questo aiuto (esc o click pe uscire)"++#~ msgid "go to the Journal view (home)"+#~ msgstr "vai alla vista giornale (home)"++#~ msgid "add a transaction (escape to cancel)"+#~ msgstr "aggiungi una registrazione (esc per annullare)"++#~ msgid "hide empty accounts in sidebar"+#~ msgstr "nascondi i conti vuoti nella barra laterale"++#~ msgid "General"+#~ msgstr "Generale"++#~ msgid "The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts"+#~ msgstr "La vista del giornale mostra le registrazioni generali, rappresentanti i movimenti a zero tra conti gerarchici"++#~ msgid "The sidebar shows the resulting accounts and their final balances"+#~ msgstr "La barra laterale mostra i conti risultanti e il loro saldo finale"++#~ msgid "Parent account balances include subaccount balances"+#~ msgstr "Il saldo dei conti genitoru include i saldi dei sottoconti"++#~ msgid "Multiple currencies in balances are displayed one above the other"+#~ msgstr "Valute differenti nei saldi sono mostrate uan sull'altra"++#~ msgid "Click account name links to see transactions affecting that account, with running balance"+#~ msgstr "Clicca sul nome del conto per vedere le registrazioni effettuate e il saldo corrente"++#~ msgid "Click date links to see journal entries on that date"+#~ msgstr "Clicca sulal data per vedere le registrazioni del giorno"++#~ msgctxt "help heading"+#~ msgid "Search"+#~ msgstr "Cerca"++#~ msgid "match account types"+#~ msgstr "tipi di conto corrispondeni"++#~ msgid "match with a boolean query (and, or, not, (..))"+#~ msgstr "corrispondenza con un operatore boolenao (and, or, not)"++#~ msgid "clip account names at this depth"+#~ msgstr "blocca i nomi dei conti a questo livello"
+ locale/ja.po view
@@ -0,0 +1,2829 @@+# Japanese translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, Japanese.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: ja\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=1; plural=0;\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "1月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "2月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "3月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "4月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "5月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "6月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "7月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "8月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "9月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "10月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "11月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "12月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "1月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "2月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "3月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "4月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "5月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "6月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "7月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "8月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "9月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "10月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "11月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "12月"++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "レポートの詳細"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "合計"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "資産"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "負債"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "純資産"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "収益"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "費用"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "その他"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "残高"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "合計"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "純額:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…ほか {n} 件"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "{parent} のその他 ({n} 勘定科目)"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "その他 ({n} 勘定科目)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(期末評価額の増減)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(期末評価額の累計増減)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(含み損益の増減)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(含み損益の累計)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(繰越込み含み損益)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(残高の増減)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(累計期末残高)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(繰越込み期末残高)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr "、原価換算"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr "、転記日時点の時価"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr "、各期末時点の時価"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr "、現在の時価"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr "、{date} 時点の時価"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "予算レポート"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "複数期間残高レポート"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "残高レポート"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "期末評価額の増減"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "期末評価額の累計増減"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "含み損益の増減"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "含み損益の累計"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "繰越込み含み損益"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "転記件数"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "転記件数 (累計)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "転記件数 (繰越込み)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "取引件数"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "残高の増減"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "期末残高 (累計)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "期末残高 (繰越込み)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "予算実績 {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "単位"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "平均"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "日次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "週次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "隔週貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "月次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "隔月貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "四半期貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "半期貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "年次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "隔年貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "期間別貸借対照表"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "純資産を含む貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "純資産を含む日次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "純資産を含む週次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "純資産を含む隔週貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "純資産を含む月次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "純資産を含む隔月貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "純資産を含む四半期貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "純資産を含む半期貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "純資産を含む年次貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "純資産を含む隔年貸借対照表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "純資産を含む期間別貸借対照表"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "日次キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "週次キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "隔週キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "月次キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "隔月キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "四半期キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "半期キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "年次キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "隔年キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "期間別キャッシュ・フロー計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "キャッシュ・フロー"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "市場価格のない保有資産は評価額と損益に含まれません: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "実現益"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "含み益"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "実現損"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "含み損"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "純損益"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "取得原価"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "市場価格なし"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "評価額"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "平均取得原価"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "取得単価/平均"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "取得単価"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "評価額合計、含み損益、含み損益%、XIRR の合計には市場価格のない保有資産を含みません: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "実現損益と XIRR の合計には、表示されていない決済済みポジション {n} 件を含みます"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings} {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings} {dates}、各期間の損益"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings} {dates}、{start} からの損益"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "日次保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "週次保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "隔週保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "月次保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "隔月保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "四半期保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "半期保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "年次保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "隔年保有資産"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "期間別保有資産"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "保有資産"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "数量"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "単価"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "取得原価合計"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "評価額合計"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "含み損益"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "含み損益%"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "実現損益"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(保有資産なし)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "日付"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "{date} 時点の保有資産"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "{date} 時点の保有資産、{period} の損益"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(-E を参照)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "保有期間"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "比率"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "勘定科目"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "合計:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "日次損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "週次損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "隔週損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "月次損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "隔月損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "四半期損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "半期損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "年次損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "隔年損益計算書"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "期間別損益計算書"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "元帳"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "表示:"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "タイトル"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "グラフ"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "すべて"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "勘定科目の残高"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "勘定科目の増減"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "現金の残高"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "貸借対照表の残高"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "損益計算書の増減"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "現金勘定"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "貸借対照表の勘定科目"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "損益計算書の勘定科目"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "すべての勘定科目"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "原価での合計:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "全勘定科目を原価に換算した合計。釣り合っていないものがあるとゼロになりません。"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "時価での合計:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "全勘定科目の時価での合計。評価額が変わり、その損益をどの仕訳も計上していないとき (投資の含み益など) は、ゼロになりません。"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "全勘定科目の合計。釣り合っていないもの (--infer-equity なしで @ を使った換算など) があるとゼロになりません。"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "{date} 時点の残高"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "この日の終わりの各勘定科目の残高。検索の日付の終わり、なければ仕訳帳の最後の日付です"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "仕訳帳"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "仕訳帳の取引を新しい順に表示"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "貸借対照表"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "資産、負債、正味資産を表示"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "損益計算書"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "収益と費用を表示"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "キャッシュ・フロー計算書"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "流動資産の増減を表示"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "投資の保有資産、ロット、損益を表示"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "すべての勘定科目の残高を期間別に表示 (balance コマンドと同様)"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "{total} 件中 {first}〜{last} 件目の取引を表示"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "{n} ページを表示"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "{n} ページ"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "{year} 年のみ表示"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Shift キーを押しながらクリックすると年の範囲を選択できます。"++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "間隔:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "期間全体を 1 列で表示"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "なし"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "年次"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "年ごとに 1 列を表示"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "四半期"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "四半期ごとに 1 列を表示"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "月次"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "月ごとに 1 列を表示"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "週次"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "週ごとに 1 列を表示"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "日次"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "日ごとに 1 列を表示"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "各期間に各残高がどれだけ増減したかを表示"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "累計"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "レポート開始時点からの各残高の増減を表示 (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "期末残高"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "各期末の残高を、それ以前のすべてを含めて表示"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "計算:"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "転記の合計を表示"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "合計"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "評価額の増減"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "各期末の時価の増減を表示 (--valuechange)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "含み損益"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "未実現のキャピタルゲイン (時価 - 原価) を表示 (--gain)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "転記を合計せずに件数を数える (--count)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "勘定科目:"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "勘定科目をフラットなリストで表示 (--flat)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "リスト"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "勘定科目をツリーで表示 (--tree)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "ツリー"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "並べ替え:"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "勘定科目順"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "行を勘定科目の表示順に並べ替え"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "金額順"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "行を金額の大きい順に並べ替え (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "グラフ:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "上下振り分け"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "各期間の金額をゼロの上下に分けて 1 本の棒で表示 (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "グループ化"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "各期間の勘定科目タイプを横に並べた棒で表示 (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "深さ {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "無制限"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "記録どおり"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "原価"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "時価"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "割合"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "グループ化したグラフ"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "合計"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "平均"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "推定価格"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "ゼロ残高を非表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "ゼロ残高を表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "ロットを表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "原価を表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "決済済みポジションを表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "決済済みポジションを非表示"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "第 2 日付"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "純資産を表示"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "割合を計算できませんでした:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "レポート間隔を解析できませんでした:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "不明な金額の換算方法:"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "{name} パラメータに、このページが認識しない値があります:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "評価額の増減と損益は各期末の時価から算出されます。value パラメータを外すか、value=end を使ってください。"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "損益は時価と原価を比較するため、value=cost とは併用できません。"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "このレポートは単一の日付のものなので、value=then は使えません。value=end、value=now、または日付を使ってください。"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "この期間のこのレポートを表示"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "取引を追加しました。"++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}、絞り込み済み"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "残高 - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "すべて"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Shift キーを押しながらクリックすると複数の種類を選択できます。"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Shift キーを押しながらクリックすると複数の単位を選択できます。"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "ジャーナルを読み込めませんでした: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "ジャーナル {file} を保存しました"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "ジャーナルを編集"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "保有資産 - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "この勘定科目の元帳を表示"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "この保有資産の元帳を表示"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "この日付の保有資産を表示"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "表示する"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "損益:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "各期間"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "各期間中の損益を表示"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "レポート開始から"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "レポートの開始日から各期間の終わりまでの損益を表示"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "取得から"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "各保有資産の取得から各期間の終わりまでの損益を表示"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "仕訳帳"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "{account} の取引"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "{account} の取引 (下位勘定科目を除く)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "仕訳帳 - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "すべての勘定科目"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (下位勘定科目を除く)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "繰越込み合計"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "期間合計"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "クリックすると、この期間の開始時点からの累計残高を表示します"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "クリックすると、この期間より前のすべてを含む累計残高を表示します"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "元帳 - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "記号なし"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "純資産を含む貸借対照表 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "貸借対照表 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "損益計算書 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "キャッシュ・フロー計算書 - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "このレポートに表示される勘定科目の残高はすべてゼロのため、非表示になっています。z キーを押すと表示されます。"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "このレポートが表示する種類の勘定科目が見つかりませんでした。勘定科目の種類を宣言するか、hledger の標準の最上位勘定科目名を使ってください。 "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "hledger が勘定科目の種類を判断する方法"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "この期間に、この検索に一致するものはありません。"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "エンコーディングエラー: '{error}'。ファイルが UTF-8 でない場合は、ブラウザが文字コードを変換する「編集フォーム」を試してください。"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "ファイル {file} をアップロードしました"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "ジャーナルをアップロード"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "閉じる"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "取引を追加"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "勘定科目 {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "金額 {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "日付の形式が正しくありません"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "日付"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "摘要"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "金額がありません"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "勘定科目がありません"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "無効な値: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "転記の検証に失敗しました"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "単位"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "グラフの表示/非表示 (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "グラフ"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "データの表示/非表示 (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "データ"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "この表示を変更するオプションを表示"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "オプション"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} {dates}"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} {dates}、絞り込み済み"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "これらの設定はレポートページで有効になります"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "価格:"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "宣言済み"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "宣言された市場価格 (P ディレクティブ) のみで金額を評価"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "推定も使用"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "取引の原価からも市場価格を推定 (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "深さ:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "合計のみを表示 (深さ 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "すべての深さの勘定科目を表示"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "深さ {depth} までの勘定科目を表示"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "金額:"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "記録された単位のまま金額を表示"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "原価で"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "取引に記録された原価に換算して金額を表示 (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "時価で"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "市場価格を使い、各期末の時価に換算して金額を表示 (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "ゼロ残高:"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "残高がゼロの勘定科目を非表示"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "非表示"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "残高がゼロの勘定科目を表示"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "表示"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "純資産:"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "資産、負債、正味資産を表示 (balancesheet コマンドと同様)"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "資産、負債、純資産を表示 (balancesheetequity コマンドと同様)"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "ステータス:"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "すべてのステータスの取引を表示"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "すべて"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "未マーク"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "未マークの取引のみ表示 (status:)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "保留"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "保留中の取引のみ表示 (status:!)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "確定"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "確定済みの取引のみ表示 (status:*)"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "転記:"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "実転記と仮想転記を表示"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "すべて"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "実転記"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "実転記のみ表示 (-R と同様、real:1)"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "仮想転記"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "仮想転記 (括弧で囲まれたもの) のみ表示 (real:0)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "追加の列:"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "各行の合計列を追加 (-T)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "各行の平均列を追加 (-A)"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "数値:"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "金額を表示"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "金額"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "各金額を列の合計に対する割合で表示 (-%)"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "原価:"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "原価なしで金額を表示"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "非表示"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "ジャーナルに記録された原価付きで金額を表示"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "表示"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "ロット:"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "各勘定科目のロットをまとめる"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "非表示"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "各ロットを個別に表示 (--lots)"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "表示"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "決済済みポジション:"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "未決済のポジションのみ表示"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "非表示"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "すべて処分済みのポジションとその実現損益も表示 (-E)"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "表示"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "評価:"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "原価の単位ごと"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "各保有資産をそれぞれの原価の単位で評価"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "評価額と原価を時価評価の単位に換算 (-V)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "種類:"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "すべての種類の勘定科目を表示"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "すべて"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "資産"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "資産勘定のみ表示 (type:A)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "負債"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "負債勘定のみ表示 (type:L)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "純資産勘定のみ表示 (type:E)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "収益"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "収益勘定のみ表示 (type:R)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "費用"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "費用勘定のみ表示 (type:X)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "現金"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "現金勘定のみ表示 (type:C)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "換算"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "換算勘定のみ表示 (type:V)"++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "損益"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "キャピタルゲイン勘定のみ表示 (type:G)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "不一致"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "不一致勘定のみ表示 (type:M)"++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "すべての単位を一覧表示"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "単位:"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "すべての単位の金額を表示"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "すべて"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "{commodity} の金額のみ表示"++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "…ほか {n} 件"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "日付を選択"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "追加先:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "保存"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "勘定科目をもう 1 階層折りたたむ"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "勘定科目をもう 1 階層展開"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "残高の表示/非表示"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "残高"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "この勘定科目と下位勘定科目に関わる取引を表示"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "この勘定科目に関わる取引を表示 (下位勘定科目を除く)"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "のみ"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "この残高の元になる取引を表示"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "この合計の元になる取引を表示"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "サイドバーの表示/非表示 (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web は実行されていません。表示しているブラウザウィンドウがない状態が 15 分続くか、停止されると終了します。続けるには、もう一度起動してこのページを再読み込みしてください。"++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "全画面表示を終了"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "検索"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "hledger の検索パターンを入力して、下のデータを絞り込みます"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "検索条件をクリア"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "検索条件を適用"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "ジャーナルファイルを管理"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "検索と全般のヘルプを表示"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "移動"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "ヘルプ"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "キーボードショートカット"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "または"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "このヘルプを表示"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "任意の画面へ移動"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "次または前の画面へ移動"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "取引を追加"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "サイドバーの切り替え"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "サイドバーの勘定科目の深さを設定"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "サイドバーの残高の切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "レポートオプションの切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "レポートのグラフの切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "グラフの単位を選択"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "グラフの純額の線の切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "レポートのデータの切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "全画面表示の切り替え"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "検索フォームにフォーカス"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "検索をクリア"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "キャンセル"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "レポートオプション"++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "繰越込み期末残高 / 残高の増減"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "年次"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "四半期"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "月次"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "週次"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "日次"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "未マーク"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "保留"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "確定"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "実転記のみ / すべて"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "深さの上限:"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "設定する"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "減らす、または増やす"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "ツリー / リスト"++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "原価で"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "時価で"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "ゼロ残高の表示 / 非表示"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "ロットの詳細の表示 / 非表示"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "合計"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "平均"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "金額順 / 勘定科目の表示順"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "オプションのキーをもう一度押すと、オフに戻ります。"++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "検索クエリ"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "スペースを含む検索パターンは引用符で囲んでください。"++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "勘定科目名に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "勘定科目の種類に一致 (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "日付に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "ステータスに一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "取引コードに一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "取引の摘要に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "摘要の取引先部分に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "摘要のメモ部分に一致"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "符号なしの大きさに一致。N に符号があれば符号付きの金額に一致。N には単位記号を付けられます。"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "レポートの行 (勘定科目、期間、取引) に増減額または残高で一致 (amt: と同様)。N には単位記号を付けられます。"++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "通貨・単位に一致。記号・名前の全体に一致する必要があります。ドル記号に一致させるには次のように書きます"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "タグ、またはタグと値に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "転記が実か仮想かに一致"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "任意のフィールド (勘定科目、金額、コメント、タグ、説明、コード) に一致。REGEX が期間式でもあれば日付にも一致"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "検索語の前に not: を付けると否定になります"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "論理式のクエリで一致 (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "いずれかの転記が一致する取引に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "すべての転記が一致する取引に一致"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "深さの上限を設定する別の方法 (勘定科目ごとに指定可)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "その他のヘルプ:"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "hledger-web ユーザーマニュアル"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "ファイルを編集"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "よろしいですか? ジャーナルが上書きされます!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "ファイル形式のヘルプ"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "戻る"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "ジャーナルに新しい取引を追加"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "日付"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "摘要"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "勘定科目"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "金額"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "この日付の仕訳を表示"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "ジャーナルのファイル"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "ファイル"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "編集"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "アップロード"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "ダウンロード"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "新しい取引を表示"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "新しい方"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "古い取引を表示"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "古い方"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "相手勘定科目"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "出金/入金"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "この仕訳と、同じ日付の他の仕訳を表示"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "前期繰越"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "この期間より前の取引を表示"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "ファイルにアップロード"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "ファイルを選択"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "年:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "すべての年を表示"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "すべて"++#~ msgid "Next report"+#~ msgstr "次のレポート"++#~ msgid "Go to the next report"+#~ msgstr "次のレポートへ移動"++#~ msgid "Previous report"+#~ msgstr "前のレポート"++#~ msgid "Go to the previous report"+#~ msgstr "前のレポートへ移動"++#~ msgid "Net, at cost:"+#~ msgstr "純額 (原価):"++#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "全勘定科目の原価換算での合計。帳簿が釣り合っていればゼロになり、残りは釣り合っていない仮想転記によるものです。"++#~ msgid "Unbooked gains:"+#~ msgstr "未計上の損益:"++#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "全勘定科目の時価での合計。どの仕訳にも計上されていない評価損益です。実現損益を計上している場合、これが含み損益になります。"++#~ msgid "Net flows:"+#~ msgstr "純フロー:"++#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "全勘定科目の合計。各単位の未決済ポジションと、その支払いに使った現金です。単位をまたぐものがなければゼロになります。"++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "各期末時点の保有資産"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "各期末時点の保有資産, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "不明な残高の累積方法:"++#~ msgid "Show only the total"+#~ msgstr "合計のみ表示"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "この残高を構成する取引を表示"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "この合計を構成する取引を表示"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "表示される任意のフィールド (勘定科目、金額、コメント、摘要、コード) に一致。REGEX が期間式でもある場合は日付に一致"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "符号なしの大きさに一致。N に符号を付けると符号付きの金額に一致。単一単位の金額のみ。"
+ locale/pt-BR.po view
@@ -0,0 +1,2833 @@+# Brazilian Portuguese translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, Brazilian Portuguese.+# Machine-made (Claude Opus 5.5); not yet checked by a native speaker.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: pt-BR\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=2; plural=(n > 1);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Janeiro"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Fevereiro"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Março"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Abril"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Maio"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Junho"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Julho"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Agosto"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Setembro"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Outubro"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Novembro"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Dezembro"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Jan"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Fev"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Mar"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Abr"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Mai"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Jun"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Jul"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Ago"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Set"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Out"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Nov"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Dez"++#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Detalhes do relatório"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Total"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Ativos"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Passivos"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Patrimônio Líquido"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Receitas"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Despesas"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Outras"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Saldo"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Total"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Líquido:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…e mais {n}"+msgstr[1] "…e mais {n}"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "outras {parent} ({n} conta)"+msgstr[1] "outras {parent} ({n} contas)"++#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "outras ({n} conta)"+msgstr[1] "outras ({n} contas)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Variações de valor no fim do período)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Variações acumuladas de valor no fim do período)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Ganho do período)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Ganho acumulado)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Ganho histórico)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Variações de saldo)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Saldos finais acumulados)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Saldos finais históricos)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", pelo custo"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", pelo valor de mercado na data da partida"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", pelo valor de mercado no fim de cada período"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", pelo valor de mercado atual"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", pelo valor de mercado em {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Relatório de orçamento"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Relatório de saldos de vários períodos"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Relatório de saldos"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Variações de valor no fim do período"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Variações acumuladas de valor no fim do período"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Ganho do período"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Ganho acumulado"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Ganho histórico"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Número de partidas"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Número acumulado de partidas"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Número histórico de partidas"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Número de transações"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Variações de saldo"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Saldos finais (acumulados)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Saldos finais (históricos)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Execução do orçamento {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Unidade"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Média"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Balanço Patrimonial"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Balanço Patrimonial Diário"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Balanço Patrimonial Semanal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Balanço Patrimonial Quinzenal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Balanço Patrimonial Mensal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Balanço Patrimonial Bimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Balanço Patrimonial Trimestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Balanço Patrimonial Semestral"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Balanço Patrimonial Anual"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Balanço Patrimonial Bienal"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Balanço Patrimonial Periódico"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Balanço Patrimonial com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Balanço Patrimonial Diário com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Semanal com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Quinzenal com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Mensal com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Bimestral com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Trimestral com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Semestral com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Balanço Patrimonial Anual com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Balanço Patrimonial Bienal com Patrimônio Líquido"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Balanço Patrimonial Periódico com Patrimônio Líquido"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Demonstração dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Demonstração Diária dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Demonstração Semanal dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Demonstração Quinzenal dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Demonstração Mensal dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Demonstração Bimestral dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Demonstração Trimestral dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Demonstração Semestral dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Demonstração Anual dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Demonstração Bienal dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Demonstração Periódica dos Fluxos de Caixa"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Fluxos de caixa"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Os valores de mercado e os ganhos excluem os investimentos sem preço de mercado: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Ganho realizado"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Ganho não realizado"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Perda realizada"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Perda não realizada"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Ganho líquido"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Custo"++#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Sem preço de mercado"++#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Valor de mercado"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Custo médio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Custo unitário/médio"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Custo unitário"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Os totais de Valor de mercado total, Ganho NR, Ganho NR % e TIR excluem os investimentos sem preço de mercado: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Os totais de Ganho R e TIR incluem {n} posição encerrada, não mostrada"+msgstr[1] "Os totais de Ganho R e TIR incluem {n} posições encerradas, não mostradas"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, ganhos de cada período"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, ganhos desde {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Carteira Diária"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Carteira Semanal"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Carteira Quinzenal"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Carteira Mensal"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Carteira Bimestral"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Carteira Trimestral"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Carteira Semestral"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Carteira Anual"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Carteira Bienal"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Carteira Periódica"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Carteira"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Quantidade"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Preço unitário"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Custo total"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Valor de mercado total"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Ganho NR"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Ganho NR %"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Ganho R"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "TIR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(sem posições)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Data"++#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Carteira em {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Carteira em {date}, ganhos em {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(veja -E)"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Idade"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Peso"++#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Conta"++#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Total:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Demonstração do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Demonstração Diária do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Demonstração Semanal do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Demonstração Quinzenal do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Demonstração Mensal do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Demonstração Bimestral do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Demonstração Trimestral do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Demonstração Semestral do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Demonstração Anual do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Demonstração Bienal do Resultado"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Demonstração Periódica do Resultado"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Extrato"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Mostrar:"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Títulos"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Gráficos"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Todos"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "saldos das contas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "variações das contas"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "saldos de caixa"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "saldos do balanço patrimonial"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "variações da demonstração do resultado"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Contas de caixa"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Contas do balanço patrimonial"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Contas da demonstração do resultado"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Todas as contas"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Total pelo custo:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "A soma de todas as contas, convertida pelo custo. Diferente de zero quando algo está desequilibrado."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Total pelo valor de mercado:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "A soma de todas as contas pelo valor de mercado. Diferente de zero quando os valores mudaram e nenhum lançamento registra o ganho ou a perda, por ex. ganhos não realizados de investimentos."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "A soma de todas as contas. Diferente de zero quando algo está desequilibrado, por ex. conversões com @ sem --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Saldos em {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "O saldo de cada conta no fim deste dia: o fim das datas da busca, ou então a última data do diário"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Livro diário"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Mostrar os lançamentos do livro diário, os mais recentes primeiro"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Balanço patrimonial"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Mostrar ativos, passivos e patrimônio líquido"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Demonstração do resultado"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Mostrar receitas e despesas"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Demonstração dos fluxos de caixa"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Mostrar as variações dos ativos líquidos"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Mostrar os investimentos na carteira, os lotes e os ganhos"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Mostrar os saldos de todas as contas, por período, como o comando balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Mostrando as transações {first} a {last} de {total}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Mostrar a página {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Página {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Mostrar só {year}"++#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Shift-clique seleciona um intervalo de anos."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Intervalo:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Mostrar uma coluna para o período inteiro"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Nenhum"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Anual"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Mostrar uma coluna por ano"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Trimestral"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Mostrar uma coluna por trimestre"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Mensal"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Mostrar uma coluna por mês"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Semanal"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Mostrar uma coluna por semana"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Diário"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Mostrar uma coluna por dia"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Mostrar quanto cada saldo variou em cada período"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Totais acumulados"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Mostrar a variação de cada saldo desde o início do relatório (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Saldos finais"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Mostrar cada saldo no fim de cada período, incluindo tudo o que veio antes"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Calcular:"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Mostrar somas das partidas"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Somas"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Variação de valor"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Mostrar como os valores de mercado no fim do período variaram (--valuechange)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Ganho não realizado"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Mostrar ganhos de capital não realizados: valor de mercado menos custo (--gain)"++#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Contar as partidas em vez de somá-las (--count)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Contas:"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Mostrar as contas em lista simples (--flat)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Lista"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Mostrar as contas em árvore (--tree)"++#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Árvore"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Ordenar:"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "Por conta"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Ordenar as linhas pela ordem de exibição das contas"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "Por valor"++#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Ordenar as linhas pelos seus valores, do maior para o menor (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Gráfico:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Divergente"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Mostrar os valores de cada período em uma só barra, acima e abaixo de zero (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Agrupado"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Mostrar os tipos de conta de cada período em barras lado a lado (--chart=grouped)"++#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Profundidade {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "ilimitada"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Como registrados"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "Custo"++#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "Valor de mercado"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Porcentagens"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Gráfico agrupado"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Total"++#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Média"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Preços inferidos"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Saldos zero ocultos"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Saldos zero mostrados"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Lotes mostrados"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Custos mostrados"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Posições encerradas mostradas"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Posições encerradas ocultas"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Datas secundárias"++#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Patrimônio líquido mostrado"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Não foi possível calcular as porcentagens:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Não foi possível interpretar o intervalo do relatório:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Conversão de valores desconhecida:"++#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "O parâmetro {name} tem um valor que esta página não conhece:"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "As variações de valor e os ganhos são calculados a partir dos valores de mercado no fim do período: omita o parâmetro value, ou use value=end."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Os ganhos comparam o valor de mercado com o custo, por isso não se combinam com value=cost."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Este relatório é de uma única data, por isso value=then não se aplica: use value=end, value=now ou uma data."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Mostrar este relatório para este período"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Transação adicionada."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, com filtro"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "saldos - hledger-web"++#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Todas"++#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Shift-clique seleciona vários tipos."++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Shift-clique seleciona várias unidades."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Falha ao carregar o diário: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Diário {file} salvo"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Editar o diário"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "carteira - hledger-web"++#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Mostrar o extrato desta conta"++#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Mostrar o extrato deste investimento"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Mostrar a carteira nesta data"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "mostrá-las"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Ganhos:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "Em cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Mostrar os ganhos durante cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Desde o início do relatório"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Mostrar os ganhos desde a data de início do relatório até o fim de cada período"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Desde a aquisição"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Mostrar os ganhos desde a aquisição de cada investimento até o fim de cada período"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Livro Diário"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Transações em {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Transações em {account} (sem subcontas)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "livro diário - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "todas as contas"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (sem subcontas)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Total histórico"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Total do período"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Clique para mostrar o saldo corrente desde o início deste período"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Clique para mostrar o saldo corrente incluindo tudo o que veio antes deste período"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "extrato - hledger-web"++#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "sem símbolo"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "balanço patrimonial com patrimônio líquido - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "balanço patrimonial - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "demonstração do resultado - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "demonstração dos fluxos de caixa - hledger-web"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Todas as contas que este relatório mostra têm saldo zero, e estão ocultas. Pressione z para mostrá-las."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Não foram encontradas contas dos tipos que este relatório mostra. Declare os tipos de conta, ou use os nomes padrão de contas de nível superior do hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Como o hledger determina os tipos de conta"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "Nada corresponde a esta busca neste período."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Erro de codificação: '{error}'. Se o seu arquivo não está em UTF-8, experimente o 'formulário de edição', onde o navegador deve tratar a conversão da codificação."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Arquivo {file} enviado"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Enviar um diário"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Fechar"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Adicionar uma transação"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Conta {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Valor {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Formato de data inválido"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Data"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Descrição"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Valor ausente"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Conta ausente"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Valor inválido: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Falha na validação das partidas"++#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Unidade"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Mostrar / ocultar o gráfico (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Gráfico"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Mostrar / ocultar os dados (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Dados"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Mostrar as opções que alteram esta visão"++#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Opções"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} {dates}"++#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} {dates}, com filtro"++#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Estes controles têm efeito nas páginas de relatório"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Preços:"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Declarados"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Avaliar os valores só com os preços de mercado declarados (diretivas P)"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "Também inferidos"++#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Inferir preços de mercado também a partir dos custos das transações (--infer-market-prices)"++#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Profundidade:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Mostrar só o total (profundidade 0)"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Mostrar contas em todas as profundidades"++#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Mostrar contas até a profundidade {depth}"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Valores:"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Mostrar os valores nas unidades em que foram registrados"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "Pelo custo"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Mostrar os valores convertidos ao seu custo, como registrado nas transações (-B)"++#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "Pelo valor de mercado"++#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Mostrar os valores convertidos ao seu valor de mercado no fim de cada período, usando preços de mercado (-V)"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Saldos zero:"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Ocultar as contas cujo saldo é zero"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Ocultos"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Mostrar as contas cujo saldo é zero"++#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Mostrados"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Patrimônio líquido:"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Mostrar ativos, passivos e patrimônio líquido, como o comando balancesheet"++#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Mostrar ativos, passivos e patrimônio líquido em contas próprias, como o comando balancesheetequity"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Situação:"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Mostrar transações de qualquer situação"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Todas"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Não marcadas"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Mostrar só as transações não marcadas (status:)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Pendentes"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Mostrar só as transações pendentes (status:!)"++#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Conciliadas"++#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Mostrar só as transações conciliadas (status:*)"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Partidas:"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Mostrar partidas reais e virtuais"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Todas"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Reais"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Mostrar só as partidas reais, como -R (real:1)"++#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Virtuais"++#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Mostrar só as partidas virtuais, as entre parênteses (real:0)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Colunas extras:"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Adicionar uma coluna com o total de cada linha (-T)"++#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Adicionar uma coluna com a média de cada linha (-A)"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Números:"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Mostrar os valores"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Valores"++#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Mostrar cada valor como porcentagem do total da sua coluna (-%)"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Custos:"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Mostrar os valores sem os seus custos"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Ocultos"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Mostrar os valores com os custos registrados no diário"++#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Mostrados"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Lotes:"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Agregar os lotes de cada conta"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Ocultos"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Mostrar cada lote separadamente (--lots)"++#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Mostrados"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Posições encerradas:"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Mostrar só as posições em aberto"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Ocultas"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Mostrar também as posições totalmente alienadas e os seus ganhos realizados (-E)"++#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Mostradas"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Valores de mercado:"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "Por unidade de custo"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Avaliar cada investimento na sua própria unidade de custo"++#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Converter valores de mercado e custos para a unidade de avaliação de mercado (-V)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Tipo:"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Mostrar contas de todos os tipos"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Todos"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Ativo"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Mostrar só as contas de ativo (type:A)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Passivo"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Mostrar só as contas de passivo (type:L)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Mostrar só as contas de patrimônio líquido (type:E)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Receita"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Mostrar só as contas de receita (type:R)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Despesa"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Mostrar só as contas de despesa (type:X)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Caixa"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Mostrar só as contas de caixa (type:C)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Conversão"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Mostrar só as contas de conversão (type:V)"++#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Ganho"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Mostrar só as contas de ganho de capital (type:G)"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Desequilíbrio"++#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Mostrar só as contas de desequilíbrio (type:M)"++#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Listar todas as unidades"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Unidade:"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Mostrar valores em todas as unidades"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Todas"++#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Mostrar só os valores em {commodity}"++#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… e mais {n}"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Escolher uma data"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Adicionar a:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Salvar"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Recolher as contas mais um nível"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Expandir as contas mais um nível"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Mostrar / ocultar os saldos"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Saldos"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Mostrar as transações que afetam esta conta e as suas subcontas"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Mostrar as transações que afetam esta conta, mas não as suas subcontas"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "só"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Mostrar as transações que compõem este saldo"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Mostrar as transações que compõem este total"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Mostrar / ocultar a barra lateral (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "O hledger-web não está mais em execução. Ele encerra depois de quinze minutos sem nenhuma janela do navegador mostrando-o, ou quando é parado. Para continuar, inicie-o de novo e recarregue esta página."++#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Sair da tela cheia"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Buscar"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Digite padrões de busca do hledger para filtrar os dados abaixo"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Limpar os termos de busca"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Aplicar os termos de busca"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Gerenciar os arquivos do diário"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Mostrar a ajuda de busca e a ajuda geral"++#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Ir para"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Ajuda"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Atalhos de teclado"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "ou"++#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "ver esta ajuda"++#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "ir para qualquer tela"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "ir para a tela seguinte ou anterior"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "adicionar uma transação"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "mostrar / ocultar a barra lateral"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "definir a profundidade das contas da barra lateral"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "mostrar / ocultar os saldos da barra lateral"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "mostrar / ocultar as opções do relatório"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "mostrar / ocultar o gráfico do relatório"++#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "escolher a unidade do gráfico"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "mostrar / ocultar a linha do total líquido do gráfico"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "mostrar / ocultar os dados do relatório"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "entrar / sair da tela cheia"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "ir para o formulário de busca"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "limpar a busca"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "cancelar"++#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Opções do relatório"++#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "saldos finais históricos / variações de saldo"++#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "anual"++#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "trimestral"++#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "mensal"++#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "semanal"++#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "diário"++#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "não marcadas"++#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "pendentes"++#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "conciliadas"++#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "só reais / todas"++#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Limite de profundidade:"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "defini-lo"++#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "diminuí-lo ou aumentá-lo"++#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "árvore / lista"++#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "pelo custo"++#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "pelo valor de mercado"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "mostrar / ocultar saldos zero"++#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "mostrar / ocultar os detalhes dos lotes"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "total"++#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "média"++#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "por valor / pela ordem de exibição das contas"++#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Pressionada de novo, a tecla de uma opção a desativa."++#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Consultas de busca"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Padrões de busca com espaços devem ficar entre aspas."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "corresponder a nomes de conta"++#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "corresponder a tipos de conta (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "corresponder a datas"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "corresponder à situação"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "corresponder a códigos de transação"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "corresponder a descrições de transação"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "corresponder à parte do favorecido das descrições"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "corresponder à parte da nota das descrições"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "corresponder a valores sem sinal, ou, com um N com sinal, a valores com sinal. N pode ter um símbolo de unidade."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "corresponder a linhas do relatório (contas, períodos, transações) pela variação ou pelo saldo, como amt:. N pode ter um símbolo de unidade."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "corresponder a moedas/unidades. Deve corresponder ao símbolo/nome inteiro. Para o cifrão, escreva"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "corresponder a etiquetas, ou a uma etiqueta e seu valor"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "corresponder ao caráter real/virtual das partidas"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "corresponder a qualquer campo (conta, valor, comentário, etiqueta, descrição, código), ou a uma data se REGEX também for uma expressão de período"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "prefixe com not: para negar um termo de busca"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "corresponder a uma consulta booleana (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "corresponder a transações em que alguma partida corresponde"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "corresponder a transações em que todas as partidas correspondem"++#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "outra forma de definir o limite de profundidade (pode ser por conta)"++#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Mais ajuda:"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "Manual do usuário do hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Editar o arquivo"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Tem certeza? Isto vai sobrescrever o seu diário!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Ajuda sobre o formato de arquivo"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Voltar"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Adicionar uma nova transação ao diário"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Data"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Descrição"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Conta"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Valor"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Mostrar os lançamentos do diário nesta data"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Os arquivos do seu diário"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Arquivo"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Editar"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Enviar"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Baixar"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Mostrar as transações mais recentes"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Mais recentes"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Mostrar as transações mais antigas"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Mais antigas"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Para/de conta(s)"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Valor saída/entrada"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Mostrar este lançamento e os outros lançamentos do diário na sua data"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Saldo anterior"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Mostrar as transações anteriores a este período"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Enviar para o arquivo"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Escolher um arquivo"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Anos:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Mostrar todos os anos"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Todos"++#~ msgid "Next report"+#~ msgstr "Próximo relatório"++#~ msgid "Go to the next report"+#~ msgstr "Ir para o próximo relatório"++#~ msgid "Previous report"+#~ msgstr "Relatório anterior"++#~ msgid "Go to the previous report"+#~ msgstr "Ir para o relatório anterior"++#~ msgid "Net, at cost:"+#~ msgstr "Líquido, pelo custo:"++#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "A soma de todas as contas, pelo custo: zero para uma contabilidade equilibrada; o que sobra vem de partidas virtuais desequilibradas."++#~ msgid "Unbooked gains:"+#~ msgstr "Ganhos não lançados:"++#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "A soma de todas as contas pelo valor de mercado: a valorização que nenhum lançamento registrou. Se os ganhos realizados forem lançados, estes são os ganhos não realizados."++#~ msgid "Net flows:"+#~ msgstr "Fluxos líquidos:"++#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "A soma de todas as contas: as posições em aberto em cada unidade, e o dinheiro que as pagou. Zero quando nada passa de uma unidade para outra."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Carteira ao fim de cada período"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Carteira ao fim de cada período, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Modo de acumulação de saldo desconhecido:"++#~ msgid "Show only the total"+#~ msgstr "Mostrar só o total"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Mostrar as transações que compõem este saldo"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Mostrar as transações que compõem este total"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "corresponder a qualquer campo visível (conta, valor, comentário, descrição, código), ou a uma data se REGEX também for uma expressão de período"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "corresponder a valores sem sinal, ou, com um N com sinal, a valores com sinal. Só para valores de uma única unidade."
+ locale/ru.po view
@@ -0,0 +1,3148 @@+# Russian translations for hledger.+# This file is distributed under the same license as hledger.+# Translators: Daniil Iaitskov.+# Entries marked "machine-translated, please review" were made by machine (Claude Opus 5.5);+# when you have checked one, delete its mark.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: ru\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Январь"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Февраль"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Март"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Апрель"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Май"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Июнь"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Июль"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Август"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Сентябрь"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Октябрь"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Ноябрь"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Декабрь"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Янв"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Фев"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Мар"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Апр"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Май"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Июн"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Июл"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Авг"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Сен"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Окт"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Ноя"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Дек"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Подробности отчёта"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Итого"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Активы"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Обязательства"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Капитал"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Доходы"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Расходы"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Прочие"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Сальдо"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Итого"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Чистый итог:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…и ещё {n}"+msgstr[1] "…и ещё {n}"+msgstr[2] "…и ещё {n}"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "прочие {parent} ({n} счёт)"+msgstr[1] "прочие {parent} ({n} счёта)"+msgstr[2] "прочие {parent} ({n} счетов)"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "прочие ({n} счёт)"+msgstr[1] "прочие ({n} счёта)"+msgstr[2] "прочие ({n} счетов)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Изменения стоимости на конец периода)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Накопленные изменения стоимости на конец периода)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Прирост)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Накопленный прирост)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Исторический прирост)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Изменения сальдо)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Накопленные конечные сальдо)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Исторические конечные сальдо)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", в ценах сделки"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", по курсу на дату проводки"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", по курсу на конец периода"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", по текущей стоимости"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", по курсу на {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Отчёт по бюджету"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Отчёт о сальдо по периодам"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Отчёт о сальдо"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} за {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Изменения стоимости на конец периода"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Накопленные изменения стоимости на конец периода"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Прирост"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Накопленный прирост"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Исторический прирост"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Количество проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Накопленное количество проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Историческое количество проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Количество транзакций"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Изменения сальдо"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Конечные сальдо (накопленные)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Конечные сальдо (исторические)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Исполнение бюджета за {dates}{valuation}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Единица учёта"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Среднее"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Ежедневный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Еженедельный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Двухнедельный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Ежемесячный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Двухмесячный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Квартальный баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Полугодовой баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Годовой баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Двухлетний баланс"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Периодический баланс"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Ежедневный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Еженедельный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Двухнедельный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Ежемесячный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Двухмесячный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Квартальный баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Полугодовой баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Годовой баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Двухлетний баланс с капиталом"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Периодический баланс с капиталом"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Ежедневный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Еженедельный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Двухнедельный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Ежемесячный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Двухмесячный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Квартальный отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Полугодовой отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Годовой отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Двухлетний отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Периодический отчёт о движении денежных средств"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Движение денежных средств"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Стоимости и прибыль не учитывают позиции без рыночной цены: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Реализованная прибыль"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Нереализованная прибыль"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Реализованный убыток"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Нереализованный убыток"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Чистая прибыль"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Стоимость приобретения"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Нет рыночной цены"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Стоимость"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Средняя стоимость приобретения"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Стоимость приобретения единицы/средняя"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Стоимость приобретения единицы"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Итоги столбцов «Стоимость, всего», «Нереал. приб.», «Нереал. приб. %» и «XIRR» не учитывают позиции без рыночной цены: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Итоги столбцов «Реал. приб.» и «XIRR» включают {n} закрытую позицию, которая не показана"+msgstr[1] "Итоги столбцов «Реал. приб.» и «XIRR» включают {n} закрытые позиции, которые не показаны"+msgstr[2] "Итоги столбцов «Реал. приб.» и «XIRR» включают {n} закрытых позиций, которые не показаны"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, прибыль за каждый период"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, прибыль с {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Ежедневные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Еженедельные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Двухнедельные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Ежемесячные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Двухмесячные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Квартальные позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Полугодовые позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Годовые позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Двухлетние позиции"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Периодические позиции"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Позиции"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Единицы"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Цена единицы"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Стоимость приобретения, всего"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Стоимость, всего"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Нереал. приб."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Нереал. приб. %"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Реал. приб."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(позиций нет)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Дата"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Позиции на {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Позиции на {date}, прибыль за {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(см. -E)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Возраст"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Доля"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Счёт"++# machine-translated, please review+#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Итого:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Ежедневный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Еженедельный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Двухнедельный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Ежемесячный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Двухмесячный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Квартальный отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Полугодовой отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Годовой отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Двухлетний отчёт о прибылях и убытках"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Периодический отчёт о прибылях и убытках"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Регистр"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Показывать:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Заголовки"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Графики"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Всё"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "сальдо счетов"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "изменения сальдо счетов"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "денежные сальдо"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "сальдо баланса"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "изменения отчёта о прибылях и убытках"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Денежные счета"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Счета баланса"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Счета отчёта о прибылях и убытках"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Все счета"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Итого в ценах сделки:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "Сумма всех счетов в ценах сделки. Не равна нулю, если что-то не сбалансировано."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Итого по рыночной стоимости:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "Сумма всех счетов по рыночной стоимости. Не равна нулю, если стоимости изменились, а прибыль или убыток не учтены ни одной записью, например нереализованная прибыль по инвестициям."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "Сумма всех счетов. Не равна нулю, если что-то не сбалансировано, например конвертации через @ без --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Сальдо на {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Сальдо каждого счёта на конец этого дня: конца дат поиска или, если их нет, последней даты журнала"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Журнал"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Показать записи общего журнала, сначала новые"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Баланс"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Показать активы, обязательства и чистые активы"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Отчёт о прибылях и убытках"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Показать доходы и расходы"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Отчёт о движении денежных средств"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Показать изменения ликвидных активов"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Показать инвестиционные позиции, лоты и прибыль"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Показать сальдо всех счетов по периодам, как команда balance"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Показаны транзакции с {first} по {last} из {total}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Показать страницу {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Страница {n}"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Показать только {year}"++# machine-translated, please review+#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Shift+щелчок выбирает диапазон лет."++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Интервал:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Показать один столбец для всего периода"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Нет"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Годовой"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Показать столбец на каждый год"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Квартальный"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Показать столбец на каждый квартал"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Ежемесячный"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Показать столбец на каждый месяц"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Еженедельный"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Показать столбец на каждую неделю"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Ежедневный"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Показать столбец на каждый день"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Показать, насколько изменилось каждое сальдо в каждом периоде"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Накопленные итоги"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Показать изменение каждого сальдо с начала отчёта (--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Конечные сальдо"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Показать каждое сальдо на конец каждого периода, включая всё, что было до него"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Вычислять:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Показать суммы проводок"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Суммы"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Изменение стоимости"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Показать, как изменились рыночные стоимости на конец периодов (--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Нереализованная прибыль"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Показать нереализованную прибыль: рыночная стоимость минус стоимость приобретения (--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Считать количество проводок вместо их сумм (--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Счета:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Показать счета плоским списком (--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Список"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Показать счета деревом (--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Дерево"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Сортировка:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "По счёту"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Сортировать строки в порядке отображения счетов"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "По сумме"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Сортировать строки по суммам, сначала наибольшие (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "График:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Расходящийся"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Показать суммы каждого периода одним столбцом, выше и ниже нуля (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Сгруппированный"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Показать типы счетов каждого периода столбцами рядом друг с другом (--chart=grouped)"++# machine-translated, please review+#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Глубина {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "без ограничений"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Как записано"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "В ценах сделки"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "По стоимости"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Проценты"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Сгруппированный график"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Итого"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Среднее"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Выведенные цены"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Нулевые сальдо скрыты"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Нулевые сальдо показаны"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Лоты показаны"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Цены сделок показаны"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Закрытые позиции показаны"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Закрытые позиции скрыты"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Вторичные даты"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Капитал показан"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Не удалось вычислить проценты:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Не удалось разобрать интервал отчёта:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Неизвестное преобразование сумм:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Параметр {name} имеет значение, неизвестное этой странице:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Изменения стоимости и прибыль вычисляются по рыночным стоимостям на конец периода: не указывайте параметр value или используйте value=end."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Прибыль сравнивает рыночную стоимость со стоимостью приобретения, поэтому не сочетается с value=cost."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Этот отчёт на одну дату, поэтому value=then неприменимо: используйте value=end, value=now или дату."++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Показать этот отчёт за этот период"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Транзакция добавлена."++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, с фильтром"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "сальдо - hledger-web"++# machine-translated, please review+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Все"++# machine-translated, please review+#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Shift+щелчок выбирает несколько типов."++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Shift+щелчок выбирает несколько единиц учёта."++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Не удалось загрузить журнал: {error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Журнал {file} сохранён"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Редактировать журнал"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "позиции - hledger-web"++# machine-translated, please review+#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Показать регистр этого счёта"++# machine-translated, please review+#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Показать регистр этой позиции"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Показать позиции на эту дату"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "показать их"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Прибыль:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "За каждый период"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Показать прибыль за каждый период"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "С начала отчёта"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Показать прибыль с даты начала отчёта до конца каждого периода"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "С момента приобретения"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Показать прибыль с момента приобретения каждой позиции до конца каждого периода"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Общий журнал"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Транзакции по счёту {account}"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Транзакции по счёту {account} (без субсчетов)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "журнал - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "все счета"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (без субсчетов)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Итого (исторически)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Итого (за период)"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Нажмите, чтобы показать нарастающее сальдо с начала этого периода"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Нажмите, чтобы показать нарастающее сальдо с учётом всего, что было до этого периода"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "регистр - hledger-web"++# machine-translated, please review+#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "без символа"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "баланс с капиталом - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "баланс - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "отчёт о прибылях и убытках - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "отчёт о движении денежных средств - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Все счета в этом отчёте имеют нулевое сальдо и скрыты. Нажмите z, чтобы показать их."++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Не найдено счетов тех типов, которые показывает этот отчёт. Объявите типы счетов или используйте стандартные названия счетов верхнего уровня hledger. "++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Как hledger определяет типы счетов"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "За этот период ничего не найдено."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Ошибка кодировки: '{error}'. Если ваш файл не в кодировке UTF-8, попробуйте форму редактирования, где перекодировку должен выполнить браузер."++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Файл {file} успешно загружен"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Загрузить журнал"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Закрыть"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Добавить транзакцию"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Счёт {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Сумма {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Неверный формат даты"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Дата"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Описание"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Отсутствует сумма"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Отсутствует счёт"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Неверное значение: {error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Проверка проводок не пройдена"++# machine-translated, please review+#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Единица учёта"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Показать/скрыть график (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "График"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Показать/скрыть данные (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Данные"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Показать параметры, меняющие этот вид"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Параметры"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} за {dates}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} за {dates}, с фильтром"++# machine-translated, please review+#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Эти элементы управления действуют на страницах отчётов"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Цены:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Объявленные"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Оценивать суммы только по объявленным рыночным ценам (директивы P)"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "И выведенные"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Выводить рыночные цены также из цен сделок (--infer-market-prices)"++# machine-translated, please review+#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Глубина:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Показать только итог (глубина 0)"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Показать счета любой глубины"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Показать счета до глубины {depth}"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Суммы:"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Показать суммы в тех единицах учёта, в которых они записаны"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "В ценах сделки"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Показать суммы, пересчитанные в цены сделок, записанные в транзакциях (-B)"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "По рыночной стоимости"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Показать суммы, пересчитанные по рыночной стоимости на конец каждого периода, по рыночным ценам (-V)"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Нулевые сальдо:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Скрыть счета с нулевым сальдо"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Скрыты"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Показать счета с нулевым сальдо"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Показаны"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Капитал:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Показать активы, обязательства и чистые активы, как команда balancesheet"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Показать активы, обязательства и капитал, как команда balancesheetequity"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Статус:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Показать транзакции с любым статусом"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Все"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Без отметки"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Показать только транзакции без отметки (status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Ожидающие"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Показать только ожидающие транзакции (status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Сверенные"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Показать только сверенные транзакции (status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Проводки:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Показать реальные и виртуальные проводки"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Все"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Реальные"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Показать только реальные проводки, как -R (real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Виртуальные"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Показать только виртуальные проводки, те, что в скобках (real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Дополнительные столбцы:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Добавить столбец с итогом каждой строки (-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Добавить столбец со средним каждой строки (-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Числа:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Показать суммы"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Суммы"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Показать каждую сумму как процент от итога её столбца (-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Цены сделок:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Показать суммы без цен сделок"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Скрыты"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Показать суммы с ценами сделок, записанными в журнале"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Показаны"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Лоты:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Объединять лоты каждого счёта"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Скрыты"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Показать каждый лот отдельно (--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Показаны"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Закрытые позиции:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Показать только открытые позиции"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Скрыты"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Показать также полностью проданные позиции и их реализованную прибыль (-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Показаны"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Стоимости:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "В единице учёта стоимости приобретения"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Оценивать каждую позицию в единице учёта её стоимости приобретения"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Пересчитывать стоимости и стоимости приобретения в единицу учёта рыночной оценки (-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Тип:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Показать счета всех типов"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Все"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Активы"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Показать только счета активов (type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Обязательства"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Показать только счета обязательств (type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Показать только счета капитала (type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Доходы"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Показать только счета доходов (type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Расходы"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Показать только счета расходов (type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Денежные средства"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Показать только денежные счета (type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Конвертация"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Показать только счета конвертации (type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Прибыль"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Показать только счета прибыли от капитала (type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Расхождение"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Показать только счета расхождений (type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Перечислить все единицы учёта"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Единица учёта:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Показать суммы во всех единицах учёта"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Все"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Показать только суммы в {commodity}"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… и ещё {n}"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Выберите дату"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Добавить в:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Сохранить"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Свернуть счета ещё на один уровень"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Развернуть счета ещё на один уровень"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Показать/скрыть сальдо"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Сальдо"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Показать транзакции по этому счёту и его субсчетам"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Показать транзакции по этому счёту, не считая субсчетов"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "только"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Показать транзакции, из которых складывается это сальдо"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Показать транзакции, из которых складывается этот итог"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Показать/скрыть боковую панель (s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web больше не работает. Он завершается после пятнадцати минут без открытого окна браузера или при остановке. Чтобы продолжить, запустите его снова и перезагрузите эту страницу."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Выйти из режима на всё окно"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Поиск"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Введите шаблоны поиска hledger для фильтрации данных ниже"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Очистить условия поиска"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Применить условия поиска"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Управление файлами журнала"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Показать справку по поиску и общую справку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Перейти"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Справка"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Горячие клавиши"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "или"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "показать эту справку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "перейти к любому экрану"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "перейти к следующему или предыдущему экрану"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "добавить транзакцию"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "показать/скрыть боковую панель"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "задать глубину счетов боковой панели"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "показать/скрыть сальдо боковой панели"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "показать/скрыть параметры отчёта"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "показать/скрыть график отчёта"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "выбрать единицу учёта графика"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "показать/скрыть линию чистого итога графика"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "показать/скрыть данные отчёта"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "включить/выключить режим на всё окно"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "перейти к форме поиска"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "очистить поиск"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "отменить"++# machine-translated, please review+#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Параметры отчёта"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "исторические конечные сальдо / изменения сальдо"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "по годам"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "по кварталам"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "по месяцам"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "по неделям"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "по дням"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "без отметки"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "ожидающие"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "сверенные"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "только реальные / все"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Ограничение глубины:"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "задать"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "уменьшить или увеличить"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "дерево / список"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "в ценах сделки"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "по рыночной стоимости"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "показать/скрыть нулевые сальдо"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "показать/скрыть детали лотов"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "итого"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "среднее"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "по сумме / в порядке отображения счетов"++# machine-translated, please review+#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Повторное нажатие клавиши параметра выключает его."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Поисковые запросы"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Шаблоны поиска с пробелами следует заключать в кавычки."++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "найти названия счетов"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "найти типы счетов (A, L, E, R, X, ...)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "найти даты"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "найти статус"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "найти коды транзакций"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "найти описания транзакций"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "найти часть описания с получателем"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "найти часть описания с примечанием"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "найти суммы по абсолютной величине или, если N со знаком, суммы со знаком. N может содержать символ единицы учёта."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "найти строки отчёта (счета, периоды, транзакции) по их изменению или сальдо, как amt:. N может содержать символ единицы учёта."++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "найти валюты/единицы учёта. Должно совпадать с полным символом/названием. Для поиска знака доллара напишите"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "найти теги или тег и значение"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "найти реальность/виртуальность проводок"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "найти любое поле (счёт, сумма, комментарий, тег, описание, код) или дату, если REGEX также является выражением периода"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "поставьте not: в начало, чтобы инвертировать условие поиска"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "найти с помощью логического выражения (and, or, not, ())"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "найти транзакции, в которых совпадает любая проводка"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "найти транзакции, в которых совпадают все проводки"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "другой способ задать ограничение глубины (можно для отдельного счёта)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Ещё справка:"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "руководство пользователя hledger-web"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Редактировать файл"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Подтвердите операцию. Журнал будет перезаписан!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Справка по формату файла"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Назад"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Добавить новую транзакцию в журнал"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Дата"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Описание"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Счёт"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Сумма"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Показать записи журнала за этот день"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Файлы вашего журнала"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Файл"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Редактировать"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Загрузить"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Скачать"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Показать более новые транзакции"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Более новые"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Показать более старые транзакции"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Более старые"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Счёт получателя/отправителя"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Расход/приход"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Показать эту и другие записи журнала за этот день"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Перенесённое сальдо"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Показать транзакции до этого периода"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Загрузить в файл"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Выбрать файл"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Годы:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Показать все годы"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Все"++# machine-translated, please review+#~ msgid "Next report"+#~ msgstr "Следующий отчёт"++# machine-translated, please review+#~ msgid "Go to the next report"+#~ msgstr "Перейти к следующему отчёту"++# machine-translated, please review+#~ msgid "Previous report"+#~ msgstr "Предыдущий отчёт"++# machine-translated, please review+#~ msgid "Go to the previous report"+#~ msgstr "Перейти к предыдущему отчёту"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "Чистый итог, в ценах сделки:"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "Сумма всех счетов в ценах сделки: ноль при сбалансированных книгах; остаток происходит от несбалансированных виртуальных проводок."++# machine-translated, please review+#~ msgid "Unbooked gains:"+#~ msgstr "Неучтённая прибыль:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "Сумма всех счетов по рыночной стоимости: прирост, не учтённый ни одной записью. Если реализованная прибыль учтена, это нереализованная прибыль."++# machine-translated, please review+#~ msgid "Net flows:"+#~ msgstr "Чистые потоки:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "Сумма всех счетов: открытые позиции в каждой единице учёта и деньги, которыми они оплачены. Ноль, когда ничто не пересекает единицы учёта."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Позиции на конец периодов"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Позиции на конец периодов, {dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Неизвестный режим накопления сальдо:"++# machine-translated, please review+#~ msgid "Show only the total"+#~ msgstr "Показать только итог"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Показать транзакции, из которых складывается это сальдо"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "Показать транзакции, из которых складывается этот итог"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "найти любое видимое поле (счёт, сумма, комментарий, описание, код) или дату, если REGEX также является выражением периода"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "найти суммы по величине, а с N со знаком — с учётом знака. Только для сумм с одной единицей учёта."++#~ msgid "Balance sheet with equity"+#~ msgstr "Баланс с капиталом"++#~ msgid "Show assets, liabilities, and equity"+#~ msgstr "Показать активы, обязательства и капитал"++#~ msgid "Show the running balance from the start of this period"+#~ msgstr "Показать нарастающее сальдо с начала этого периода"++#~ msgid "Show the running balance including everything before this period"+#~ msgstr "Показать нарастающее сальдо, включая всё до этого периода"++#~ msgid "hide empty accounts"+#~ msgstr "скрыть пустые счета"++#~ msgid "General"+#~ msgstr "Общее"++#~ msgid "The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts"+#~ msgstr "Вид журнала показывает записи общего журнала — сбалансированные перемещения денег (или других единиц учёта) между иерархическими счетами"++#~ msgid "The sidebar shows the resulting accounts and their final balances"+#~ msgstr "Боковая панель показывает получившиеся счета и их конечные сальдо"++#~ msgid "The sidebar's report links show the balance sheet, income statement, and cashflow statement, each linking to the other reports"+#~ msgstr "Ссылки на отчёты на боковой панели показывают баланс, отчёт о прибылях и убытках и отчёт о движении денежных средств, каждая со ссылками на другие отчёты"++#~ msgid "Parent account balances include subaccount balances"+#~ msgstr "Сальдо родительских счетов включают сальдо субсчетов"++#~ msgid "Multiple currencies in balances are displayed one above the other"+#~ msgstr "Несколько валют в сальдо отображаются одна над другой"++#~ msgid "Click account name links to see transactions affecting that account, with running balance"+#~ msgstr "Нажмите на ссылку с названием счёта, чтобы увидеть транзакции по этому счёту с нарастающим сальдо"++#~ msgid "Click an amount to see the transactions it is made of, in a register ending on that amount"+#~ msgstr "Нажмите на сумму, чтобы увидеть в регистре транзакции, из которых она складывается, с итогом на эту сумму"++#~ msgid "Click date links to see journal entries on that date"+#~ msgstr "Нажмите на ссылку с датой, чтобы увидеть записи журнала за этот день"++#~ msgid "The balance sheet and income statement show liabilities, equity, and revenues as positive amounts; their registers show them negative, as hledger does"+#~ msgstr "Баланс и отчёт о прибылях и убытках показывают обязательства, капитал и доходы как положительные суммы; их регистры показывают их отрицательными, как это делает hledger"++#~ msgctxt "help heading"+#~ msgid "Search"+#~ msgstr "Поиск"++#~ msgid "match account types"+#~ msgstr "найти типы счетов"++#~ msgid "clip account names at this depth"+#~ msgstr "обрезать названия счетов до этой глубины"++#~ msgid "Could not parse the period expression:"+#~ msgstr "Не удалось разобрать выражение периода:"++#~ msgid "Report:"+#~ msgstr "Отчёт:"++#~ msgid "add a transaction (escape to cancel)"+#~ msgstr "добавить транзакцию (Escape для отмены)"++#~ msgid "go to the Journal view (home)"+#~ msgstr "перейти к виду журнала (главная)"++#~ msgid "or maybe"+#~ msgstr "или"++#~ msgid "view this help (escape or click to exit)"+#~ msgstr "показать эту справку (Escape или клик для выхода)"++#~ msgid "Balance report"+#~ msgstr "Отчёт о сальдо"++#~ msgid "Show the balance report: any accounts, by period"+#~ msgstr "Показать отчёт о сальдо: любые счета, по периодам"
+ locale/uk.po view
@@ -0,0 +1,3321 @@+# Ukrainian translations for hledger.+# This file is distributed under the same license as hledger.+# Terminology and choices to check: see hledger-lib/locale/README.md, Ukrainian.+# Machine-made (Claude Fable 5.1, and Opus 5.5 for the entries new in 2.0); not yet checked by a native speaker.+# "Key term" marks an entry whose mistranslation would mislead about money or data:+# use your country's standard accounting term, and review these first.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"Language: uk\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"++# machine-translated, please review+#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "Січень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "Лютий"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "Березень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "Квітень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "Травень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "Червень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "Липень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "Серпень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "Вересень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "Жовтень"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "Листопад"++# machine-translated, please review+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "Грудень"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "Січ"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "Лют"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "Бер"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "Кві"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "Тра"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "Чер"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "Лип"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "Сер"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "Вер"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "Жов"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "Лис"++# machine-translated, please review+#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "Гру"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "Деталі звіту"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "Разом"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "Активи"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "Зобов'язання"++# machine-translated, please review+#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "Капітал"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "Доходи"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "Витрати"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "Інші"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "Сальдо"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "Разом"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "Чистий підсумок:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…і ще {n}"+msgstr[1] "…і ще {n}"+msgstr[2] "…і ще {n}"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "інші {parent} ({n} рахунок)"+msgstr[1] "інші {parent} ({n} рахунки)"+msgstr[2] "інші {parent} ({n} рахунків)"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "інші ({n} рахунок)"+msgstr[1] "інші ({n} рахунки)"+msgstr[2] "інші ({n} рахунків)"++# machine-translated, please review+#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{report} {dates}{clarification}{valuation}"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(Зміни вартості на кінець періоду)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(Накопичені зміни вартості на кінець періоду)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(Приріст)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(Накопичений приріст)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(Історичний приріст)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(Зміни сальдо)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(Накопичені кінцеві сальдо)"++# machine-translated, please review+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(Історичні кінцеві сальдо)"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ", у цінах угод"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ", за курсом на дату проводки"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ", за курсом на кінець періоду"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ", за поточною вартістю"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ", за курсом на {date}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "Звіт за бюджетом"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "Звіт про сальдо за періодами"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "Звіт про сальдо"++# machine-translated, please review+#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{report} за {dates}{valuation}:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "Зміни вартості на кінець періоду"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "Накопичені зміни вартості на кінець періоду"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "Приріст"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "Накопичений приріст"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "Історичний приріст"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "Кількість проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "Накопичена кількість проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "Історична кількість проводок"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "Кількість транзакцій"++# machine-translated, please review+#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "Зміни сальдо"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "Кінцеві сальдо (накопичені)"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "Кінцеві сальдо (історичні)"++# machine-translated, please review+#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "Виконання бюджету за {dates}{valuation}:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "Одиниця обліку"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "Середнє"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "Баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "Щоденний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "Щотижневий баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "Двотижневий баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "Щомісячний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "Двомісячний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "Квартальний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "Піврічний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "Річний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "Дворічний баланс"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "Періодичний баланс"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "Баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "Щоденний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "Щотижневий баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "Двотижневий баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "Щомісячний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "Двомісячний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "Квартальний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "Піврічний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "Річний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "Дворічний баланс з капіталом"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "Періодичний баланс з капіталом"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "Звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "Щоденний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "Щотижневий звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "Двотижневий звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "Щомісячний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "Двомісячний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "Квартальний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "Піврічний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "Річний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "Дворічний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "Періодичний звіт про рух грошових коштів"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "Рух грошових коштів"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "Вартості та прибуток не враховують позиції без ринкової ціни: {commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "Реалізований прибуток"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "Нереалізований прибуток"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "Реалізований збиток"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "Нереалізований збиток"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "Чистий прибуток"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "Вартість придбання"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "Немає ринкової ціни"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "Вартість"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "Середня вартість придбання"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "Вартість придбання одиниці/середня"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "Вартість придбання одиниці"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "Підсумки стовпців «Вартість, разом», «Нереал. приб.», «Нереал. приб. %» і «XIRR» не враховують позиції без ринкової ціни: {commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "Підсумки стовпців «Реал. приб.» і «XIRR» включають {n} закриту позицію, яку не показано"+msgstr[1] "Підсумки стовпців «Реал. приб.» і «XIRR» включають {n} закриті позиції, які не показано"+msgstr[2] "Підсумки стовпців «Реал. приб.» і «XIRR» включають {n} закритих позицій, які не показано"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings}, {dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings}, {dates}, прибуток за кожен період"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings}, {dates}, прибуток з {start}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "Щоденні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "Щотижневі позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "Двотижневі позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "Щомісячні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "Двомісячні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "Квартальні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "Піврічні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "Річні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "Дворічні позиції"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "Періодичні позиції"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "Позиції"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "Одиниці"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "Ціна одиниці"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "Вартість придбання, разом"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "Вартість, разом"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "Нереал. приб."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "Нереал. приб. %"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "Реал. приб."++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(позицій немає)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "Дата"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "Позиції на {date}"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "Позиції на {date}, прибуток за {period}"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(див. -E)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "Вік"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "Частка"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "Рахунок"++# machine-translated, please review+#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "Разом:"++# machine-translated, please review+#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "Звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "Щоденний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "Щотижневий звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "Двотижневий звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "Щомісячний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "Двомісячний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "Квартальний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "Піврічний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "Річний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "Дворічний звіт про фінансові результати"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "Періодичний звіт про фінансові результати"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "Реєстр"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "Показувати:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "Заголовки"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "Діаграми"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "Усе"++# machine-translated, please review+#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "сальдо рахунків"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "зміни сальдо рахунків"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "грошові сальдо"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "сальдо балансу"++# machine-translated, please review+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "зміни звіту про фінансові результати"++# machine-translated, please review+#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "Грошові рахунки"++# machine-translated, please review+#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "Рахунки балансу"++# machine-translated, please review+#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "Рахунки звіту про фінансові результати"++# machine-translated, please review+#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "Усі рахунки"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "Разом у цінах угод:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "Сума всіх рахунків у цінах угод. Не дорівнює нулю, якщо щось не збалансовано."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "Разом за ринковою вартістю:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "Сума всіх рахунків за ринковою вартістю. Не дорівнює нулю, якщо вартості змінилися, а прибуток чи збиток не облікований жодним записом, наприклад нереалізований прибуток від інвестицій."++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "Сума всіх рахунків. Не дорівнює нулю, якщо щось не збалансовано, наприклад конвертації через @ без --infer-equity."++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "Сальдо на {date}"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "Сальдо кожного рахунку на кінець цього дня: кінця дат пошуку або, якщо їх немає, останньої дати журналу"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "Журнал"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "Показати записи загального журналу, спочатку нові"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "Баланс"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "Показати активи, зобов'язання та чисті активи"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "Звіт про фінансові результати"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "Показати доходи та витрати"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "Звіт про рух грошових коштів"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "Показати зміни ліквідних активів"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "Показати інвестиційні позиції, лоти та прибуток"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "Показати сальдо всіх рахунків за періодами, як команда balance"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "Показано транзакції з {first} по {last} із {total}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "Показати сторінку {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "Сторінка {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "Показати лише {year}"++# machine-translated, please review+#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "Shift+клацання вибирає діапазон років."++# machine-translated, please review+#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "Інтервал:"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "Показати один стовпець за весь період"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "Немає"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "Річний"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "Показати стовпець на кожен рік"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "Квартальний"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "Показати стовпець на кожен квартал"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "Щомісячний"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "Показати стовпець на кожен місяць"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "Щотижневий"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "Показати стовпець на кожен тиждень"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "Щоденний"++# machine-translated, please review+#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "Показати стовпець на кожен день"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "Показати, наскільки змінилося кожне сальдо в кожному періоді"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "Накопичені підсумки"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "Показати зміну кожного сальдо від початку звіту (--cumulative)"++# machine-translated, please review+#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "Кінцеві сальдо"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "Показати кожне сальдо на кінець кожного періоду, включно з усім, що було до нього"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "Обчислювати:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "Показати суми проводок"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "Суми"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "Зміна вартості"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "Показати, як змінилися ринкові вартості на кінець періодів (--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "Нереалізований прибуток"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "Показати нереалізований прибуток: ринкова вартість мінус вартість придбання (--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "Рахувати кількість проводок замість їх сум (--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "Рахунки:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "Показати рахунки плоским списком (--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "Список"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "Показати рахунки деревом (--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "Дерево"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "Сортування:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "За рахунком"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "Сортувати рядки в порядку відображення рахунків"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "За сумою"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "Сортувати рядки за сумами, спочатку найбільші (-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "Діаграма:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "Розбіжна"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "Показати суми кожного періоду одним стовпцем, вище й нижче нуля (--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "Згрупована"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "Показати типи рахунків кожного періоду стовпцями поруч (--chart=grouped)"++# machine-translated, please review+#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "Глибина {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "без обмежень"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "Як записано"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "У цінах угод"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "За вартістю"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "Відсотки"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "Згрупована діаграма"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "Разом"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "Середнє"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "Виведені ціни"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "Нульові сальдо сховано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "Нульові сальдо показано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "Лоти показано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "Ціни угод показано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "Закриті позиції показано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "Закриті позиції сховано"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "Вторинні дати"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "Капітал показано"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "Не вдалося обчислити відсотки:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "Не вдалося розібрати інтервал звіту:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "Невідоме перетворення сум:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "Параметр {name} має значення, невідоме цій сторінці:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "Зміни вартості та прибуток обчислюються за ринковими вартостями на кінець періоду: не вказуйте параметр value або використовуйте value=end."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "Прибуток порівнює ринкову вартість із вартістю придбання, тому не поєднується з value=cost."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "Цей звіт на одну дату, тому value=then не застосовується: використовуйте value=end, value=now або дату."++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "Показати цей звіт за цей період"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "Транзакцію додано."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title}, з фільтром"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "сальдо - hledger-web"++# machine-translated, please review+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "Shift+клацання вибирає кілька типів."++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "Shift+клацання вибирає кілька одиниць обліку."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "Не вдалося завантажити журнал: {error}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "Журнал {file} збережено"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "Редагувати журнал"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "позиції - hledger-web"++# machine-translated, please review+#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "Показати реєстр цього рахунку"++# machine-translated, please review+#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "Показати реєстр цієї позиції"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "Показати позиції на цю дату"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "показати їх"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "Прибуток:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "За кожен період"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "Показати прибуток за кожен період"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "Від початку звіту"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "Показати прибуток від дати початку звіту до кінця кожного періоду"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "Від придбання"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "Показати прибуток від придбання кожної позиції до кінця кожного періоду"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "Загальний журнал"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "Транзакції за рахунком {account}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "Транзакції за рахунком {account} (без субрахунків)"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "журнал - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "усі рахунки"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account} (без субрахунків)"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "Разом (історично)"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "Разом (за період)"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "Натисніть, щоб показати наростаюче сальдо від початку цього періоду"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "Натисніть, щоб показати наростаюче сальдо включно з усім, що було до цього періоду"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "реєстр - hledger-web"++# machine-translated, please review+#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "без символу"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "баланс з капіталом - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "баланс - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "звіт про фінансові результати - hledger-web"++# machine-translated, please review+#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "звіт про рух грошових коштів - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "Усі рахунки в цьому звіті мають нульове сальдо і сховані. Натисніть z, щоб показати їх."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "Не знайдено рахунків тих типів, які показує цей звіт. Оголосіть типи рахунків або використовуйте стандартні назви рахунків верхнього рівня hledger. "++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "Як hledger визначає типи рахунків"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "За цей період нічого не знайдено."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "Помилка кодування: '{error}'. Якщо ваш файл не в кодуванні UTF-8, спробуйте форму редагування, де перекодування має виконати браузер."++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "Файл {file} успішно вивантажено"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "Вивантажити журнал"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "Закрити"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "Додати транзакцію"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "Рахунок {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "Сума {n}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "Неправильний формат дати"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "Дата"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "Опис"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "Відсутня сума"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "Відсутній рахунок"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "Неправильне значення: {error}"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "Перевірка проводок не пройдена"++# machine-translated, please review+#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "Одиниця обліку"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "Показати/сховати діаграму (c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "Діаграма"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "Показати/сховати дані (d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "Дані"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "Показати параметри, що змінюють цей вигляд"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "Параметри"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{title} за {dates}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{title} за {dates}, з фільтром"++# machine-translated, please review+#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "Ці елементи керування діють на сторінках звітів"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "Ціни:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "Оголошені"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "Оцінювати суми лише за оголошеними ринковими цінами (директиви P)"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "І виведені"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "Виводити ринкові ціни також із цін угод (--infer-market-prices)"++# machine-translated, please review+#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "Глибина:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "Показати лише підсумок (глибина 0)"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "Показати рахунки будь-якої глибини"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "Показати рахунки до глибини {depth}"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "Суми:"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "Показати суми в тих одиницях обліку, в яких їх записано"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "У цінах угод"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "Показати суми, перераховані в ціни угод, записані в транзакціях (-B)"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "За ринковою вартістю"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "Показати суми, перераховані за ринковою вартістю на кінець кожного періоду, за ринковими цінами (-V)"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "Нульові сальдо:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "Сховати рахунки з нульовим сальдо"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "Сховано"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "Показати рахунки з нульовим сальдо"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "Показано"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "Капітал:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "Показати активи, зобов'язання та чисті активи, як команда balancesheet"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "Показати активи, зобов'язання та капітал, як команда balancesheetequity"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "Статус:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "Показати транзакції з будь-яким статусом"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "Без позначки"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "Показати лише транзакції без позначки (status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "Очікувані"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "Показати лише очікувані транзакції (status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "Звірені"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "Показати лише звірені транзакції (status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "Проводки:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "Показати реальні та віртуальні проводки"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "Реальні"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "Показати лише реальні проводки, як -R (real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "Віртуальні"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "Показати лише віртуальні проводки, ті, що в дужках (real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "Додаткові стовпці:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "Додати стовпець із підсумком кожного рядка (-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "Додати стовпець із середнім кожного рядка (-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "Числа:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "Показати суми"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "Суми"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "Показати кожну суму як відсоток від підсумку її стовпця (-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "Ціни угод:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "Показати суми без цін угод"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "Сховано"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "Показати суми з цінами угод, записаними в журналі"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "Показано"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "Лоти:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "Об'єднувати лоти кожного рахунку"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "Сховано"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "Показати кожен лот окремо (--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "Показано"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "Закриті позиції:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "Показати лише відкриті позиції"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "Сховано"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "Показати також повністю продані позиції та їх реалізований прибуток (-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "Показано"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "Вартості:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "В одиниці обліку вартості придбання"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "Оцінювати кожну позицію в одиниці обліку її вартості придбання"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "Перераховувати вартості та вартості придбання в одиницю обліку ринкової оцінки (-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "Тип:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "Показати рахунки всіх типів"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "Активи"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "Показати лише рахунки активів (type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "Зобов'язання"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "Показати лише рахунки зобов'язань (type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "Показати лише рахунки капіталу (type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "Доходи"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "Показати лише рахунки доходів (type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "Витрати"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "Показати лише рахунки витрат (type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "Грошові кошти"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "Показати лише грошові рахунки (type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "Конвертація"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "Показати лише рахунки конвертації (type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "Прибуток"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "Показати лише рахунки прибутку від капіталу (type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "Розбіжність"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "Показати лише рахунки розбіжностей (type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "Перелічити всі одиниці обліку"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "Одиниця обліку:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "Показати суми в усіх одиницях обліку"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "Показати лише суми в {commodity}"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… і ще {n}"++# machine-translated, please review+#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "Виберіть дату"++# machine-translated, please review+#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "Додати до:"++# machine-translated, please review+#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "Зберегти"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "Згорнути рахунки ще на один рівень"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "Розгорнути рахунки ще на один рівень"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "Показати/сховати сальдо"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "Сальдо"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "Показати транзакції за цим рахунком та його субрахунками"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "Показати транзакції за цим рахунком, не рахуючи субрахунків"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "лише"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "Показати транзакції, з яких складається це сальдо"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "Показати транзакції, з яких складається цей підсумок"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "Показати/сховати бічну панель (s)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web більше не працює. Він завершується через п'ятнадцять хвилин без відкритого вікна браузера або після зупинки. Щоб продовжити, запустіть його знову та перезавантажте цю сторінку."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "Вийти з режиму на все вікно"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "Пошук"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "Введіть шаблони пошуку hledger для фільтрації даних нижче"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "Очистити умови пошуку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "Застосувати умови пошуку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "Керування файлами журналу"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "Показати довідку з пошуку та загальну довідку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "Перейти"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "Довідка"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "Гарячі клавіші"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "або"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "показати цю довідку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "перейти до будь-якого екрана"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "перейти до наступного або попереднього екрана"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "додати транзакцію"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "показати/сховати бічну панель"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "задати глибину рахунків бічної панелі"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "показати/сховати сальдо бічної панелі"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "показати/сховати параметри звіту"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "показати/сховати діаграму звіту"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "вибрати одиницю обліку діаграми"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "показати/сховати лінію чистого підсумку діаграми"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "показати/сховати дані звіту"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "увімкнути/вимкнути режим на все вікно"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "перейти до форми пошуку"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "очистити пошук"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "скасувати"++# machine-translated, please review+#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "Параметри звіту"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "історичні кінцеві сальдо / зміни сальдо"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "за роками"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "за кварталами"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "за місяцями"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "за тижнями"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "за днями"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "без позначки"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "очікувані"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "звірені"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "лише реальні / усі"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "Обмеження глибини:"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "задати"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "зменшити або збільшити"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "дерево / список"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "у цінах угод"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "за ринковою вартістю"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "показати/сховати нульові сальдо"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "показати/сховати деталі лотів"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "разом"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "середнє"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "за сумою / в порядку відображення рахунків"++# machine-translated, please review+#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "Повторне натискання клавіші параметра вимикає його."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "Пошукові запити"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "Шаблони пошуку з пробілами слід брати в лапки."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "знайти назви рахунків"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "знайти типи рахунків (A, L, E, R, X, ...)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "знайти дати"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "знайти статус"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "знайти коди транзакцій"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "знайти описи транзакцій"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "знайти частину опису з одержувачем"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "знайти частину опису з приміткою"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "знайти суми за абсолютною величиною або, якщо N зі знаком, суми зі знаком. N може містити символ одиниці обліку."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "знайти рядки звіту (рахунки, періоди, транзакції) за їх зміною або сальдо, як amt:. N може містити символ одиниці обліку."++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "знайти валюти/одиниці обліку. Має збігатися з повним символом/назвою. Для пошуку знака долара напишіть"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "знайти теги або тег і значення"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "знайти реальність/віртуальність проводок"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "знайти будь-яке поле (рахунок, сума, коментар, тег, опис, код) або дату, якщо REGEX також є виразом періоду"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "поставте not: на початку, щоб інвертувати умову пошуку"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "знайти за допомогою логічного виразу (and, or, not, ())"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "знайти транзакції, в яких збігається будь-яка проводка"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "знайти транзакції, в яких збігаються всі проводки"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "інший спосіб задати обмеження глибини (можна для окремого рахунку)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "Ще довідка:"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "посібник користувача hledger-web"++# machine-translated, please review+#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "Редагувати файл"++# machine-translated, please review+#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "Ви впевнені? Журнал буде перезаписано!"++# machine-translated, please review+#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "Довідка з формату файлу"++# machine-translated, please review+#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "Назад"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "Додати нову транзакцію до журналу"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "Дата"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "Опис"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "Рахунок"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "Сума"++# machine-translated, please review+#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "Показати записи журналу за цей день"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "Файли вашого журналу"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "Файл"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "Редагувати"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "Вивантажити"++# machine-translated, please review+#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "Завантажити"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "Показати новіші транзакції"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "Новіші"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "Показати старіші транзакції"++# machine-translated, please review+#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "Старіші"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "Рахунок одержувача/відправника"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "Витрата/надходження"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "Показати цей та інші записи журналу за цей день"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "Перенесене сальдо"++# machine-translated, please review+#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "Показати транзакції до цього періоду"++# machine-translated, please review+#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "Вивантажити у файл"++# machine-translated, please review+#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "Вибрати файл"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "Роки:"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "Показати всі роки"++# machine-translated, please review+#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "Усі"++# machine-translated, please review+#~ msgid "Next report"+#~ msgstr "Наступний звіт"++# machine-translated, please review+#~ msgid "Go to the next report"+#~ msgstr "Перейти до наступного звіту"++# machine-translated, please review+#~ msgid "Previous report"+#~ msgstr "Попередній звіт"++# machine-translated, please review+#~ msgid "Go to the previous report"+#~ msgstr "Перейти до попереднього звіту"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "Чистий підсумок, у цінах угод:"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "Сума всіх рахунків у цінах угод: нуль для збалансованих книг; залишок походить від незбалансованих віртуальних проводок."++# machine-translated, please review+#~ msgid "Unbooked gains:"+#~ msgstr "Необлікований прибуток:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "Сума всіх рахунків за ринковою вартістю: приріст, не облікований жодним записом. Якщо реалізований прибуток обліковано, це нереалізований прибуток."++# machine-translated, please review+#~ msgid "Net flows:"+#~ msgstr "Чисті потоки:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "Сума всіх рахунків: відкриті позиції в кожній одиниці обліку та гроші, якими їх оплачено. Нуль, коли ніщо не перетинає одиниці обліку."++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "Позиції на кінець періодів"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "Позиції на кінець періодів, {dates}"++# machine-translated, please review+#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "Невідомий режим накопичення сальдо:"++# machine-translated, please review+#~ msgid "Show only the total"+#~ msgstr "Показати лише підсумок"++# machine-translated, please review+#~ msgid "Show the transactions that make up this balance"+#~ msgstr "Показати транзакції, з яких складається це сальдо"++# machine-translated, please review+#~ msgid "Show the transactions that make up this total"+#~ msgstr "Показати транзакції, з яких складається цей підсумок"++# machine-translated, please review+#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "знайти будь-яке видиме поле (рахунок, сума, коментар, опис, код) або дату, якщо REGEX також є виразом періоду"++# machine-translated, please review+#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "знайти суми за величиною, а з N зі знаком - з урахуванням знака. Лише для сум з однією одиницею обліку."
+ locale/zh-Hans.po view
@@ -0,0 +1,3156 @@+# Simplified Chinese translations for hledger.+# This file is distributed under the same license as hledger.+# Translators: Chunhui Ouyang.+# Entries marked "machine-translated, please review" were made by machine (Claude Opus 5.5);+# when you have checked one, delete its mark.+#+msgid ""+msgstr ""+"Project-Id-Version: hledger\n"+"Report-Msgid-Bugs-To: https://github.com/simonmichael/hledger/issues\n"+"POT-Creation-Date: \n"+"PO-Revision-Date: \n"+"Last-Translator: \n"+"Language-Team: \n"+"Language: zh_CN\n"+"MIME-Version: 1.0\n"+"Content-Type: text/plain; charset=UTF-8\n"+"Content-Transfer-Encoding: 8bit\n"+"Plural-Forms: nplurals=1; plural=0;\n"+"X-Generator: Poedit 3.9\n"++#. ---- Entries for the hledger command line (some, like month names, also shown by hledger-ui and hledger-web). ----+#. "Key term" marks an entry whose mistranslation would mislead about money or data: use your country's standard accounting term (eg from official IFRS translations), and review these first.+#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "January"+msgstr "1 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "February"+msgstr "2 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "March"+msgstr "3 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "April"+msgstr "4 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "May"+msgstr "5 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "June"+msgstr "6 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "July"+msgstr "7 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "August"+msgstr "8 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "September"+msgstr "9 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "October"+msgstr "10 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "November"+msgstr "11 月"++#. stand-alone (nominative) month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month"+msgid "December"+msgstr "12 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jan"+msgstr "1 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Feb"+msgstr "2 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Mar"+msgstr "3 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Apr"+msgstr "4 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "May"+msgstr "5 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jun"+msgstr "6 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Jul"+msgstr "7 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Aug"+msgstr "8 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Sep"+msgstr "9 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Oct"+msgstr "10 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Nov"+msgstr "11 月"++#. short stand-alone month names, as used in a column heading.+#: hledger-lib/Hledger/Utils/I18n.hs+msgctxt "month abbrev"+msgid "Dec"+msgstr "12 月"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+msgid "Report details"+msgstr "报表明细"++#: hledger/Hledger/Cli/Chart.hs+msgid "Total"+msgstr "总计"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Assets"+msgstr "资产"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balancesheet.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Liabilities"+msgstr "负债"++#. Key term+#. 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.+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Chart.hs+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity"+msgstr "权益"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Revenues"+msgstr "收入"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Expenses"+msgstr "支出"++# machine-translated, please review+#. in a balance chart grouped by account type, the group of accounts with no known type.+#: hledger/Hledger/Cli/Chart.hs+msgid "Other"+msgstr "其他"++#: hledger/Hledger/Cli/Chart.hs+msgid "Balance"+msgstr "余额"++#. the hint below the commodity filter row.+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Total"+msgstr "总计"++#. Key term+#: hledger/Hledger/Cli/Chart.hs hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "Net:"+msgstr "净额:"++# machine-translated, please review+#. after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "…and {n} more"+msgid_plural "…and {n} more"+msgstr[0] "…及其他 {n} 项"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other {parent} ({n} account)"+msgid_plural "other {parent} ({n} accounts)"+msgstr[0] "其他 {parent}({n} 个账户)"++# machine-translated, please review+#: hledger/Hledger/Cli/Chart.hs+#, python-brace-format+msgid "other ({n} account)"+msgid_plural "other ({n} accounts)"+msgstr[0] "其他({n} 个账户)"++#. the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends". {clarification} brings its own leading space when present.+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#, python-brace-format+msgid "{report} {dates}{clarification}{valuation}"+msgstr "{dates}{clarification}{valuation} {report}"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Period-End Value Changes)"+msgstr "(期末价值变动)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Period-End Value Changes)"+msgstr "(期末价值累计变动)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Incremental Gain)"+msgstr "(增量收益)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Gain)"+msgstr "(累积增益)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Gain)"+msgstr "(历史收益)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Balance Changes)"+msgstr "(余额变动)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Cumulative Ending Balances)"+msgstr "(累计期末余额)"++#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+msgid "(Historical Ending Balances)"+msgstr "(历史期末余额)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", converted to cost"+msgstr ",转换为成本"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at posting date"+msgstr ",按发布日估值"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", valued at period ends"+msgstr ",按期末估值"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid ", current value"+msgstr ",当前值"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/CompoundBalanceCommand.hs+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid ", valued at {date}"+msgstr ",估值日期为 {date}"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Budget Report"+msgstr "预算报告"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Multi-period Balance Report"+msgstr "多期间余额报表"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Balance Report"+msgstr "余额报告"++#. the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "{report} in {dates}{valuation}:"+msgstr "{dates} {valuation} {report}:"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Period-end value changes"+msgstr "期末价值变动"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative period-end value changes"+msgstr "期末累计价值变动"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Incremental gain"+msgstr "增量收益"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative gain"+msgstr "累积增益"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical gain"+msgstr "历史收益"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Posting counts"+msgstr "分录数"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Cumulative posting counts"+msgstr "累计分录数"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Historical posting counts"+msgstr "历史分录数"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Transaction counts"+msgstr "交易数"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Balance changes"+msgstr "余额变动"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (cumulative)"+msgstr "期末余额(累计)"++#: hledger/Hledger/Cli/Commands/Balance.hs+msgid "Ending balances (historical)"+msgstr "期末余额(历史数据)"++#. the budget report title, eg "Budget performance in 2024, valued at period ends:".+#: hledger/Hledger/Cli/Commands/Balance.hs+#, python-brace-format+msgid "Budget performance in {dates}{valuation}:"+msgstr "{dates}{valuation} 期间的预算执行情况:"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Commodity"+msgstr "商品"++#: hledger/Hledger/Cli/Commands/Balance.hs+#: hledger/Hledger/Cli/Commands/Balance/Internal.hs+msgctxt "column heading"+msgid "Average"+msgstr "平均"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Balance Sheet"+msgstr "资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Daily Balance Sheet"+msgstr "每日资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Weekly Balance Sheet"+msgstr "每周资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biweekly Balance Sheet"+msgstr "双周资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Monthly Balance Sheet"+msgstr "月度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Bimonthly Balance Sheet"+msgstr "双月资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Quarterly Balance Sheet"+msgstr "季度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Half-yearly Balance Sheet"+msgstr "半年度资产负债表"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Yearly Balance Sheet"+msgstr "年度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Biennial Balance Sheet"+msgstr "两年期资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheet.hs+msgid "Periodic Balance Sheet"+msgstr "定期资产负债表"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Balance Sheet With Equity"+msgstr "包含权益的资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Daily Balance Sheet With Equity"+msgstr "含权益的每日资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Weekly Balance Sheet With Equity"+msgstr "包含权益的每周资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biweekly Balance Sheet With Equity"+msgstr "包含权益的每两周资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Monthly Balance Sheet With Equity"+msgstr "含权益的月度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Bimonthly Balance Sheet With Equity"+msgstr "含权益的双月资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Quarterly Balance Sheet With Equity"+msgstr "含权益的季度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Half-yearly Balance Sheet With Equity"+msgstr "含权益的半年度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Yearly Balance Sheet With Equity"+msgstr "含权益的年度资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Biennial Balance Sheet With Equity"+msgstr "含权益的两年期资产负债表"++#. 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.+#: hledger/Hledger/Cli/Commands/Balancesheetequity.hs+msgid "Periodic Balance Sheet With Equity"+msgstr "包含权益的定期资产负债表"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cashflow Statement"+msgstr "现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Daily Cashflow Statement"+msgstr "每日现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Weekly Cashflow Statement"+msgstr "每周现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biweekly Cashflow Statement"+msgstr "双周现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Monthly Cashflow Statement"+msgstr "月度现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Bimonthly Cashflow Statement"+msgstr "双月现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Quarterly Cashflow Statement"+msgstr "季度现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Half-yearly Cashflow Statement"+msgstr "半年度现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Yearly Cashflow Statement"+msgstr "年度现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Biennial Cashflow Statement"+msgstr "两年期现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Periodic Cashflow Statement"+msgstr "定期现金流量表"++#. 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.+#: hledger/Hledger/Cli/Commands/Cashflow.hs+msgid "Cash flows"+msgstr "现金流"++# machine-translated, please review+#. a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Values and gains exclude holdings with no market price: {commodities}"+msgstr "市值和收益不包括没有市场价格的持仓:{commodities}"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised gain"+msgstr "已实现收益"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised gain"+msgstr "未实现收益"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Realised loss"+msgstr "已实现亏损"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unrealised loss"+msgstr "未实现亏损"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Net gain"+msgstr "净收益"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Cost"+msgstr "成本"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "No market price"+msgstr "无市场价格"++# machine-translated, please review+#. Key term+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Value"+msgstr "市值"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Avg cost"+msgstr "平均成本"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit/Avg cost"+msgstr "单位/平均成本"++# machine-translated, please review+#. the holdings table's cost column heading, translated where it is displayed.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Unit cost"+msgstr "单位成本"++# machine-translated, please review+#. a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+msgstr "总市值、未实现收益、未实现收益% 和 XIRR 的合计不包括没有市场价格的持仓:{commodities}"++# machine-translated, please review+#. a note below the holdings table; {n} is the number of closed (fully disposed) positions.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "RGain and XIRR totals include {n} closed position, not shown"+msgid_plural "RGain and XIRR totals include {n} closed positions, not shown"+msgstr[0] "已实现收益和 XIRR 的合计包括 {n} 个未显示的已平仓持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}"+msgstr "{holdings},{dates}"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains in each period"+msgstr "{holdings},{dates},各期间收益"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#, python-brace-format+msgid "{holdings}, {dates}, gains since {start}"+msgstr "{holdings},{dates},自 {start} 以来的收益"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Daily holdings"+msgstr "每日持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Weekly holdings"+msgstr "每周持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biweekly holdings"+msgstr "双周持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Monthly holdings"+msgstr "月度持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Bimonthly holdings"+msgstr "双月持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Quarterly holdings"+msgstr "季度持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Half-yearly holdings"+msgstr "半年度持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Yearly holdings"+msgstr "年度持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Biennial holdings"+msgstr "两年期持仓"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "Periodic holdings"+msgstr "定期持仓"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Holdings"+msgstr "持仓"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Units"+msgstr "数量"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Unit price"+msgstr "单价"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total cost"+msgstr "总成本"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total value"+msgstr "总市值"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain"+msgstr "未实现收益"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "UGain%"+msgstr "未实现收益%"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "RGain"+msgstr "已实现收益"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "XIRR"+msgstr "XIRR"++# machine-translated, please review+#. 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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(no holdings)"+msgstr "(无持仓)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Date"+msgstr "日期"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}"+msgstr "{date} 的持仓"++# machine-translated, please review+#. 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.+#. the holdings page's heading; {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.+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#, python-brace-format+msgid "Holdings on {date}, gains in {period}"+msgstr "{date} 的持仓,{period} 的收益"++# machine-translated, please review+#. follows the holdings report's closed positions note, naming the flag that shows them.+#: hledger/Hledger/Cli/Commands/Holdings.hs+msgid "(see -E)"+msgstr "(参见 -E)"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Age"+msgstr "持有天数"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Weight"+msgstr "权重"++# machine-translated, please review+#. the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+#: hledger/Hledger/Cli/Commands/Holdings.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Account"+msgstr "账户"++# machine-translated, please review+#. the heading of the holdings table's totals row.+#: hledger/Hledger/Cli/Commands/Holdings.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Total:"+msgstr "总计:"++#. Key term+#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Income Statement"+msgstr "损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Daily Income Statement"+msgstr "每日损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Weekly Income Statement"+msgstr "每周损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biweekly Income Statement"+msgstr "双周损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Monthly Income Statement"+msgstr "月度损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Bimonthly Income Statement"+msgstr "双月损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Quarterly Income Statement"+msgstr "季度损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Half-yearly Income Statement"+msgstr "半年度损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Yearly Income Statement"+msgstr "年度损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Biennial Income Statement"+msgstr "两年期损益表"++#. 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.+#: hledger/Hledger/Cli/Commands/Incomestatement.hs+msgid "Periodic Income Statement"+msgstr "定期损益表"++#: hledger/Hledger/Cli/Commands/Register.hs+msgid "Register"+msgstr "明细账"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger/Hledger/Cli/Commands/Run.hs hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Show:"+msgstr "显示:"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Titles"+msgstr "标题"++# machine-translated, please review+#: hledger/Hledger/Cli/Commands/Run.hs+msgid "Charts"+msgstr "图表"++#: hledger/Hledger/Cli/Commands/Run.hs+msgid "All"+msgstr "全部"++#. ---- Entries for hledger-ui. ----+#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account balances"+msgstr "账户余额"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "account changes"+msgstr "账户变更"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "cash balances"+msgstr "现金余额"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "balance sheet balances"+msgstr "资产负债表余额"++#: hledger-ui/Hledger/UI/AccountsScreen.hs+msgid "income statement changes"+msgstr "损益表变动"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Cash accounts"+msgstr "现金账户"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Balance sheet accounts"+msgstr "资产负债表账户"++#. the menu screen's entries; translated when drawn.+#: hledger-ui/Hledger/UI/UIScreens.hs+msgid "Income statement accounts"+msgstr "损益表账户"++#. the menu screen's entries; translated when drawn.+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#. the browser tab title of this page.+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-ui/Hledger/UI/UIScreens.hs hledger-web/Hledger/Web/App.hs+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "All accounts"+msgstr "所有账户"++# machine-translated, please review+#. ---- Entries for hledger-web. ----+#: hledger-web/Hledger/Web/App.hs+msgid "Total at cost:"+msgstr "按成本合计:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account, converted to cost. Not zero when something is unbalanced."+msgstr "所有账户换算为成本后的合计。有不平衡之处时不为零。"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "Total at value:"+msgstr "按市值合计:"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains."+msgstr "所有账户按市值的合计。当价值发生变化而没有分录记录相应的收益或亏损(例如未实现的投资收益)时,不为零。"++# machine-translated, please review+#: hledger-web/Hledger/Web/App.hs+msgid "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity."+msgstr "所有账户的合计。有不平衡之处时不为零,例如未使用 --infer-equity 而用 @ 进行的换算。"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+#, python-brace-format+msgid "Balances on {date}"+msgstr "{date} 的余额"++# machine-translated, please review+#. above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date"+msgstr "各账户在这一天结束时的余额:搜索日期的结束日,否则为日记账的最后日期"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Journal"+msgstr "日记账"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show general journal entries, most recent first"+msgstr "显示总账分录,最近的分录在前"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Balance sheet"+msgstr "资产负债表"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show assets, liabilities, and net worth"+msgstr "列示资产、负债和净值"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Income statement"+msgstr "损益表"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show revenues and expenses"+msgstr "显示收入和支出"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Cashflow statement"+msgstr "现金流量表"++#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show changes in liquid assets"+msgstr "显示流动资产的变动"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show investment holdings, lots, and gains"+msgstr "显示投资持仓、批次和收益"++# machine-translated, please review+#. the report links above each report page and in the sidebar: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/App.hs+msgid "Show the balances of all accounts, by period, like the balance command"+msgstr "按期间显示所有账户的余额,如同 balance 命令"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Showing {first} to {last} of {total} transactions"+msgstr "显示第 {first} 至 {last} 笔交易(共 {total} 笔)"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show page {n}"+msgstr "显示第 {n} 页"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Page {n}"+msgstr "第 {n} 页"++#: hledger-web/Hledger/Web/Paging.hs+#, python-brace-format+msgid "Show only {year}"+msgstr "仅显示 {year}"++# machine-translated, please review+#. the hint below the years row.+#: hledger-web/Hledger/Web/Paging.hs+msgid "Shift-click selects a range of years."+msgstr "按住 Shift 点击可选择一段年份范围。"++#. the label before a report's interval links.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Interval:"+msgstr "间隔:"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show one column for the whole period"+msgstr "针对整个期间显示列"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "interval"+msgid "None"+msgstr "没有任何"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Yearly"+msgstr "每年"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per year"+msgstr "按年份显示列"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Quarterly"+msgstr "每季"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per quarter"+msgstr "按季度显示列"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Monthly"+msgstr "每月度"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per month"+msgstr "按月显示列"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Weekly"+msgstr "每周"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per week"+msgstr "按周显示列"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Daily"+msgstr "每日"++#. the interval links above a report: each link's text, and its tooltip.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show a column per day"+msgstr "按天显示列"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how much each balance changed in each period"+msgstr "展示每个期间各项余额的变化幅度"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Cumulative totals"+msgstr "累计总额"++# machine-translated, please review+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance's change since the start of the report (--cumulative)"+msgstr "显示每个余额自报表开始以来的变动(--cumulative)"++#. Key term+#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Ending balances"+msgstr "期末余额"++#. the label before a report's accumulation mode links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show each balance at the end of each period, including everything before it"+msgstr "显示每个期间结束时的余额,包括该期间之前的所有内容"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Calculate:"+msgstr "计算:"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show sums of postings"+msgstr "显示分录的合计"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "calculation"+msgid "Sums"+msgstr "合计"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value change"+msgstr "价值变动"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show how period-end market values changed (--valuechange)"+msgstr "显示期末市值的变动(--valuechange)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unrealized gain"+msgstr "未实现收益"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show unrealized capital gains: market value minus cost (--gain)"+msgstr "显示未实现资本收益:市值减去成本(--gain)"++# machine-translated, please review+#. the label before a report's calculation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Count the postings instead of summing them (--count)"+msgstr "统计分录数而不是求和(--count)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Accounts:"+msgstr "账户:"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a flat list (--flat)"+msgstr "以平铺列表显示账户(--flat)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "List"+msgstr "列表"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show accounts as a tree (--tree)"+msgstr "以树形显示账户(--tree)"++# machine-translated, please review+#. the label before a report's list/tree links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "accounts"+msgid "Tree"+msgstr "树形"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Sort:"+msgstr "排序:"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By account"+msgstr "按账户"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by account display order"+msgstr "按账户显示顺序排列各行"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "By amount"+msgstr "按金额"++# machine-translated, please review+#. the label before a report's sort links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Sort rows by their amounts, largest first (-S)"+msgstr "按金额排列各行,最大的在前(-S)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart:"+msgstr "图表:"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Diverging"+msgstr "发散"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's amounts in one bar, above and below zero (--chart=diverging)"+msgstr "将每个期间的金额绘制在一根柱中,分列零线上下(--chart=diverging)"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped"+msgstr "分组"++# machine-translated, please review+#. the label before a report's chart layout links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Chart each period's account types in bars side by side (--chart=grouped)"+msgstr "将每个期间的账户类型绘制为并排的柱(--chart=grouped)"++# machine-translated, please review+#. the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "Depth {depth}"+msgstr "层级 {depth}"++# machine-translated, please review+#. no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "depth"+msgid "all"+msgstr "不限"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "As recorded"+msgstr "按记录"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Cost"+msgstr "按成本"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgctxt "amounts"+msgid "Value"+msgstr "按市值"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Percentages"+msgstr "百分比"++# machine-translated, please review+#. the grouped chart layout, in the list of options in effect.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Grouped chart"+msgstr "分组图表"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Total"+msgstr "总计"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/ReportPage.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "column"+msgid "Average"+msgstr "平均"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Inferred prices"+msgstr "推断的价格"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances hidden"+msgstr "隐藏零余额"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Zero balances shown"+msgstr "显示零余额"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Lots shown"+msgstr "显示批次"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Costs shown"+msgstr "显示成本"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions shown"+msgstr "显示已平仓持仓"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Closed positions hidden"+msgstr "隐藏已平仓持仓"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Secondary dates"+msgstr "次要日期"++# machine-translated, please review+#. options in effect, listed on the closed options disclosure.+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Equity shown"+msgstr "显示权益"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not calculate percentages:"+msgstr "无法计算百分比:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Could not parse the reporting interval:"+msgstr "无法解析报表间隔:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Unknown amount conversion:"+msgstr "未知的金额换算方式:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+#, python-brace-format+msgid "The {name} parameter has a value this page does not know:"+msgstr "参数 {name} 的值不被此页面识别:"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."+msgstr "价值变动和收益按期末市值计算:请省略 value 参数,或使用 value=end。"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Gains compare market value against cost, so they do not combine with value=cost."+msgstr "收益是市值与成本的比较,因此不能与 value=cost 同时使用。"++# machine-translated, please review+#: hledger-web/Hledger/Web/ReportPage.hs+msgid "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."+msgstr "此报表针对单一日期,因此 value=then 不适用:请使用 value=end、value=now 或某个日期。"++#: hledger-web/Hledger/Web/ReportPage.hs+msgid "Show this report for this period"+msgstr "显示该期间的这份报告"++#: hledger-web/Hledger/Web/Handler/AddR.hs+msgid "Transaction added."+msgstr "交易已添加。"++#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title}, filtered"+msgstr "{title},已筛选"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+msgid "balance - hledger-web"+msgstr "余额 - hledger-web"++# machine-translated, please review+#. the name of a depth 0 report's one row, all accounts in one.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgctxt "accounts"+msgid "All"+msgstr "全部"++# machine-translated, please review+#. the hint below the account type filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Shift-click selects several types."+msgstr "按住 Shift 点击可选择多个类型。"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/BalanceR.hs+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+#: hledger-web/Hledger/Web/Handler/JournalR.hs+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Shift-click selects several commodities."+msgstr "按住 Shift 点击可选择多个商品。"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Failed to load journal: {error}"+msgstr "无法加载日记账:{error}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#, python-brace-format+msgid "Saved journal {file}"+msgstr "已保存日记账 {file}"++#: hledger-web/Hledger/Web/Handler/EditR.hs+#: hledger-web/Hledger/Web/Handler/MiscR.hs+msgid "Edit journal"+msgstr "编辑日记账"++# machine-translated, please review+#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "holdings - hledger-web"+msgstr "持仓 - hledger-web"++# machine-translated, please review+#. the tooltip of an account heading or lot's register link.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this account's register"+msgstr "显示此账户的明细账"++# machine-translated, please review+#. the tooltip of a position's register link, which filters to its commodity.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show this holding's register"+msgstr "显示此持仓的明细账"++# machine-translated, please review+#. the tooltip of a period's date in the holdings page's table with an interval.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the holdings on this date"+msgstr "显示该日期的持仓"++# machine-translated, please review+#. the link after the holdings page's closed positions note, in parentheses.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "show them"+msgstr "显示它们"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Gains:"+msgstr "收益:"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "In each period"+msgstr "各期间"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains during each period"+msgstr "显示每个期间内的收益"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since report start"+msgstr "自报表开始"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since the report's start date, up to each period's end"+msgstr "显示从报表开始日期到各期间结束的收益"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Since acquisition"+msgstr "自购入"++# machine-translated, please review+#. the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.+#: hledger-web/Hledger/Web/Handler/HoldingsR.hs+msgid "Show the gains since each holding was acquired, up to each period's end"+msgstr "显示从每项持仓购入到各期间结束的收益"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "General Journal"+msgstr "通用日记账"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account}"+msgstr "{account} 的交易"++#: hledger-web/Hledger/Web/Handler/JournalR.hs+#, python-brace-format+msgid "Transactions in {account} (excluding subaccounts)"+msgstr "{account} 账户的交易(不含子账户)"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/JournalR.hs+msgid "journal - hledger-web"+msgstr "日记账 - hledger-web"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "all accounts"+msgstr "所有账户"++#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#, python-brace-format+msgid "{account} (excluding subaccounts)"+msgstr "{account}(不包括子账户)"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Historical Total"+msgstr "历史总计"++#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgctxt "column heading"+msgid "Period Total"+msgstr "期间总计"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance from the start of this period"+msgstr "点击以显示自本期间开始的累计余额"++# machine-translated, please review+#. the hint below the commodity filter row.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "Click to show the running balance including everything before this period"+msgstr "点击以显示包含本期间之前全部内容的累计余额"++#. the browser tab title of this page.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+msgid "register - hledger-web"+msgstr "明细账 - hledger-web"++# machine-translated, please review+#. a chart legend's entry for amounts written without a commodity symbol.+#: hledger-web/Hledger/Web/Handler/RegisterR.hs+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "no symbol"+msgstr "无符号"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet with equity - hledger-web"+msgstr "包含权益的资产负债表 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "balance sheet - hledger-web"+msgstr "资产负债表 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "income statement - hledger-web"+msgstr "损益表 - hledger-web"++#. the browser tab titles of the statement pages.+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "cashflow statement - hledger-web"+msgstr "现金流量表 - hledger-web"++# machine-translated, please review+#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "All the accounts this report shows have zero balances, which are hidden. Press z to show them."+msgstr "本报告中显示的所有账户余额均为零,且处于隐藏状态。请按“z”键显示这些账户。"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "+msgstr "未找到本报告所显示的那些类型的账户。请声明账户类型,或使用 hledger 标准的顶层账户名称。"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "How hledger finds account types"+msgstr "hledger 如何识别账户类型"++#: hledger-web/Hledger/Web/Handler/StatementsR.hs+msgid "Nothing matches this search in this period."+msgstr "在此期间,没有符合此搜索条件的内容。"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser."+msgstr "编码错误:'{error}'。如果您的文件不是 UTF-8 编码,请尝试使用“编辑表单”,浏览器应会处理转码。"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+#, python-brace-format+msgid "File {file} uploaded successfully"+msgstr "文件 {file} 上传成功"++#: hledger-web/Hledger/Web/Handler/UploadR.hs+msgid "Upload journal"+msgstr "上传日记账"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Close"+msgstr "关闭"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#: hledger-web/templates/journal.hamlet+msgid "Add a transaction"+msgstr "添加交易"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Account {n}"+msgstr "账户 {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Amount {n}"+msgstr "数量 {n}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Invalid date format"+msgstr "日期格式无效"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Date"+msgstr "日期"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgctxt "placeholder"+msgid "Description"+msgstr "描述"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing amount"+msgstr "缺失金额"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Missing account"+msgstr "账户丢失"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+#, python-brace-format+msgid "Invalid value: {error}"+msgstr "无效值:{error}"++#: hledger-web/Hledger/Web/Widget/AddForm.hs+msgid "Postings validation failed"+msgstr "过账验证失败"++# machine-translated, please review+#. in a report page's chart, before the commodities that can be charted.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Commodity"+msgstr "商品"++# machine-translated, please review+#. a tooltip; c is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the chart (c)"+msgstr "显示/隐藏图表(c)"++# machine-translated, please review+#. a small disclosure button above a report page's chart, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Chart"+msgstr "图表"++# machine-translated, please review+#. a tooltip; d is the keyboard shortcut, which is not translated.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Show or hide the data (d)"+msgstr "显示/隐藏数据(d)"++# machine-translated, please review+#. a small disclosure button above a report page's data table, showing or hiding it.+#: hledger-web/Hledger/Web/Widget/Chart.hs+msgid "Data"+msgstr "数据"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the options that reshape this view"+msgstr "显示用于调整此视图的选项"++# machine-translated, please review+#. the disclosure hiding each page's rows of report controls: its text, and its tooltip.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Options"+msgstr "选项"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}"+msgstr "{dates} 的{title}"++# machine-translated, please review+#. a journal or register page's heading when the search has dates, eg "General Journal in 2024".+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "{title} in {dates}, filtered"+msgstr "{dates} 的{title},已筛选"++# machine-translated, please review+#. the tooltip on the muted control rows of the journal and register pages.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "These controls take effect on the report pages"+msgstr "这些控件在报表页面上生效"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Prices:"+msgstr "价格:"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Declared"+msgstr "已声明"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value amounts using declared market prices (P directives) only"+msgstr "仅使用已声明的市场价格(P 指令)对金额估值"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Inferred too"+msgstr "含推断"++# machine-translated, please review+#. the label before a page's market price source links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Infer market prices from transaction costs too (--infer-market-prices)"+msgstr "也从交易成本推断市场价格(--infer-market-prices)"++# machine-translated, please review+#. the label before a report's depth links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Depth:"+msgstr "层级:"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only the total (depth 0)"+msgstr "仅显示总计(层级 0)"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts at every depth"+msgstr "显示所有层级的账户"++# machine-translated, please review+#. the tooltips of a report's depth links.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show accounts down to depth {depth}"+msgstr "显示到第 {depth} 层的账户"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Amounts:"+msgstr "金额:"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in the commodities they were recorded in"+msgstr "以记录时的商品显示金额"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At cost"+msgstr "按成本"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their cost, as recorded in transactions (-B)"+msgstr "显示按交易中记录的成本换算后的金额(-B)"++# machine-translated, please review+#. Key term+#. the label before a report's amount conversion links, and the links' text and tooltips.+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "At market value"+msgstr "按市值"++# machine-translated, please review+#. the label before a report's amount conversion links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts converted to their market value at the end of each period, using market prices (-V)"+msgstr "显示按各期末市场价格换算为市值的金额(-V)"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Zero balances:"+msgstr "零余额:"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hide accounts whose balances are zero"+msgstr "隐藏余额为零的账户"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Hidden"+msgstr "隐藏"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts whose balances are zero"+msgstr "显示余额为零的账户"++# machine-translated, please review+#. the label before the links that show or hide zero balances, and the links' text and tooltips.+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Shown"+msgstr "显示"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Equity:"+msgstr "权益:"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and net worth, as the balancesheet command does"+msgstr "显示资产、负债和净值,如同 balancesheet 命令"++# machine-translated, please review+#. the label before the balance sheet's links that hide or show equity, and the links' tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show assets, liabilities, and equity, as the balancesheetequity command does"+msgstr "显示资产、负债和权益,如同 balancesheetequity 命令"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Status:"+msgstr "状态:"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show transactions of any status"+msgstr "显示任何状态的交易"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "status"+msgid "All"+msgstr "全部"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Unmarked"+msgstr "未标记"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only unmarked transactions (status:)"+msgstr "仅显示未标记的交易(status:)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Pending"+msgstr "待处理"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only pending transactions (status:!)"+msgstr "仅显示待处理的交易(status:!)"++# machine-translated, please review+#. Key term+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cleared"+msgstr "已核对"++# machine-translated, please review+#. the label before a report's status filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cleared transactions (status:*)"+msgstr "仅显示已核对的交易(status:*)"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Postings:"+msgstr "分录:"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show real and virtual postings"+msgstr "显示真实和虚拟分录"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "postings"+msgid "All"+msgstr "全部"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Real"+msgstr "真实"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only real postings, as -R does (real:1)"+msgstr "仅显示真实分录,如同 -R(real:1)"++# machine-translated, please review+#. Key term+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Virtual"+msgstr "虚拟"++# machine-translated, please review+#. the label before a report's real/virtual filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only virtual postings, the parenthesized ones (real:0)"+msgstr "仅显示虚拟分录,即带括号的分录(real:0)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Extra columns:"+msgstr "附加列:"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column totaling each row (-T)"+msgstr "添加一列显示每行的总计(-T)"++# machine-translated, please review+#. the label before a report's extra-column toggles, and the toggles' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Add a column averaging each row (-A)"+msgstr "添加一列显示每行的平均(-A)"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Numbers:"+msgstr "数值:"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show the amounts"+msgstr "显示金额"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "numbers"+msgid "Amounts"+msgstr "金额"++# machine-translated, please review+#. the label before a report's amounts/percentages links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each amount as a percentage of its column's total (-%)"+msgstr "将每个金额显示为其所在列总计的百分比(-%)"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Costs:"+msgstr "成本:"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts without their costs"+msgstr "显示不含成本的金额"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Hidden"+msgstr "隐藏"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts with the costs recorded in the journal"+msgstr "显示含日记账中记录的成本的金额"++# machine-translated, please review+#. the label before the register's cost links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "costs"+msgid "Shown"+msgstr "显示"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#: hledger-web/templates/default-layout.hamlet+msgid "Lots:"+msgstr "批次:"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Aggregate each account's lots"+msgstr "汇总每个账户的批次"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Hidden"+msgstr "隐藏"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show each lot separately (--lots)"+msgstr "分别显示每个批次(--lots)"++# machine-translated, please review+#. the label before a report's lot detail links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "lots"+msgid "Shown"+msgstr "显示"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Closed positions:"+msgstr "已平仓持仓:"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only open positions"+msgstr "仅显示未平仓持仓"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Hidden"+msgstr "隐藏"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Also show fully disposed positions and their realized gains (-E)"+msgstr "同时显示已全部处置的持仓及其已实现收益(-E)"++# machine-translated, please review+#. the label before the holdings page's closed-position links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "closed"+msgid "Shown"+msgstr "显示"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Values:"+msgstr "估值:"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Per cost commodity"+msgstr "按成本商品"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Value each holding in its own cost commodity"+msgstr "以各自的成本商品对每项持仓估值"++# machine-translated, please review+#. the label before the holdings page's valuation links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Convert values and costs to the market valuation commodity (-V)"+msgstr "将市值和成本换算为市场估值商品(-V)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Type:"+msgstr "类型:"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show accounts of every type"+msgstr "显示所有类型的账户"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "account type"+msgid "All"+msgstr "全部"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Asset"+msgstr "资产"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only asset accounts (type:A)"+msgstr "仅显示资产账户(type:A)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Liability"+msgstr "负债"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only liability accounts (type:L)"+msgstr "仅显示负债账户(type:L)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only equity accounts (type:E)"+msgstr "仅显示权益账户(type:E)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Revenue"+msgstr "收入"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only revenue accounts (type:R)"+msgstr "仅显示收入账户(type:R)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Expense"+msgstr "支出"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only expense accounts (type:X)"+msgstr "仅显示支出账户(type:X)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Cash"+msgstr "现金"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only cash accounts (type:C)"+msgstr "仅显示现金账户(type:C)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Conversion"+msgstr "换算"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only conversion accounts (type:V)"+msgstr "仅显示换算账户(type:V)"++# machine-translated, please review+#. Key term+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Gain"+msgstr "收益"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only capital gain accounts (type:G)"+msgstr "仅显示资本收益账户(type:G)"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Imbalance"+msgstr "不平衡"++# machine-translated, please review+#. the label before the account type filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show only imbalance accounts (type:M)"+msgstr "仅显示不平衡账户(type:M)"++# machine-translated, please review+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "List all the commodities"+msgstr "列出所有商品"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Commodity:"+msgstr "商品:"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgid "Show amounts in every commodity"+msgstr "显示所有商品的金额"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+msgctxt "commodity"+msgid "All"+msgstr "全部"++# machine-translated, please review+#. the label before a page's commodity filter links, and the links' text and tooltips.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "Show only amounts in {commodity}"+msgstr "仅显示 {commodity} 的金额"++# machine-translated, please review+#. the note for a balance, or the register chart, showing fewer commodities than it has.+#: hledger-web/Hledger/Web/Widget/Common.hs+#, python-brace-format+msgid "… and {n} more"+msgstr "… 及其他 {n} 项"++#: hledger-web/templates/add-form.hamlet+msgid "Pick a date"+msgstr "选择一个日期"++#: hledger-web/templates/add-form.hamlet+msgid "Add to:"+msgstr "添加:"++#: hledger-web/templates/add-form.hamlet hledger-web/templates/edit-form.hamlet+msgid "Save"+msgstr "保存"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Fold the accounts one level more"+msgstr "将账户再折叠一层"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Open the accounts one level more"+msgstr "将账户再展开一层"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show or hide the balances"+msgstr "显示/隐藏余额"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Balances"+msgstr "余额"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account and subaccounts"+msgstr "显示影响此账户及子账户的交易"++#: hledger-web/templates/balance-report.hamlet+msgid "Show transactions affecting this account but not subaccounts"+msgstr "显示影响此账户但不影响子账户的交易"++#: hledger-web/templates/balance-report.hamlet+msgid "only"+msgstr "仅"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this balance"+msgstr "显示构成此余额的交易"++# machine-translated, please review+#: hledger-web/templates/balance-report.hamlet+msgid "Show the transactions behind this total"+msgstr "显示构成此总计的交易"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Show or hide the sidebar (s)"+msgstr "显示/隐藏侧边栏(s)"++#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."+msgstr "hledger-web 已停止运行。如果十五分钟内没有浏览器窗口显示它,或者程序被手动停止,它就会退出。若要继续使用,请重新启动程序并刷新此页面。"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Leave full window"+msgstr "退出全窗口模式"++#: hledger-web/templates/default-layout.hamlet+msgctxt "search box"+msgid "Search"+msgstr "搜索"++#: hledger-web/templates/default-layout.hamlet+msgid "Enter hledger search patterns to filter the data below"+msgstr "输入 hledger 搜索模式以筛选下方数据"++#: hledger-web/templates/default-layout.hamlet+msgid "Clear search terms"+msgstr "清除搜索词"++#: hledger-web/templates/default-layout.hamlet+msgid "Apply search terms"+msgstr "应用搜索词"++#: hledger-web/templates/default-layout.hamlet+msgid "Manage journal files"+msgstr "管理 journal 文件"++#: hledger-web/templates/default-layout.hamlet+msgid "Show search and general help"+msgstr "显示搜索与常规帮助"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Go to"+msgstr "转到"++#: hledger-web/templates/default-layout.hamlet+msgid "Help"+msgstr "帮助"++#: hledger-web/templates/default-layout.hamlet+msgid "Keyboard shortcuts"+msgstr "快捷键"++#: hledger-web/templates/default-layout.hamlet+msgid "or"+msgstr "或者"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "view this help"+msgstr "查看此帮助"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to any screen"+msgstr "转到任意界面"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "go to the next or previous screen"+msgstr "转到下一个或上一个界面"++#: hledger-web/templates/default-layout.hamlet+msgid "add a transaction"+msgstr "添加交易"++#: hledger-web/templates/default-layout.hamlet+msgid "toggle sidebar"+msgstr "切换侧边栏"++# machine-translated, please review+#. in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.+#: hledger-web/templates/default-layout.hamlet+msgid "set the sidebar's account depth"+msgstr "设置侧边栏的账户层级"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show or hide the sidebar's balances"+msgstr "显示/隐藏侧边栏的余额"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle report options"+msgstr "显示/隐藏报表选项"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's chart"+msgstr "显示/隐藏报表图表"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "select the chart's commodity"+msgstr "选择图表的商品"++# machine-translated, please review+#. in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the chart's net total line"+msgstr "显示/隐藏图表的净额线"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle the report's data"+msgstr "显示/隐藏报表数据"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "toggle full window"+msgstr "切换全窗口模式"++#: hledger-web/templates/default-layout.hamlet+msgid "focus search form"+msgstr "聚焦搜索表单"++# machine-translated, please review+#. in the help, what the Del key does: clear the search box, showing everything again.+#: hledger-web/templates/default-layout.hamlet+msgid "clear the search"+msgstr "清除搜索"++#: hledger-web/templates/default-layout.hamlet+msgid "cancel"+msgstr "取消"++# machine-translated, please review+#. in the help, the heading of the options' keys, listed under the options panel's own labels.+#: hledger-web/templates/default-layout.hamlet+msgid "Report options"+msgstr "报表选项"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "historical end balances / balance changes"+msgstr "历史期末余额 / 余额变动"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "yearly"+msgstr "每年"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "quarterly"+msgstr "每季度"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "monthly"+msgstr "每月"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "weekly"+msgstr "每周"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "daily"+msgstr "每日"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "unmarked"+msgstr "未标记"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "pending"+msgstr "待处理"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "cleared"+msgstr "已核对"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "real only / all"+msgstr "仅真实 / 全部"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "Depth limit:"+msgstr "层级限制:"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "set it"+msgstr "设置"++# machine-translated, please review+#. in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.+#: hledger-web/templates/default-layout.hamlet+msgid "decrease or increase it"+msgstr "减少或增加"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "accounts"+msgid "tree / list"+msgstr "树形 / 列表"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at cost"+msgstr "按成本"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "at market value"+msgstr "按市值"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide zero balances"+msgstr "显示/隐藏零余额"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "show / hide lot details"+msgstr "显示/隐藏批次详情"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "total"+msgstr "总计"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "column"+msgid "average"+msgstr "平均"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "by amount / by account display order"+msgstr "按金额 / 按账户显示顺序"++# machine-translated, please review+#. in the help, below the options' keys.+#: hledger-web/templates/default-layout.hamlet+msgid "Pressed again, an option's key turns it back off."+msgstr "再次按下选项的按键即可关闭该选项。"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgctxt "help heading"+msgid "Search queries"+msgstr "搜索查询"++#: hledger-web/templates/default-layout.hamlet+msgid "Search patterns with spaces should be enclosed in quotes."+msgstr "包含空格的搜索模式应使用引号括起来"++#: hledger-web/templates/default-layout.hamlet+msgid "match account names"+msgstr "匹配账户名称"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match account types (A, L, E, R, X, ...)"+msgstr "匹配账户类型(A、L、E、R、X 等)"++#: hledger-web/templates/default-layout.hamlet+msgid "match dates"+msgstr "匹配日期"++#: hledger-web/templates/default-layout.hamlet+msgid "match status"+msgstr "匹配状态"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction codes"+msgstr "匹配交易代码"++#: hledger-web/templates/default-layout.hamlet+msgid "match transaction descriptions"+msgstr "匹配交易描述"++#: hledger-web/templates/default-layout.hamlet+msgid "match payee part of descriptions"+msgstr "匹配描述中的收款人部分"++#: hledger-web/templates/default-layout.hamlet+msgid "match note part of descriptions"+msgstr "匹配描述中的备注部分"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."+msgstr "匹配不带符号的数值大小;若 N 带符号,则匹配带符号的金额。N 可以带商品符号。"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."+msgstr "按变动额或余额匹配报表行(账户、期间、交易),类似 amt:。N 可以带商品符号。"++#: hledger-web/templates/default-layout.hamlet+msgid "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"+msgstr "匹配货币/商品。必须匹配完整的代码/名称。若要匹配美元符号,请书写"++#: hledger-web/templates/default-layout.hamlet+msgid "match tags, or tag and value"+msgstr "匹配标签,或标签与值"++#: hledger-web/templates/default-layout.hamlet+msgid "match postings' realness/virtualness"+msgstr "匹配发布内容的真实性与虚拟性"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"+msgstr "匹配任意字段(账户、金额、备注、标签、描述、代码),若 REGEX 同时是期间表达式,也匹配日期"++#: hledger-web/templates/default-layout.hamlet+msgid "prepend not: to negate a search term"+msgstr "在搜索词前加上 not:用于否定该搜索词"++#: hledger-web/templates/default-layout.hamlet+msgid "match with a boolean query (and, or, not, ())"+msgstr "与布尔查询(and、or、not、())匹配"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where any posting matches"+msgstr "匹配任意过账项相符的交易"++#: hledger-web/templates/default-layout.hamlet+msgid "match transactions where all postings match"+msgstr "匹配所有过账项均相符的交易"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "another way to set depth limit (can be per account)"+msgstr "设置层级限制的另一种方式(可针对单个账户)"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "More help:"+msgstr "更多帮助:"++# machine-translated, please review+#: hledger-web/templates/default-layout.hamlet+msgid "hledger-web user manual"+msgstr "hledger-web 用户手册"++#: hledger-web/templates/edit-form.hamlet+msgid "Edit file"+msgstr "编辑文件"++#. Key term+#: hledger-web/templates/edit-form.hamlet+#: hledger-web/templates/upload-form.hamlet+msgid "Are you sure? This will overwrite your journal!"+msgstr "确定吗?这会覆盖你的日记!"++#: hledger-web/templates/edit-form.hamlet+msgid "File format help"+msgstr "文件格式帮助"++#: hledger-web/templates/edit-form.hamlet+msgid "Go back"+msgstr "回退"++#: hledger-web/templates/journal.hamlet+msgid "Add a new transaction to the journal"+msgstr "向日记账添加一笔新交易"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Date"+msgstr "日期"++#: hledger-web/templates/journal.hamlet hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Description"+msgstr "描述"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Account"+msgstr "账户"++#: hledger-web/templates/journal.hamlet+msgctxt "column heading"+msgid "Amount"+msgstr "金额"++#: hledger-web/templates/journal.hamlet+msgid "Show the journal entries on this date"+msgstr "显示该日期的日记条目"++#: hledger-web/templates/manage.hamlet+msgid "Your journal's files"+msgstr "你的日记账文件"++#: hledger-web/templates/manage.hamlet+msgctxt "column heading"+msgid "File"+msgstr "文件"++#: hledger-web/templates/manage.hamlet+msgid "Edit"+msgstr "编辑"++#: hledger-web/templates/manage.hamlet hledger-web/templates/upload-form.hamlet+msgid "Upload"+msgstr "上传"++#: hledger-web/templates/manage.hamlet+msgid "Download"+msgstr "下载"++#: hledger-web/templates/paging.hamlet+msgid "Show the newer transactions"+msgstr "显示较新的交易"++#: hledger-web/templates/paging.hamlet+msgid "Newer"+msgstr "较新"++#: hledger-web/templates/paging.hamlet+msgid "Show the older transactions"+msgstr "显示较早的交易"++#: hledger-web/templates/paging.hamlet+msgid "Older"+msgstr "较旧的"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "To/From Account(s)"+msgstr "转入/转出账户"++#: hledger-web/templates/register.hamlet+msgctxt "column heading"+msgid "Amount Out/In"+msgstr "流出/流入金额"++#: hledger-web/templates/register.hamlet+msgid "Show this entry and the other journal entries on its date"+msgstr "显示此条目及同一日期的其他日记条目"++#: hledger-web/templates/register.hamlet+msgid "Balance brought forward"+msgstr "上期结转余额"++#: hledger-web/templates/register.hamlet+msgid "Show the transactions before this period"+msgstr "显示此期间之前的交易"++#: hledger-web/templates/upload-form.hamlet+msgid "Upload to file"+msgstr "上传文件"++#: hledger-web/templates/upload-form.hamlet+msgid "Select file"+msgstr "选择文件"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "Years:"+msgstr "年:"++#: hledger-web/templates/years.hamlet+msgid "Show all years"+msgstr "显示所有年份"++#: hledger-web/templates/years.hamlet+msgctxt "years row"+msgid "All"+msgstr "全部"++# machine-translated, please review+#~ msgid "Next report"+#~ msgstr "下一个报表"++# machine-translated, please review+#~ msgid "Go to the next report"+#~ msgstr "转到下一个报表"++# machine-translated, please review+#~ msgid "Previous report"+#~ msgstr "上一个报表"++# machine-translated, please review+#~ msgid "Go to the previous report"+#~ msgstr "转到上一个报表"++# machine-translated, please review+#~ msgid "Net, at cost:"+#~ msgstr "净额(按成本):"++# machine-translated, please review+#~ msgid "The sum of every account, converted to cost: zero for balanced books; anything left comes from unbalanced virtual postings."+#~ msgstr "所有账户换算为成本后的合计:账目平衡时为零;剩余部分来自未平衡的虚拟分录。"++# machine-translated, please review+#~ msgid "Unbooked gains:"+#~ msgstr "未入账收益:"++# machine-translated, please review+#~ msgid "The sum of every account at market value: appreciation not booked by any entry. If realized gains are booked, this is the unrealized gains."+#~ msgstr "所有账户按市值的合计:未被任何分录入账的增值。若已实现收益已入账,则此即未实现收益。"++# machine-translated, please review+#~ msgid "Net flows:"+#~ msgstr "净流量:"++# machine-translated, please review+#~ msgid "The sum of every account: open positions in each commodity, and the cash that paid for them. Zero when nothing crosses commodities."+#~ msgstr "所有账户的合计:各商品的未平仓持仓及用于购买它们的现金。没有跨商品交易时为零。"++# machine-translated, please review+#~ msgid "Holdings at period ends"+#~ msgstr "各期末持仓"++# machine-translated, please review+#, python-brace-format+#~ msgid "Holdings at period ends, {dates}"+#~ msgstr "各期末持仓,{dates}"++#~ msgid "Unknown balance accumulation mode:"+#~ msgstr "未知的余额累积模式:"++# machine-translated, please review+#~ msgid "Show only the total"+#~ msgstr "仅显示总计"++#~ msgid "Show the transactions that make up this balance"+#~ msgstr "显示构成此余额的交易"++#~ msgid "Show the transactions that make up this total"+#~ msgstr "显示构成此总额的各项交易"++#~ msgid "match any visible field (account, amount, comment, description, code), or a date if REGEX is also a period expression"+#~ msgstr "匹配交易描述匹配任意可见字段(账户、金额、备注、描述、代码),或者在正则表达式同时为周期表达式时匹配日期"++#~ msgid "match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only."+#~ msgstr "匹配无符号数值,或结合有符号“与”运算及有符号数值。仅适用于单一商品数量。"++#~ msgid "Balance sheet with equity"+#~ msgstr "包含权益的资产负债表"++#~ msgid "Show assets, liabilities, and equity"+#~ msgstr "显示资产、负债和权益"++#~ msgid "Show the running balance from the start of this period"+#~ msgstr "显示本期开始以来的累计余额"++#~ msgid "Show the running balance including everything before this period"+#~ msgstr "显示包含本期之前所有项目的累计余额。"++#~ msgid "General"+#~ msgstr "通用"++#~ msgid "The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts"+#~ msgstr "“日记账”视图显示了普通日记账分录,代表了层级账户之间资金(或其他商品)的零和变动"++#~ msgid "The sidebar shows the resulting accounts and their final balances"+#~ msgstr "侧边栏显示了生成的账户及其最终余额"++#~ msgid "The sidebar's report links show the balance sheet, income statement, and cashflow statement, each linking to the other reports"+#~ msgstr "侧边栏中的报表链接指向资产负债表、损益表和现金流量表,且各报表之间相互链接"++#~ msgid "Parent account balances include subaccount balances"+#~ msgstr "父账户余额包含子账户余额"++#~ msgid "Multiple currencies in balances are displayed one above the other"+#~ msgstr "余额中的多种货币呈上下排列显示"++#~ msgid "Click account name links to see transactions affecting that account, with running balance"+#~ msgstr "点击账户名称链接,即可查看影响该账户的交易记录及实时余额"++#~ msgid "Click an amount to see the transactions it is made of, in a register ending on that amount"+#~ msgstr "点击某个金额,即可在以该金额为终值的明细列表中查看构成该金额的各项交易"++#~ msgid "Click date links to see journal entries on that date"+#~ msgstr "点击日期链接,查看该日期的日志条目"++#~ msgid "The balance sheet and income statement show liabilities, equity, and revenues as positive amounts; their registers show them negative, as hledger does"+#~ msgstr "资产负债表和损益表将负债、权益和收入显示为正数;而在账目明细中,它们则显示为负数,这与 hledger 的处理方式一致"++#~ msgctxt "help heading"+#~ msgid "Search"+#~ msgstr "搜索"++#~ msgid "match account types"+#~ msgstr "匹配账户类型"++#~ msgid "clip account names at this depth"+#~ msgstr "在此层级截断账户名称"++#~ msgid "Could not parse the period expression:"+#~ msgstr "无法解析周期表达式:"++#~ msgid "Report:"+#~ msgstr "报告:"++#~ msgid "add a transaction (escape to cancel)"+#~ msgstr "添加交易(按 Esc 键取消)"++#~ msgid "go to the Journal view (home)"+#~ msgstr "转到日记账视图(主页)"++#~ msgid "or maybe"+#~ msgstr "或者也许"++#~ msgid "view this help (escape or click to exit)"+#~ msgstr "查看此帮助(按 Esc 键或点击以退出)"++#~ msgid "Balance report"+#~ msgstr "余额报告"++#~ msgid "Show the balance report: any accounts, by period"+#~ msgstr "显示余额报表:按期间显示任意账户"++#~ msgid "Show the yearly balance report"+#~ msgstr "显示年度余额报告"++#~ msgid "Show the quarterly balance report"+#~ msgstr "显示季度余额报告"++#~ msgid "Show the monthly balance report"+#~ msgstr "显示月度余额报告"++#~ msgid "Show the weekly balance report"+#~ msgstr "显示每周余额报告"++#~ msgid "Show the daily balance report"+#~ msgstr "显示每日余额报表"
+ test/doctests.hs view
@@ -0,0 +1,68 @@+{-+Run doctests in Hledger source files under the current directory+(./Hledger.hs, ./Hledger/**, ./Text/**) using the doctest runner.++https://github.com/sol/doctest#readme++Arguments are case-insensitive file path substrings, to limit the files searched.+--verbose shows files being searched for doctests and progress while running.+--slow reloads ghci between each test (https://github.com/sol/doctest#a-note-on-performance).++Eg, in hledger source dir:++$ make ghci-doctest, :main [--verbose] [--slow] [CIFILEPATHSUBSTRINGS]++or:++$ stack test hledger-lib:test:doctest --test-arguments="--verbose --slow [CIFILEPATHSUBSTRINGS]"++-}+-- This file can't be called doctest.hs ("File name does not match module name")+++{-# LANGUAGE PackageImports #-}++import Control.Monad+import Data.Char+import Data.List+import System.Environment+import "Glob" System.FilePath.Glob+import Test.DocTest++main :: IO ()+main = do+ args <- getArgs+ let+ verbose = "--verbose" `elem` args+ slow = "--slow" `elem` args+ pats = filter (not . ("-" `isPrefixOf`)) args++ -- find source files+ sourcefiles <- (filter (not . isInfixOf "/.") . concat) <$> sequence [+ glob "Hledger.hs"+ ,glob "Hledger/**/*.hs"+ ,glob "Text/**/*.hs"+ ]++ -- filter by patterns (case insensitive infix substring match)+ let+ fs | null pats = sourcefiles+ | otherwise = [f | f <- sourcefiles, let f' = map toLower f, any (`isInfixOf` f') pats']+ where pats' = map (map toLower) pats+ fslen = length fs++ if (null fs)+ then do+ putStrLn $ "No file paths found matching: " ++ unwords pats++ else do+ putStrLn $+ "Loading and searching for doctests in "+ ++ show fslen+ ++ if fslen > 1 then " files, plus any files they import:" else " file, plus any files it imports:"+ when verbose $ putStrLn $ unwords fs++ doctest $+ (if verbose then ("--verbose" :) else id) $ -- doctest >= 0.15.0+ (if slow then id else ("--fast" :)) $ -- doctest >= 0.11.4+ fs
+ test/unittest.hs view
@@ -0,0 +1,13 @@+{-+Run the hledger-lib package's unit tests using the tasty test runner.+-}++import Hledger (tests_Hledger)+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