packages feed

hledger-lib 1.52.4 → 2.0

raw patch · 79 files changed

+55792/−6419 lines, 79 filesdep +blaze-svgdep +safe-exceptionsdep +temporarydep −luciddep ~aesonPVP ok

version bump matches the API change (PVP)

Dependencies added: blaze-svg, safe-exceptions, temporary

Dependencies removed: lucid

Dependency ranges changed: aeson

API changes (from Hackage documentation)

- Hledger.Data: RegularPosting :: PostingType
- Hledger.Data: [jfinalcommentlines] :: Journal -> Text
- Hledger.Data: [jincludefilestack] :: Journal -> [(FilePath, FilePath)]
- Hledger.Data: [ptype] :: Posting -> PostingType
- Hledger.Data: data PostingType
- Hledger.Data: isAccountSubtypeOf :: AccountType -> AccountType -> Bool
- Hledger.Data.Amount: defaultMaxPrecision :: Word8
- Hledger.Data.Json: instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.PostingType
- Hledger.Data.Json: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PostingType
- Hledger.Data.Transaction: TBPExact :: TransactionBalancingPrecision
- Hledger.Data.Transaction: TBPOld :: TransactionBalancingPrecision
- Hledger.Data.Types: RegularPosting :: PostingType
- Hledger.Data.Types: [jfinalcommentlines] :: Journal -> Text
- Hledger.Data.Types: [jincludefilestack] :: Journal -> [(FilePath, FilePath)]
- Hledger.Data.Types: [ptype] :: Posting -> PostingType
- Hledger.Data.Types: data PostingType
- Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.PostingType
- Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.PostingType
- Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.PostingType
- Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.PostingType
- Hledger.Data.Types: isAccountSubtypeOf :: AccountType -> AccountType -> Bool
- Hledger.Query: Sym :: Regexp -> Query
- Hledger.Query: matchesDescription :: Query -> Text -> Bool
- Hledger.Query: matchesPayeeWIP :: Query -> Payee -> Bool
- Hledger.Query: queryIsAmtOrSym :: Query -> Bool
- Hledger.Query: queryIsSym :: Query -> Bool
- Hledger.Read: instance GHC.Show.Show Hledger.Read.LatestDatesForFile
- Hledger.Read: saveLatestDates :: LatestDates -> FilePath -> IO ()
- Hledger.Read: saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()
- Hledger.Read.Common: [auto_posting_tags_] :: InputOpts -> Bool
- Hledger.Read.Common: auto_posting_tags :: HasInputOpts c => Lens' c Bool
- Hledger.Read.Common: clearAccountAliases :: MonadState Journal m => m ()
- Hledger.Read.Common: popParentAccount :: forall (m :: Type -> Type). JournalParser m ()
- Hledger.Read.InputOptions: [auto_posting_tags_] :: InputOpts -> Bool
- Hledger.Read.InputOptions: auto_posting_tags :: HasInputOpts c => Lens' c Bool
- Hledger.Utils.Parse: showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String
- Hledger.Utils.Text: stripquotes :: Text -> Text
- Hledger.Write.Html.Attribute: bottomdoubleborder :: Text
- Hledger.Write.Html.Attribute: concatStyles :: [Text] -> Text
- Hledger.Write.Html.Attribute: doubleborder :: Text
- Hledger.Write.Html.Attribute: topdoubleborder :: Text
- Hledger.Write.Html.Blaze: formatCell :: Lines border => Cell border Html -> Html
- Hledger.Write.Html.Blaze: formatRow :: Lines border => [Cell border Html] -> Html
- Hledger.Write.Html.Blaze: styledTableHtml :: Lines border => [[Cell border Html]] -> Html
- Hledger.Write.Html.HtmlCommon: borderLines :: Lines border => border -> [Text]
- Hledger.Write.Html.HtmlCommon: borderStyles :: Lines border => Cell border text -> [Text]
- Hledger.Write.Html.HtmlCommon: class Lines border => Lines border
- Hledger.Write.Html.HtmlCommon: instance Hledger.Write.Html.HtmlCommon.Lines ()
- Hledger.Write.Html.HtmlCommon: instance Hledger.Write.Html.HtmlCommon.Lines Hledger.Write.Spreadsheet.NumLines
- Hledger.Write.Html.Lucid: formatCell :: Lines border => Cell border Html -> Html
- Hledger.Write.Html.Lucid: formatRow :: Lines border => [Cell border Html] -> Html
- Hledger.Write.Html.Lucid: styledTableHtml :: Lines border => [[Cell border Html]] -> Html
- Hledger.Write.Html.Lucid: toHtml :: forall (m :: Type -> Type). (ToHtml a, Monad m) => a -> HtmlT m ()
- Hledger.Write.Html.Lucid: type Html = Html ()
+ Hledger.Data: AVERAGE :: ReductionMethod
+ Hledger.Data: AVERAGEALL :: ReductionMethod
+ Hledger.Data: AssertDirective :: AssertQuantifier -> Maybe (Interval, DateSpan) -> Text -> Text -> [DateSpan] -> Text -> SourcePos -> AssertDirective
+ Hledger.Data: AssertNone :: AssertQuantifier
+ Hledger.Data: AssertSome :: AssertQuantifier
+ Hledger.Data: FIFO :: ReductionMethod
+ Hledger.Data: FIFOALL :: ReductionMethod
+ Hledger.Data: FastPathStats :: Int -> Int -> Int -> Int -> Map Text Int -> FastPathStats
+ Hledger.Data: HIFO :: ReductionMethod
+ Hledger.Data: HIFOALL :: ReductionMethod
+ Hledger.Data: Imbalance :: AccountType
+ Hledger.Data: JIBlank :: JournalItem
+ Hledger.Data: JIComment :: !Text -> JournalItem
+ Hledger.Data: JICommentBlock :: !Text -> JournalItem
+ Hledger.Data: JIDirective :: !Text -> JournalItem
+ Hledger.Data: JIInclude :: !Text -> JournalItem
+ Hledger.Data: JINonExportedDirective :: !Text -> JournalItem
+ Hledger.Data: JITransaction :: !SourcePos -> JournalItem
+ Hledger.Data: JournalFile :: FilePath -> Text -> Int -> JournalFile
+ Hledger.Data: LIFO :: ReductionMethod
+ Hledger.Data: LIFOALL :: ReductionMethod
+ Hledger.Data: LotId :: !Day -> !Maybe Text -> LotId
+ Hledger.Data: ParsePos :: SourcePos -> Int -> Text -> ParsePos
+ Hledger.Data: RealPosting :: PostingRealness
+ Hledger.Data: SPECID :: ReductionMethod
+ Hledger.Data: [adPeriodText] :: AssertDirective -> Text
+ Hledger.Data: [adPeriod] :: AssertDirective -> Maybe (Interval, DateSpan)
+ Hledger.Data: [adQuantifier] :: AssertDirective -> AssertQuantifier
+ Hledger.Data: [adQueryText] :: AssertDirective -> Text
+ Hledger.Data: [adSkips] :: AssertDirective -> [DateSpan]
+ Hledger.Data: [adSourcePos] :: AssertDirective -> SourcePos
+ Hledger.Data: [adSourceText] :: AssertDirective -> Text
+ Hledger.Data: [caliases] :: Commodity -> [(Amount, SourcePos)]
+ Hledger.Data: [csourcepos] :: Commodity -> SourcePos
+ Hledger.Data: [fpsDeclines] :: FastPathStats -> Map Text Int
+ Hledger.Data: [fpsPricesFast] :: FastPathStats -> Int
+ Hledger.Data: [fpsPricesGeneral] :: FastPathStats -> Int
+ Hledger.Data: [fpsTxnsFast] :: FastPathStats -> Int
+ Hledger.Data: [fpsTxnsGeneral] :: FastPathStats -> Int
+ Hledger.Data: [jasserts] :: Journal -> [AssertDirective]
+ Hledger.Data: [jauxfiles] :: Journal -> [(FilePath, [FilePath])]
+ Hledger.Data: [jfdepth] :: JournalFile -> Int
+ Hledger.Data: [jfpath] :: JournalFile -> FilePath
+ Hledger.Data: [jftext] :: JournalFile -> Text
+ Hledger.Data: [jitems] :: Journal -> [JournalItem]
+ Hledger.Data: [jparseamountstyles] :: Journal -> Set AmountStyle
+ Hledger.Data: [jparseapplyyears] :: Journal -> [Maybe Year]
+ Hledger.Data: [jparsefastpathstats] :: Journal -> FastPathStats
+ Hledger.Data: [jparseincludefilestack] :: Journal -> [(FilePath, FilePath)]
+ Hledger.Data: [jparseoptaliases] :: Journal -> [AccountAlias]
+ Hledger.Data: [jparsepos] :: Journal -> Maybe ParsePos
+ Hledger.Data: [jparsetexts] :: Journal -> Set Text
+ Hledger.Data: [lotDate] :: LotId -> !Day
+ Hledger.Data: [lotLabel] :: LotId -> !Maybe Text
+ Hledger.Data: [ppInput] :: ParsePos -> Text
+ Hledger.Data: [ppOffset] :: ParsePos -> Int
+ Hledger.Data: [ppSourcePos] :: ParsePos -> SourcePos
+ Hledger.Data: [preal] :: Posting -> PostingRealness
+ Hledger.Data: data AssertDirective
+ Hledger.Data: data AssertQuantifier
+ Hledger.Data: data FastPathStats
+ Hledger.Data: data JournalFile
+ Hledger.Data: data JournalItem
+ Hledger.Data: data LotId
+ Hledger.Data: data ParsePos
+ Hledger.Data: data PostingRealness
+ Hledger.Data: data ReductionMethod
+ Hledger.Data: mixedAmountKey :: Amount -> MixedAmountKey
+ Hledger.Data.AccountName: accountNameHasEmptyPart :: AccountName -> Bool
+ Hledger.Data.AccountName: defaultGainAccount :: IsString a => a
+ Hledger.Data.AccountName: defaultImbalanceAccount :: IsString a => a
+ Hledger.Data.AccountName: imbalanceAccountRegex :: Regexp
+ Hledger.Data.AccountName: unrealisedGainAccountRegex :: Regexp
+ Hledger.Data.AccountType: Long :: LotDirection
+ Hledger.Data.AccountType: Short :: LotDirection
+ Hledger.Data.AccountType: accountTypeChoices :: Bool -> String
+ Hledger.Data.AccountType: accountTypeLotDirection :: AccountType -> Maybe LotDirection
+ Hledger.Data.AccountType: accountTypeName :: AccountType -> Text
+ Hledger.Data.AccountType: data LotDirection
+ Hledger.Data.AccountType: instance GHC.Classes.Eq Hledger.Data.AccountType.LotDirection
+ Hledger.Data.AccountType: instance GHC.Classes.Ord Hledger.Data.AccountType.LotDirection
+ Hledger.Data.AccountType: instance GHC.Show.Show Hledger.Data.AccountType.LotDirection
+ Hledger.Data.AccountType: isAccountSubtypeOf :: AccountType -> AccountType -> Bool
+ Hledger.Data.AccountType: isAssetType :: AccountType -> Bool
+ Hledger.Data.AccountType: isEquityType :: AccountType -> Bool
+ Hledger.Data.AccountType: isExpenseType :: AccountType -> Bool
+ Hledger.Data.AccountType: isLiabilityType :: AccountType -> Bool
+ Hledger.Data.AccountType: isRevenueType :: AccountType -> Bool
+ Hledger.Data.AccountType: lotDirectionSign :: LotDirection -> Quantity
+ Hledger.Data.AccountType: parseAccountType :: Bool -> Text -> Either String AccountType
+ Hledger.Data.Amount: [displayLedgerLotSyntax] :: AmountFormat -> Bool
+ Hledger.Data.Amount: addAmountStyle :: Amount -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle
+ Hledger.Data.Amount: amountCostBasis :: Amount -> Amount
+ Hledger.Data.Amount: amountRoundedQuantity :: Amount -> Quantity
+ Hledger.Data.Amount: amountSetCostToBasis :: Amount -> Amount
+ Hledger.Data.Amount: amountSetQuantity :: Quantity -> Amount -> Amount
+ Hledger.Data.Amount: defaultMaxDisplayPrecision :: Word8
+ Hledger.Data.Amount: divideAmountAndUpdatePrecision :: Quantity -> Amount -> Amount
+ Hledger.Data.Amount: divideMixedAmountAndUpdatePrecision :: Quantity -> MixedAmount -> MixedAmount
+ Hledger.Data.Amount: mixedAmountCostBasis :: MixedAmount -> MixedAmount
+ Hledger.Data.Amount: mixedAmountSetFullPrecisionCapped :: MixedAmount -> MixedAmount
+ Hledger.Data.Amount: multiplyQuantities :: Quantity -> Quantity -> Quantity
+ Hledger.Data.Amount: showAmountCostBasisLedger :: Amount -> String
+ Hledger.Data.Amount: showAmountCostBasisLedgerB :: AmountFormat -> Amount -> WideBuilder
+ Hledger.Data.Amount: showAmountQuantity :: Bool -> Amount -> WideBuilder
+ Hledger.Data.Amount: showAmountsDistinctly :: AmountFormat -> Amount -> Amount -> (String, String)
+ Hledger.Data.Amount: showMixedAmountOneLinePartsB :: AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]
+ Hledger.Data.Amount: showMixedAmountsDistinctly :: AmountFormat -> MixedAmount -> MixedAmount -> (String, String)
+ Hledger.Data.Amount: showPriceDirective :: PriceDirective -> Text
+ Hledger.Data.Balancing: [account_lots_tags_] :: BalancingOpts -> Map AccountName Text
+ Hledger.Data.Balancing: [imbalance_account_] :: BalancingOpts -> AccountName
+ Hledger.Data.Balancing: [infer_imbalance_] :: BalancingOpts -> Bool
+ Hledger.Data.Balancing: [lenient_lots_] :: BalancingOpts -> Bool
+ Hledger.Data.Balancing: [lotful_commodities_] :: BalancingOpts -> Set CommoditySymbol
+ Hledger.Data.Balancing: [verbose_balancing_tags_] :: BalancingOpts -> Bool
+ Hledger.Data.Balancing: account_lots_tags :: HasBalancingOpts c => Lens' c (Map AccountName Text)
+ Hledger.Data.Balancing: imbalance_account :: HasBalancingOpts c => Lens' c AccountName
+ Hledger.Data.Balancing: infer_imbalance :: HasBalancingOpts c => Lens' c Bool
+ Hledger.Data.Balancing: journalBalanceTransactionsAndDeferAssertions :: BalancingOpts -> Journal -> Either String (Journal, Maybe String)
+ Hledger.Data.Balancing: lenient_lots :: HasBalancingOpts c => Lens' c Bool
+ Hledger.Data.Balancing: lotful_commodities :: HasBalancingOpts c => Lens' c (Set CommoditySymbol)
+ Hledger.Data.Balancing: postingRoundCalculatedAmounts :: Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)
+ Hledger.Data.Balancing: roundedPostingTagName :: TagName
+ Hledger.Data.Balancing: transactionBalanceError :: Transaction -> [String] -> String
+ Hledger.Data.Balancing: transactionBalancingSum :: Transaction -> MixedAmount
+ Hledger.Data.Balancing: transactionRoundCalculatedAmounts :: Transaction -> Transaction
+ Hledger.Data.Balancing: verbose_balancing_tags :: HasBalancingOpts c => Lens' c Bool
+ Hledger.Data.Currency: cryptocurrencies :: [CurrencyCode]
+ Hledger.Data.Currency: toCurrencyCode :: CurrencySymbol -> CurrencyCode
+ Hledger.Data.Currency: type CurrencyCode = Text
+ Hledger.Data.Currency: type CurrencySymbol = Text
+ Hledger.Data.Dates: reportingintervalp :: forall (m :: Type -> Type). TextParser m Interval
+ Hledger.Data.Dates: showDateSpanAbbrevWith :: TimeLocale -> DateSpan -> Text
+ Hledger.Data.Dates: showDateSpanForQuery :: DateSpan -> Text
+ Hledger.Data.Dates: showDateSpanFull :: DateSpan -> Text
+ Hledger.Data.DayPartition: splitSpanStartEnd :: Bool -> Interval -> DateSpan -> Maybe (Day, Day)
+ Hledger.Data.DayPartition: splitSpanToDateSpans :: Bool -> Interval -> DateSpan -> [DateSpan]
+ Hledger.Data.Errors: decorateExcerpt :: Int -> Maybe (Int, Maybe Int) -> Text -> Text
+ Hledger.Data.Errors: makeCommodityTagErrorExcerpt :: Commodity -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
+ Hledger.Data.Errors: makePostingErrorExcerptByIndex :: Transaction -> Int -> Maybe (Int, Maybe Int) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
+ Hledger.Data.Journal: accountUsesNoLotsWith :: Map AccountName Text -> AccountName -> Bool
+ Hledger.Data.Journal: addAssertDirective :: AssertDirective -> Journal -> Journal
+ Hledger.Data.Journal: addJournalItem :: JournalItem -> Journal -> Journal
+ Hledger.Data.Journal: addTransactionItem :: Transaction -> Journal -> Journal
+ Hledger.Data.Journal: commoditiesAndAliases :: Journal -> Set CommoditySymbol
+ Hledger.Data.Journal: commodityAliases :: Commodity -> [CommoditySymbol]
+ Hledger.Data.Journal: commodityCombine :: Commodity -> Commodity -> Commodity
+ Hledger.Data.Journal: commodityRedeclare :: Commodity -> Commodity -> Commodity
+ Hledger.Data.Journal: convertAliasAmount :: CommodityAliases -> Amount -> (Amount, Quantity)
+ Hledger.Data.Journal: defaultGainAccount :: IsString a => a
+ Hledger.Data.Journal: instance GHC.Show.Show Hledger.Data.Types.AssertDirective
+ Hledger.Data.Journal: journalAccountForType :: AccountName -> AccountType -> Journal -> AccountName
+ Hledger.Data.Journal: journalAccountLotsTags :: Journal -> Map AccountName Text
+ Hledger.Data.Journal: journalAccountUsesNoLots :: Journal -> AccountName -> Bool
+ Hledger.Data.Journal: journalAllFilePaths :: Journal -> [FilePath]
+ Hledger.Data.Journal: journalApplyCommodityAliases :: Journal -> Either String Journal
+ Hledger.Data.Journal: journalBaseCurrency :: Journal -> Maybe (CommoditySymbol, CurrencyCode)
+ Hledger.Data.Journal: journalBaseCurrencyCode :: Journal -> CurrencyCode
+ Hledger.Data.Journal: journalBaseGainAccount :: Journal -> AccountName
+ Hledger.Data.Journal: journalCheckLotsTagValues :: Journal -> Either String Journal
+ Hledger.Data.Journal: journalCommodityAliases :: Journal -> CommodityAliases
+ Hledger.Data.Journal: journalCommodityLotsMethod :: Journal -> CommoditySymbol -> Maybe ReductionMethod
+ Hledger.Data.Journal: journalCommodityUsesLots :: Journal -> CommoditySymbol -> Bool
+ Hledger.Data.Journal: journalGainAccounts :: Journal -> [AccountName]
+ Hledger.Data.Journal: journalInferPostingsTransactedCost :: Journal -> Journal
+ Hledger.Data.Journal: journalLotfulCommodities :: Journal -> Set CommoditySymbol
+ Hledger.Data.Journal: journalTieTransactions :: Journal -> Journal
+ Hledger.Data.Journal: parseReductionMethod :: Text -> Maybe ReductionMethod
+ Hledger.Data.Journal: postingLotsMethod :: Posting -> Maybe ReductionMethod
+ Hledger.Data.Journal: type CommodityAliases = Map CommoditySymbol (CommoditySymbol, Quantity, Maybe AmountStyle)
+ Hledger.Data.JournalChecks: journalCheckAsserts :: Day -> Journal -> Either String ()
+ Hledger.Data.JournalChecks: journalCheckLots :: Journal -> Either String ()
+ Hledger.Data.JournalChecks: journalUndeclaredCommodities :: Journal -> [CommoditySymbol]
+ Hledger.Data.JournalChecks.Assert: journalCheckAsserts :: Day -> Journal -> Either String ()
+ Hledger.Data.Json: instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.PostingRealness
+ Hledger.Data.Json: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.JournalFile
+ Hledger.Data.Json: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PostingRealness
+ Hledger.Data.Lots: isDisposePosting :: Posting -> Bool
+ Hledger.Data.Lots: isGainPosting :: Posting -> Bool
+ Hledger.Data.Lots: isSetAsideGainPosting :: Transaction -> Posting -> Bool
+ Hledger.Data.Lots: journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal
+ Hledger.Data.Lots: journalAveragePoolCosts :: Journal -> Maybe Day -> Map (AccountName, CommoditySymbol) Amount
+ Hledger.Data.Lots: journalAveragePoolTotals :: Journal -> Maybe Day -> Map (AccountName, CommoditySymbol) (Quantity, Amount)
+ Hledger.Data.Lots: journalCalculateLots :: Bool -> Journal -> Either String Journal
+ Hledger.Data.Lots: journalCheckAcquireBasis :: Journal -> Either String Journal
+ Hledger.Data.Lots: journalCheckLotsMethodCoherence :: Journal -> Either String Journal
+ Hledger.Data.Lots: journalClassifyLotPostings :: Bool -> Journal -> Journal
+ Hledger.Data.Lots: journalCollapseLotDetail :: Journal -> Journal
+ Hledger.Data.Lots: journalHasLotFeatures :: Journal -> Bool
+ Hledger.Data.Lots: journalLotDirection :: Journal -> AccountName -> Maybe LotDirection
+ Hledger.Data.Lots: journalStripBalancerCopiedBases :: Journal -> Journal
+ Hledger.Data.Lots: journalTagGainPostings :: Bool -> Bool -> Journal -> Either String Journal
+ Hledger.Data.Lots: lotBaseAccount :: AccountName -> AccountName
+ Hledger.Data.Lots: lotDirectionOf :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe LotDirection
+ Hledger.Data.Lots: lotSubaccountName :: AccountName -> Maybe Text
+ Hledger.Data.Lots: mergeCostBasis :: CostBasis -> CostBasis -> Either String CostBasis
+ Hledger.Data.Lots: parseLotName :: (String -> Maybe Amount) -> Text -> Either String CostBasis
+ Hledger.Data.Lots: resolveReductionMethodForAccount :: Journal -> AccountName -> CommoditySymbol -> (ReductionMethod, String)
+ Hledger.Data.Lots: showLotName :: CostBasis -> Text
+ Hledger.Data.Lots: transactionAutoSplitFeeOutflows :: Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction
+ Hledger.Data.Lots: transactionHasLotfulAmounts :: Set CommoditySymbol -> Transaction -> Bool
+ Hledger.Data.Lots: transactionTagGainPostings :: Bool -> Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction
+ Hledger.Data.Period: showPeriodAbbrevWith :: TimeLocale -> Period -> Text
+ Hledger.Data.PeriodicTransaction: periodicTransactionDates :: PeriodicTransaction -> DateSpan -> [Day]
+ Hledger.Data.Posting: AmountCols :: !Int -> !Int -> !Int -> AmountCols
+ Hledger.Data.Posting: LayoutDecimal :: !Int -> PostingLayout
+ Hledger.Data.Posting: LayoutHledger1 :: PostingLayout
+ Hledger.Data.Posting: PostingWidths :: !Int -> !Int -> !Int -> !Int -> !Int -> PostingWidths
+ Hledger.Data.Posting: [acAssDecMark] :: AmountCols -> !Int
+ Hledger.Data.Posting: [acDecMark] :: AmountCols -> !Int
+ Hledger.Data.Posting: [acEquals] :: AmountCols -> !Int
+ Hledger.Data.Posting: [pwAcct] :: PostingWidths -> !Int
+ Hledger.Data.Posting: [pwAsnLeft] :: PostingWidths -> !Int
+ Hledger.Data.Posting: [pwLeft] :: PostingWidths -> !Int
+ Hledger.Data.Posting: [pwOperator] :: PostingWidths -> !Int
+ Hledger.Data.Posting: [pwRight] :: PostingWidths -> !Int
+ Hledger.Data.Posting: amountIntegerWidth :: AmountFormat -> Amount -> Int
+ Hledger.Data.Posting: balanceAssertionAmountB :: AmountFormat -> BalanceAssertion -> WideBuilder
+ Hledger.Data.Posting: balanceAssertionOperatorB :: BalanceAssertion -> WideBuilder
+ Hledger.Data.Posting: commentPrependTag :: Text -> Tag -> Text
+ Hledger.Data.Posting: data AmountCols
+ Hledger.Data.Posting: data PostingLayout
+ Hledger.Data.Posting: data PostingWidths
+ Hledger.Data.Posting: defaultDecimalMarkColumn :: Int
+ Hledger.Data.Posting: defaultPostingLayout :: PostingLayout
+ Hledger.Data.Posting: feesplitPostingTagName :: TagName
+ Hledger.Data.Posting: imbalancePostingTagName :: TagName
+ Hledger.Data.Posting: instance GHC.Classes.Eq Hledger.Data.Posting.AmountCols
+ Hledger.Data.Posting: instance GHC.Classes.Eq Hledger.Data.Posting.PostingLayout
+ Hledger.Data.Posting: instance GHC.Classes.Eq Hledger.Data.Posting.PostingWidths
+ Hledger.Data.Posting: instance GHC.Show.Show Hledger.Data.Posting.AmountCols
+ Hledger.Data.Posting: instance GHC.Show.Show Hledger.Data.Posting.PostingLayout
+ Hledger.Data.Posting: instance GHC.Show.Show Hledger.Data.Posting.PostingWidths
+ Hledger.Data.Posting: isExplicitAmount :: Posting -> Bool
+ Hledger.Data.Posting: lotParentAssertionTagName :: TagName
+ Hledger.Data.Posting: lotsplitPostingTagName :: TagName
+ Hledger.Data.Posting: postingHasTag :: TagName -> Posting -> Bool
+ Hledger.Data.Posting: postingRemoveHiddenAndVisibleTag :: HiddenTag -> Posting -> Posting
+ Hledger.Data.Posting: postingsAddInferredEquityPostings :: Bool -> Text -> [Posting] -> [Posting]
+ Hledger.Data.Posting: postingsAsLinesWithLayout :: AmountFormat -> Bool -> PostingLayout -> [Posting] -> [Text]
+ Hledger.Data.Transaction: TBPDisplay :: TransactionBalancingPrecision
+ Hledger.Data.Transaction: TBPEntry :: TransactionBalancingPrecision
+ Hledger.Data.Transaction: showTransactionOneLine :: Transaction -> Text
+ Hledger.Data.Transaction: showTransactionWithLayout :: PostingLayout -> Transaction -> Text
+ Hledger.Data.Types: AVERAGE :: ReductionMethod
+ Hledger.Data.Types: AVERAGEALL :: ReductionMethod
+ Hledger.Data.Types: AssertDirective :: AssertQuantifier -> Maybe (Interval, DateSpan) -> Text -> Text -> [DateSpan] -> Text -> SourcePos -> AssertDirective
+ Hledger.Data.Types: AssertNone :: AssertQuantifier
+ Hledger.Data.Types: AssertSome :: AssertQuantifier
+ Hledger.Data.Types: FIFO :: ReductionMethod
+ Hledger.Data.Types: FIFOALL :: ReductionMethod
+ Hledger.Data.Types: FastPathStats :: Int -> Int -> Int -> Int -> Map Text Int -> FastPathStats
+ Hledger.Data.Types: HIFO :: ReductionMethod
+ Hledger.Data.Types: HIFOALL :: ReductionMethod
+ Hledger.Data.Types: Imbalance :: AccountType
+ Hledger.Data.Types: JIBlank :: JournalItem
+ Hledger.Data.Types: JIComment :: !Text -> JournalItem
+ Hledger.Data.Types: JICommentBlock :: !Text -> JournalItem
+ Hledger.Data.Types: JIDirective :: !Text -> JournalItem
+ Hledger.Data.Types: JIInclude :: !Text -> JournalItem
+ Hledger.Data.Types: JINonExportedDirective :: !Text -> JournalItem
+ Hledger.Data.Types: JITransaction :: !SourcePos -> JournalItem
+ Hledger.Data.Types: JournalFile :: FilePath -> Text -> Int -> JournalFile
+ Hledger.Data.Types: LIFO :: ReductionMethod
+ Hledger.Data.Types: LIFOALL :: ReductionMethod
+ Hledger.Data.Types: LotId :: !Day -> !Maybe Text -> LotId
+ Hledger.Data.Types: ParsePos :: SourcePos -> Int -> Text -> ParsePos
+ Hledger.Data.Types: RealPosting :: PostingRealness
+ Hledger.Data.Types: SPECID :: ReductionMethod
+ Hledger.Data.Types: [adPeriodText] :: AssertDirective -> Text
+ Hledger.Data.Types: [adPeriod] :: AssertDirective -> Maybe (Interval, DateSpan)
+ Hledger.Data.Types: [adQuantifier] :: AssertDirective -> AssertQuantifier
+ Hledger.Data.Types: [adQueryText] :: AssertDirective -> Text
+ Hledger.Data.Types: [adSkips] :: AssertDirective -> [DateSpan]
+ Hledger.Data.Types: [adSourcePos] :: AssertDirective -> SourcePos
+ Hledger.Data.Types: [adSourceText] :: AssertDirective -> Text
+ Hledger.Data.Types: [caliases] :: Commodity -> [(Amount, SourcePos)]
+ Hledger.Data.Types: [csourcepos] :: Commodity -> SourcePos
+ Hledger.Data.Types: [fpsDeclines] :: FastPathStats -> Map Text Int
+ Hledger.Data.Types: [fpsPricesFast] :: FastPathStats -> Int
+ Hledger.Data.Types: [fpsPricesGeneral] :: FastPathStats -> Int
+ Hledger.Data.Types: [fpsTxnsFast] :: FastPathStats -> Int
+ Hledger.Data.Types: [fpsTxnsGeneral] :: FastPathStats -> Int
+ Hledger.Data.Types: [jasserts] :: Journal -> [AssertDirective]
+ Hledger.Data.Types: [jauxfiles] :: Journal -> [(FilePath, [FilePath])]
+ Hledger.Data.Types: [jfdepth] :: JournalFile -> Int
+ Hledger.Data.Types: [jfpath] :: JournalFile -> FilePath
+ Hledger.Data.Types: [jftext] :: JournalFile -> Text
+ Hledger.Data.Types: [jitems] :: Journal -> [JournalItem]
+ Hledger.Data.Types: [jparseamountstyles] :: Journal -> Set AmountStyle
+ Hledger.Data.Types: [jparseapplyyears] :: Journal -> [Maybe Year]
+ Hledger.Data.Types: [jparsefastpathstats] :: Journal -> FastPathStats
+ Hledger.Data.Types: [jparseincludefilestack] :: Journal -> [(FilePath, FilePath)]
+ Hledger.Data.Types: [jparseoptaliases] :: Journal -> [AccountAlias]
+ Hledger.Data.Types: [jparsepos] :: Journal -> Maybe ParsePos
+ Hledger.Data.Types: [jparsetexts] :: Journal -> Set Text
+ Hledger.Data.Types: [lotDate] :: LotId -> !Day
+ Hledger.Data.Types: [lotLabel] :: LotId -> !Maybe Text
+ Hledger.Data.Types: [ppInput] :: ParsePos -> Text
+ Hledger.Data.Types: [ppOffset] :: ParsePos -> Int
+ Hledger.Data.Types: [ppSourcePos] :: ParsePos -> SourcePos
+ Hledger.Data.Types: [preal] :: Posting -> PostingRealness
+ Hledger.Data.Types: data AssertDirective
+ Hledger.Data.Types: data AssertQuantifier
+ Hledger.Data.Types: data FastPathStats
+ Hledger.Data.Types: data JournalFile
+ Hledger.Data.Types: data JournalItem
+ Hledger.Data.Types: data LotId
+ Hledger.Data.Types: data ParsePos
+ Hledger.Data.Types: data PostingRealness
+ Hledger.Data.Types: data ReductionMethod
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.AssertDirective
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.AssertQuantifier
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.JournalFile
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.JournalItem
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.LotId
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.ParsePos
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.PostingRealness
+ Hledger.Data.Types: instance Control.DeepSeq.NFData Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: instance GHC.Base.Monoid Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance GHC.Base.Semigroup Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.AssertDirective
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.AssertQuantifier
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.JournalFile
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.JournalItem
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.LotId
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.ParsePos
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.PostingRealness
+ Hledger.Data.Types: instance GHC.Classes.Eq Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: instance GHC.Classes.Ord Hledger.Data.Types.LotId
+ Hledger.Data.Types: instance GHC.Classes.Ord Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: instance GHC.Enum.Bounded Hledger.Data.Types.AccountType
+ Hledger.Data.Types: instance GHC.Enum.Enum Hledger.Data.Types.AccountType
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.AssertDirective
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.AssertQuantifier
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.JournalFile
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.JournalItem
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.LotId
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.ParsePos
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.PostingRealness
+ Hledger.Data.Types: instance GHC.Generics.Generic Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: instance GHC.Read.Read Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.AssertQuantifier
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.FastPathStats
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.JournalFile
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.JournalItem
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.LotId
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.ParsePos
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.PostingRealness
+ Hledger.Data.Types: instance GHC.Show.Show Hledger.Data.Types.ReductionMethod
+ Hledger.Data.Types: mixedAmountKey :: Amount -> MixedAmountKey
+ Hledger.Data.Valuation: ToTransactedCost :: ConversionOp
+ Hledger.Data.Valuation: amountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> Amount -> Amount
+ Hledger.Data.Valuation: journalAliasPriceDirectives :: Journal -> [PriceDirective]
+ Hledger.Query: Balance :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query
+ Hledger.Query: Change :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query
+ Hledger.Query: Cur :: Regexp -> Query
+ Hledger.Query: Find :: Regexp -> Maybe DateSpan -> Query
+ Hledger.Query: matchesCommodityExtra :: (CommoditySymbol -> [Tag]) -> Query -> CommoditySymbol -> Bool
+ Hledger.Query: matchesPayee :: Query -> Payee -> Bool
+ Hledger.Query: matchesRowAmounts :: Query -> MixedAmount -> MixedAmount -> Bool
+ Hledger.Query: parseAmountQueryArg :: String -> Text -> Either String (OrdPlus, Quantity, Maybe CommoditySymbol)
+ Hledger.Query: postingQueryForAccount :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe AccountName -> Query -> Query
+ Hledger.Query: queryHasBalance :: Query -> Bool
+ Hledger.Query: queryHasChange :: Query -> Bool
+ Hledger.Query: queryIsAmtOrCur :: Query -> Bool
+ Hledger.Query: queryIsBalance :: Query -> Bool
+ Hledger.Query: queryIsChange :: Query -> Bool
+ Hledger.Query: queryIsCur :: Query -> Bool
+ Hledger.Query: queryIsFind :: Query -> Bool
+ Hledger.Query: queryIsFlatDepth :: Query -> Bool
+ Hledger.Query: queryIsRowTerm :: Query -> Bool
+ Hledger.Query: querySplitRowTerms :: Query -> Either String (Query, Query)
+ Hledger.Query: transformQuery :: (Query -> Query) -> Query -> Query
+ Hledger.Read: parseAssertDirective :: Day -> String -> Text -> Either String AssertDirective
+ Hledger.Read.Common: AmbiguousNumber :: DigitGrp -> Char -> DigitGrp -> AmbiguousNumber
+ Hledger.Read.Common: DigitGrp :: !Word -> !Integer -> DigitGrp
+ Hledger.Read.Common: MultiplierAmount :: AmountParseKind
+ Hledger.Read.Common: NoSeparators :: DigitGrp -> Maybe (Char, DigitGrp) -> RawNumber
+ Hledger.Read.Common: OrdinaryAmount :: AmountParseKind
+ Hledger.Read.Common: StyleAmount :: AmountParseKind
+ Hledger.Read.Common: WithSeparators :: Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber
+ Hledger.Read.Common: [_dryrun] :: InputOpts -> Bool
+ Hledger.Read.Common: [_fileoverrides] :: InputOpts -> Map FilePath Text
+ Hledger.Read.Common: [_forecastOnlyForDisplay] :: InputOpts -> Bool
+ Hledger.Read.Common: [_importing] :: InputOpts -> Bool
+ Hledger.Read.Common: [_journaldir] :: InputOpts -> Maybe FilePath
+ Hledger.Read.Common: [_scanfiles] :: InputOpts -> Bool
+ Hledger.Read.Common: [digitGroupLength] :: DigitGrp -> !Word
+ Hledger.Read.Common: [digitGroupNumber] :: DigitGrp -> !Integer
+ Hledger.Read.Common: [ignore_lots_] :: InputOpts -> Bool
+ Hledger.Read.Common: accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName
+ Hledger.Read.Common: aliasedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName
+ Hledger.Read.Common: applyParentAndOptionAliases :: forall (m :: Type -> Type). AccountName -> JournalParser m AccountName
+ Hledger.Read.Common: data AmbiguousNumber
+ Hledger.Read.Common: data AmountParseKind
+ Hledger.Read.Common: data DigitGrp
+ Hledger.Read.Common: data RawNumber
+ Hledger.Read.Common: dryrun :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.Common: fileoverrides :: HasInputOpts c => Lens' c (Map FilePath Text)
+ Hledger.Read.Common: forecastOnlyForDisplay :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.Common: getSourcePos' :: forall (m :: Type -> Type). JournalParser m SourcePos
+ Hledger.Read.Common: ignore_lots :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.Common: importing :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.Common: includeFileParser :: forall (m :: Type -> Type). MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal
+ Hledger.Read.Common: instance GHC.Classes.Eq Hledger.Read.Common.AmountParseKind
+ Hledger.Read.Common: instance GHC.Show.Show Hledger.Read.Common.AmountParseKind
+ Hledger.Read.Common: interpretRawNumber :: Maybe Char -> Maybe AmountStyle -> Either AmbiguousNumber RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
+ Hledger.Read.Common: isDigitSeparatorChar :: Char -> Bool
+ Hledger.Read.Common: journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle
+ Hledger.Read.Common: journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()
+ Hledger.Read.Common: journalDecimalMarkStyle :: Journal -> Maybe AmountStyle
+ Hledger.Read.Common: journaldir :: HasInputOpts c => Lens' c (Maybe FilePath)
+ Hledger.Read.Common: parentaccountnamep :: forall (m :: Type -> Type). TextParser m AccountName
+ Hledger.Read.Common: parseamountWithStyles :: Map CommoditySymbol AmountStyle -> String -> Either HledgerParseErrors Amount
+ Hledger.Read.Common: postingamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
+ Hledger.Read.Common: readerReadsOwnInput :: forall (m :: Type -> Type). Reader m -> Bool
+ Hledger.Read.Common: scanfiles :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.Common: shareAmountStyle :: forall (m :: Type -> Type). AmountStyle -> JournalParser m AmountStyle
+ Hledger.Read.Common: shareText :: forall (m :: Type -> Type). Text -> JournalParser m Text
+ Hledger.Read.Common: simpleamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
+ Hledger.Read.Common: timeofdayp :: forall (m :: Type -> Type). TextParser m TimeOfDay
+ Hledger.Read.InputOptions: [_dryrun] :: InputOpts -> Bool
+ Hledger.Read.InputOptions: [_fileoverrides] :: InputOpts -> Map FilePath Text
+ Hledger.Read.InputOptions: [_forecastOnlyForDisplay] :: InputOpts -> Bool
+ Hledger.Read.InputOptions: [_importing] :: InputOpts -> Bool
+ Hledger.Read.InputOptions: [_journaldir] :: InputOpts -> Maybe FilePath
+ Hledger.Read.InputOptions: [_scanfiles] :: InputOpts -> Bool
+ Hledger.Read.InputOptions: [ignore_lots_] :: InputOpts -> Bool
+ Hledger.Read.InputOptions: dryrun :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.InputOptions: fileOverride :: InputOpts -> FilePath -> IO (Maybe Text)
+ Hledger.Read.InputOptions: fileoverrides :: HasInputOpts c => Lens' c (Map FilePath Text)
+ Hledger.Read.InputOptions: forecastOnlyForDisplay :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.InputOptions: ignore_lots :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.InputOptions: importing :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.InputOptions: inputOptsSetJournalDir :: Journal -> InputOpts -> InputOpts
+ Hledger.Read.InputOptions: journaldir :: HasInputOpts c => Lens' c (Maybe FilePath)
+ Hledger.Read.InputOptions: scanfiles :: HasInputOpts c => Lens' c Bool
+ Hledger.Read.JournalReader: parseAssertDirective :: Day -> String -> Text -> Either String AssertDirective
+ Hledger.Read.LatestDates: LatestDatesForFile :: FilePath -> LatestDates -> LatestDatesForFile
+ Hledger.Read.LatestDates: data LatestDatesForFile
+ Hledger.Read.LatestDates: instance GHC.Show.Show Hledger.Read.LatestDates.LatestDatesForFile
+ Hledger.Read.LatestDates: journalFilterSinceLatestDates :: LatestDates -> Journal -> (Journal, LatestDates)
+ Hledger.Read.LatestDates: latestDates :: [Day] -> LatestDates
+ Hledger.Read.LatestDates: latestDatesFileFor :: FilePath -> FilePath
+ Hledger.Read.LatestDates: previousLatestDates :: FilePath -> IO LatestDates
+ Hledger.Read.LatestDates: saveLatestDates :: LatestDates -> FilePath -> IO ()
+ Hledger.Read.LatestDates: saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()
+ Hledger.Read.LatestDates: type LatestDates = [Day]
+ Hledger.Read.RulesReader: instance GHC.Classes.Eq Hledger.Read.RulesReader.FieldAssignment
+ Hledger.Read.RulesReader: instance GHC.Show.Show Hledger.Read.RulesReader.FieldAssignment
+ Hledger.Read.RulesReader: instance GHC.Show.Show Hledger.Read.RulesReader.TemplateExpr
+ Hledger.Read.RulesReader: readParsedJournalFromCsv :: FilePath -> CsvRules -> (FilePath, [FilePath]) -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO (ParsedJournal, String -> String)
+ Hledger.Reports.AccountTransactionsReport: accountTransactionsReportWithStart :: ReportSpec -> Journal -> Query -> (MixedAmount, AccountTransactionsReport)
+ Hledger.Reports.AccountTransactionsReport: filterAccountTransactionsReportByCommodity :: CommoditySymbol -> AccountTransactionsReport -> AccountTransactionsReport
+ Hledger.Reports.AccountTransactionsReport: transactionRegisterDateExtra :: (AccountName -> Maybe AccountType) -> WhichDate -> Query -> Query -> Transaction -> Day
+ Hledger.Reports.EntriesReport: entriesReportUnsorted :: ReportSpec -> Journal -> EntriesReport
+ Hledger.Reports.MultiBalanceReport: accountRowAmounts :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> Map AccountName (MixedAmount, MixedAmount)
+ Hledger.Reports.MultiBalanceReport: balanceReportStyles :: ReportOpts -> Journal -> Map CommoditySymbol AmountStyle
+ Hledger.Reports.MultiBalanceReport: instance GHC.Base.Semigroup Hledger.Reports.MultiBalanceReport.RowAmounts
+ Hledger.Reports.MultiBalanceReport: rowTotal :: ReportOpts -> c -> c -> Map Day c -> c
+ Hledger.Reports.PostingsReport: postingsReportStartBalances :: ReportSpec -> Journal -> Map AccountName MixedAmount
+ Hledger.Reports.PostingsReport: registerRunningCalculationFn :: ReportOpts -> Int -> MixedAmount -> MixedAmount -> MixedAmount
+ Hledger.Reports.ReportOptions: CalcTransactionsCount :: BalanceCalculation
+ Hledger.Reports.ReportOptions: LayoutBareWide :: Layout
+ Hledger.Reports.ReportOptions: PTCompact :: PeriodTitles
+ Hledger.Reports.ReportOptions: PTDates :: PeriodTitles
+ Hledger.Reports.ReportOptions: [_rsRowQuery] :: ReportSpec -> Query
+ Hledger.Reports.ReportOptions: [fold_depth_] :: ReportOpts -> Maybe Int
+ Hledger.Reports.ReportOptions: [full_names_] :: ReportOpts -> Bool
+ Hledger.Reports.ReportOptions: [period_titles_] :: ReportOpts -> PeriodTitles
+ Hledger.Reports.ReportOptions: [subreport_titles_] :: ReportOpts -> Maybe Text
+ Hledger.Reports.ReportOptions: [title_] :: ReportOpts -> Maybe Text
+ Hledger.Reports.ReportOptions: [translations_] :: ReportOpts -> Translations
+ Hledger.Reports.ReportOptions: balanceCalcIsCount :: BalanceCalculation -> Bool
+ Hledger.Reports.ReportOptions: data PeriodTitles
+ Hledger.Reports.ReportOptions: effectiveTitle :: ReportOpts -> Text -> Text
+ Hledger.Reports.ReportOptions: fold_depth :: HasReportOptsNoUpdate c => Lens' c (Maybe Int)
+ Hledger.Reports.ReportOptions: full_names :: HasReportOptsNoUpdate c => Lens' c Bool
+ Hledger.Reports.ReportOptions: instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.PeriodTitles
+ Hledger.Reports.ReportOptions: instance GHC.Classes.Eq Hledger.Reports.ReportOptions.PeriodTitles
+ Hledger.Reports.ReportOptions: instance GHC.Show.Show Hledger.Reports.ReportOptions.PeriodTitles
+ Hledger.Reports.ReportOptions: intervalFromQueryOpts :: [QueryOpt] -> Maybe Interval
+ Hledger.Reports.ReportOptions: period_titles :: HasReportOptsNoUpdate c => Lens' c PeriodTitles
+ Hledger.Reports.ReportOptions: reportSpanBothDatesLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])
+ Hledger.Reports.ReportOptions: reportSpanLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])
+ Hledger.Reports.ReportOptions: rsRowQuery :: HasReportSpec c => Lens' c Query
+ Hledger.Reports.ReportOptions: subreport_titles :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
+ Hledger.Reports.ReportOptions: title__ :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
+ Hledger.Reports.ReportOptions: translations :: HasReportOptsNoUpdate c => Lens' c Translations
+ Hledger.Utils.Debug: dbgTime :: NFData a => Int -> String -> a -> a
+ Hledger.Utils.Debug: dbgTimeIO :: (MonadIO m, NFData a) => Int -> String -> a -> m a
+ Hledger.Utils.Debug: dbgTimeResetIO :: MonadIO m => m ()
+ Hledger.Utils.I18n: PluralForms :: Int -> (Int -> Int) -> PluralForms
+ Hledger.Utils.I18n: Translations :: Text -> Map Text Text -> Map Text [Text] -> Maybe PluralForms -> Translations
+ Hledger.Utils.I18n: [pfCount] :: PluralForms -> Int
+ Hledger.Utils.I18n: [pfRule] :: PluralForms -> Int -> Int
+ Hledger.Utils.I18n: [trLang] :: Translations -> Text
+ Hledger.Utils.I18n: [trMessages] :: Translations -> Map Text Text
+ Hledger.Utils.I18n: [trPluralForms] :: Translations -> Maybe PluralForms
+ Hledger.Utils.I18n: [trPlurals] :: Translations -> Map Text [Text]
+ Hledger.Utils.I18n: availableLanguages :: IO [Text]
+ Hledger.Utils.I18n: builtinLanguages :: [Text]
+ Hledger.Utils.I18n: builtinTranslations :: Map Text Translations
+ Hledger.Utils.I18n: data PluralForms
+ Hledger.Utils.I18n: data Translations
+ Hledger.Utils.I18n: i18n :: Text -> Text
+ Hledger.Utils.I18n: i18nc :: Text -> Text -> Text
+ Hledger.Utils.I18n: instance GHC.Show.Show Hledger.Utils.I18n.Translations
+ Hledger.Utils.I18n: isValidLangTag :: Text -> Bool
+ Hledger.Utils.I18n: langPrefsFromEnv :: [(String, String)] -> [Text]
+ Hledger.Utils.I18n: langTagCandidates :: Text -> [Text]
+ Hledger.Utils.I18n: loadAllTranslations :: IO (Map Text Translations)
+ Hledger.Utils.I18n: loadTranslations :: Text -> IO Translations
+ Hledger.Utils.I18n: mergeTranslations :: Translations -> Translations -> Translations
+ Hledger.Utils.I18n: noTranslations :: Translations
+ Hledger.Utils.I18n: normalizeLangTag :: Text -> Maybe Text
+ Hledger.Utils.I18n: parsePluralForms :: Text -> Maybe PluralForms
+ Hledger.Utils.I18n: parsePo :: String -> Text -> Text -> Either String Translations
+ Hledger.Utils.I18n: placeholders :: Text -> Set Text
+ Hledger.Utils.I18n: resolveLang :: [Text] -> [Text] -> Maybe Text
+ Hledger.Utils.I18n: shortLangTag :: Text -> Text
+ Hledger.Utils.I18n: startingCatalog :: Text -> Either String (Text, Bool, ByteString)
+ Hledger.Utils.I18n: substitutePlaceholders :: [(Text, Text)] -> Text -> Text
+ Hledger.Utils.I18n: tests_I18n :: TestTree
+ Hledger.Utils.I18n: tr :: Translations -> Text -> Text
+ Hledger.Utils.I18n: trTimeLocale :: Translations -> TimeLocale
+ Hledger.Utils.I18n: translationsForLangOption :: Maybe String -> IO Translations
+ Hledger.Utils.I18n: translationsOverrideDir :: IO FilePath
+ Hledger.Utils.I18n: trc :: Translations -> Text -> Text -> Text
+ Hledger.Utils.I18n: trf :: Translations -> Text -> [(Text, Text)] -> Text
+ Hledger.Utils.I18n: trn :: Translations -> Int -> Text -> Text -> Text
+ Hledger.Utils.I18n: writeStartingCatalog :: Text -> IO (Either String (FilePath, Text, Bool))
+ Hledger.Utils.IO: accent :: String -> String
+ Hledger.Utils.IO: dataDirName :: FilePath
+ Hledger.Utils.IO: embedFileRelativeBytes :: FilePath -> Q Exp
+ Hledger.Utils.IO: ensureFilesystemCanAppend :: FilePath -> IO Bool
+ Hledger.Utils.IO: gradientStr :: (String -> String) -> Int -> Int -> Int -> Int -> String -> String
+ Hledger.Utils.IO: insideEmacsNotVterm :: IO Bool
+ Hledger.Utils.IO: rulesDirName :: FilePath
+ Hledger.Utils.IO: setWarningHandler :: (String -> IO ()) -> IO ()
+ Hledger.Utils.IO: supportsTrueColor :: IO Bool
+ Hledger.Utils.IO: supportsTrueColorUnsafe :: Bool
+ Hledger.Utils.IO: titleAndVersionLine :: Int -> String -> String -> String
+ Hledger.Utils.IO: titleLine :: String -> String
+ Hledger.Utils.IO: withFileOrStdout :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
+ Hledger.Utils.Parse: finalMessageFailure :: MonadError (FinalParseError' e) m => String -> m a
+ Hledger.Utils.Parse: finalizeCustomErrorBundle :: HledgerParseErrors -> HledgerParseErrors
+ Hledger.Utils.Parse: manyWhile :: MonadPlus m => m Bool -> m a -> m [a]
+ Hledger.Utils.Parse: peekAfterSpaces :: forall (m :: Type -> Type). TextParser m (Bool, Maybe Char)
+ Hledger.Utils.Parse: peekChar :: forall (m :: Type -> Type). TextParser m (Maybe Char)
+ Hledger.Utils.Parse: peekChars2 :: forall (m :: Type -> Type). TextParser m (Maybe Char, Maybe Char)
+ Hledger.Utils.Parse: sourcePosFileLine :: SourcePos -> String
+ Hledger.Utils.Regex: regexEscape :: Text -> Text
+ Hledger.Utils.String: isDoubleQuoted :: String -> Bool
+ Hledger.Utils.String: isSingleQuoted :: String -> Bool
+ Hledger.Utils.String: shellQuoteIfNeeded :: String -> String
+ Hledger.Utils.String: stripQuotes :: String -> String
+ Hledger.Utils.String: wordsEither :: String -> Either String [String]
+ Hledger.Utils.String: wordsmay :: String -> Maybe [String]
+ Hledger.Utils.Text: quoteForQuery :: Text -> Text
+ Hledger.Utils.Text: textStripQuotes :: Text -> Text
+ Hledger.Write.Beancount: beancountDirectives :: Journal -> [Transaction] -> Text
+ Hledger.Write.Beancount: beancountItemRenderer :: ItemRenderer
+ Hledger.Write.Beancount: beancountRenameAccounts :: Journal -> [Transaction] -> (Journal, [Transaction])
+ Hledger.Write.Beancount: beancountTransactions :: [Transaction] -> [Transaction]
+ Hledger.Write.Beancount: showPriceDirectiveBeancount :: PriceDirective -> Text
+ Hledger.Write.Chart: ByName :: Colouring
+ Hledger.Write.Chart: ByType :: Colouring
+ Hledger.Write.Chart: Chart :: Text -> XAxis -> [Panel] -> [Text] -> Chart
+ Hledger.Write.Chart: ChartLabel :: Text -> Text -> Int -> Maybe AccountType -> Bool -> [Text] -> ChartLabel
+ Hledger.Write.Chart: Diverging :: BarLayout
+ Hledger.Write.Chart: Grouped :: BarLayout
+ Hledger.Write.Chart: IndexColour :: Int -> Colour
+ Hledger.Write.Chart: LoneColour :: Colour
+ Hledger.Write.Chart: MarkBar :: Mark
+ Hledger.Write.Chart: MarkLine :: Mark
+ Hledger.Write.Chart: MarkMarker :: Mark
+ Hledger.Write.Chart: MarkNone :: Mark
+ Hledger.Write.Chart: NeutralColour :: Colour
+ Hledger.Write.Chart: OtherColour :: Maybe AccountType -> Colour
+ Hledger.Write.Chart: Panel :: Amount -> [Series] -> [Text] -> Maybe Quantity -> BarLayout -> Bool -> [Summary] -> [Maybe Text] -> Panel
+ Hledger.Write.Chart: Series :: ChartLabel -> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
+ Hledger.Write.Chart: SeriesItem :: SeriesRole
+ Hledger.Write.Chart: SeriesOther :: SeriesRole
+ Hledger.Write.Chart: SeriesProvisional :: SeriesRole
+ Hledger.Write.Chart: SeriesShortfall :: SeriesRole
+ Hledger.Write.Chart: SeriesTotal :: SeriesRole
+ Hledger.Write.Chart: Single :: Colouring
+ Hledger.Write.Chart: Summary :: SummaryKind -> Text -> Amount -> Summary
+ Hledger.Write.Chart: SummaryAverage :: SummaryKind
+ Hledger.Write.Chart: SummaryTotal :: SummaryKind
+ Hledger.Write.Chart: TotalColour :: Colour
+ Hledger.Write.Chart: TypeColour :: AccountType -> Int -> Colour
+ Hledger.Write.Chart: XCategories :: [ChartLabel] -> XAxis
+ Hledger.Write.Chart: XDates :: [Day] -> XAxis
+ Hledger.Write.Chart: XPeriods :: [(DateSpan, Text)] -> XAxis
+ Hledger.Write.Chart: [chNotes] :: Chart -> [Text]
+ Hledger.Write.Chart: [chPanels] :: Chart -> [Panel]
+ Hledger.Write.Chart: [chTitle] :: Chart -> Text
+ Hledger.Write.Chart: [chXAxis] :: Chart -> XAxis
+ Hledger.Write.Chart: [lbAccount] :: ChartLabel -> Bool
+ Hledger.Write.Chart: [lbFull] :: ChartLabel -> Text
+ Hledger.Write.Chart: [lbIndent] :: ChartLabel -> Int
+ Hledger.Write.Chart: [lbShort] :: ChartLabel -> Text
+ Hledger.Write.Chart: [lbTipLines] :: ChartLabel -> [Text]
+ Hledger.Write.Chart: [lbType] :: ChartLabel -> Maybe AccountType
+ Hledger.Write.Chart: [pnCounts] :: Panel -> Bool
+ Hledger.Write.Chart: [pnGroupNames] :: Panel -> [Text]
+ Hledger.Write.Chart: [pnLayout] :: Panel -> BarLayout
+ Hledger.Write.Chart: [pnScale] :: Panel -> Maybe Quantity
+ Hledger.Write.Chart: [pnSeries] :: Panel -> [Series]
+ Hledger.Write.Chart: [pnSummary] :: Panel -> [Summary]
+ Hledger.Write.Chart: [pnUnit] :: Panel -> Amount
+ Hledger.Write.Chart: [pnValueLabels] :: Panel -> [Maybe Text]
+ Hledger.Write.Chart: [seGroup] :: Series -> Int
+ Hledger.Write.Chart: [seLabel] :: Series -> ChartLabel
+ Hledger.Write.Chart: [seMark] :: Series -> Mark
+ Hledger.Write.Chart: [seRole] :: Series -> SeriesRole
+ Hledger.Write.Chart: [seSign] :: Series -> Int
+ Hledger.Write.Chart: [seValues] :: Series -> [Maybe Quantity]
+ Hledger.Write.Chart: [suKind] :: Summary -> SummaryKind
+ Hledger.Write.Chart: [suLabel] :: Summary -> Text
+ Hledger.Write.Chart: [suValue] :: Summary -> Amount
+ Hledger.Write.Chart: categoryTints :: [ChartLabel] -> [Maybe Quantity] -> [Int]
+ Hledger.Write.Chart: chartAsCsv :: Chart -> CSV
+ Hledger.Write.Chart: chartColouring :: Chart -> Colouring
+ Hledger.Write.Chart: chartWithoutTotalMarks :: Chart -> Chart
+ Hledger.Write.Chart: data BarLayout
+ Hledger.Write.Chart: data Chart
+ Hledger.Write.Chart: data ChartLabel
+ Hledger.Write.Chart: data Colour
+ Hledger.Write.Chart: data Colouring
+ Hledger.Write.Chart: data Mark
+ Hledger.Write.Chart: data Panel
+ Hledger.Write.Chart: data Series
+ Hledger.Write.Chart: data SeriesRole
+ Hledger.Write.Chart: data Summary
+ Hledger.Write.Chart: data SummaryKind
+ Hledger.Write.Chart: data XAxis
+ Hledger.Write.Chart: hatchedSeries :: Series -> Bool
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.BarLayout
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Chart
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.ChartLabel
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Mark
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Panel
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Series
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.SeriesRole
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Summary
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.SummaryKind
+ Hledger.Write.Chart: instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.XAxis
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.BarLayout
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Chart
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.ChartLabel
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Colour
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Colouring
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Mark
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Panel
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Series
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.SeriesRole
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.Summary
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.SummaryKind
+ Hledger.Write.Chart: instance GHC.Classes.Eq Hledger.Write.Chart.XAxis
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.BarLayout
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.Chart
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.ChartLabel
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.Mark
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.Panel
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.Series
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.SeriesRole
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.Summary
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.SummaryKind
+ Hledger.Write.Chart: instance GHC.Generics.Generic Hledger.Write.Chart.XAxis
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.BarLayout
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Chart
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.ChartLabel
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Colour
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Colouring
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Mark
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Panel
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Series
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.SeriesRole
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.Summary
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.SummaryKind
+ Hledger.Write.Chart: instance GHC.Show.Show Hledger.Write.Chart.XAxis
+ Hledger.Write.Chart: isContra :: Series -> Quantity -> Bool
+ Hledger.Write.Chart: isHatched :: Series -> Quantity -> Bool
+ Hledger.Write.Chart: legendListsSeries :: Bool -> [Series] -> Bool
+ Hledger.Write.Chart: mainAccountType :: AccountType -> AccountType
+ Hledger.Write.Chart: maxTints :: Int
+ Hledger.Write.Chart: scaleSpans :: (Ord a, Fractional a) => a -> a -> a -> (a, a)
+ Hledger.Write.Chart: seriesColours :: Colouring -> [Series] -> [Colour]
+ Hledger.Write.Chart: seriesSize :: Series -> Quantity
+ Hledger.Write.Chart: seriesValues :: Series -> SeriesValues
+ Hledger.Write.Chart: setChartLayout :: Maybe BarLayout -> Chart -> Chart
+ Hledger.Write.Chart: setChartScales :: [Amount] -> Chart -> Chart
+ Hledger.Write.Chart: stableSlots :: Ord a => Int -> [(Text, a)] -> [Int]
+ Hledger.Write.Chart: stableSlotsFavouringFirst :: Ord a => Double -> Int -> [(Text, a)] -> [Int]
+ Hledger.Write.Chart: tests_Hledger_Write_Chart :: TestTree
+ Hledger.Write.Chart: type SeriesValues = Array Int Maybe Quantity
+ Hledger.Write.Chart: valueAt :: SeriesValues -> Int -> Maybe Quantity
+ Hledger.Write.Chart.Palette: colourHex :: Bool -> Colour -> Text
+ Hledger.Write.Chart.Palette: tests_Hledger_Write_Chart_Palette :: TestTree
+ Hledger.Write.Chart.Palette: tint :: Double -> Text -> Text
+ Hledger.Write.Chart.Svg: SvgOptions :: Bool -> Bool -> Double -> Double -> (Int -> Maybe Text) -> Bool -> Maybe Day -> Text -> SvgOptions
+ Hledger.Write.Chart.Svg: [svgDark] :: SvgOptions -> Bool
+ Hledger.Write.Chart.Svg: [svgDateScale] :: SvgOptions -> Bool
+ Hledger.Write.Chart.Svg: [svgIds] :: SvgOptions -> Text
+ Hledger.Write.Chart.Svg: [svgPlotHeight] :: SvgOptions -> Double
+ Hledger.Write.Chart.Svg: [svgPointLink] :: SvgOptions -> Int -> Maybe Text
+ Hledger.Write.Chart.Svg: [svgStyles] :: SvgOptions -> Bool
+ Hledger.Write.Chart.Svg: [svgToday] :: SvgOptions -> Maybe Day
+ Hledger.Write.Chart.Svg: [svgWidth] :: SvgOptions -> Double
+ Hledger.Write.Chart.Svg: chartAsSvg :: Chart -> Text
+ Hledger.Write.Chart.Svg: chartAsSvgWith :: Bool -> Chart -> Text
+ Hledger.Write.Chart.Svg: chartPanelsSvgMarkupWith :: SvgOptions -> Chart -> [Svg]
+ Hledger.Write.Chart.Svg: chartStylesheet :: Bool -> Text
+ Hledger.Write.Chart.Svg: chartSvgMarkup :: Bool -> Chart -> Svg
+ Hledger.Write.Chart.Svg: chartSvgMarkupWith :: SvgOptions -> Chart -> Svg
+ Hledger.Write.Chart.Svg: data SvgOptions
+ Hledger.Write.Chart.Svg: defaultSvgOptions :: SvgOptions
+ Hledger.Write.Chart.Svg: tests_Hledger_Write_Chart_Svg :: TestTree
+ Hledger.Write.Chart.Text: BasicColour :: ColourMode
+ Hledger.Write.Chart.Text: NoColour :: ColourMode
+ Hledger.Write.Chart.Text: RgbColour :: Bool -> ColourMode
+ Hledger.Write.Chart.Text: StyleLone :: Style
+ Hledger.Write.Chart.Text: StyleNegative :: Style
+ Hledger.Write.Chart.Text: StyleOther :: Maybe AccountType -> Style
+ Hledger.Write.Chart.Text: StylePlain :: Style
+ Hledger.Write.Chart.Text: StyleSeries :: Int -> Style
+ Hledger.Write.Chart.Text: StyleType :: AccountType -> Int -> Style
+ Hledger.Write.Chart.Text: TextChartOpts :: Int -> Bool -> TextChartOpts
+ Hledger.Write.Chart.Text: [tcUnicode] :: TextChartOpts -> Bool
+ Hledger.Write.Chart.Text: [tcWidth] :: TextChartOpts -> Int
+ Hledger.Write.Chart.Text: chartAsStyledLines :: TextChartOpts -> Chart -> [StyledLine]
+ Hledger.Write.Chart.Text: data ColourMode
+ Hledger.Write.Chart.Text: data Style
+ Hledger.Write.Chart.Text: data TextChartOpts
+ Hledger.Write.Chart.Text: instance GHC.Classes.Eq Hledger.Write.Chart.Text.ColourMode
+ Hledger.Write.Chart.Text: instance GHC.Classes.Eq Hledger.Write.Chart.Text.Style
+ Hledger.Write.Chart.Text: instance GHC.Show.Show Hledger.Write.Chart.Text.ColourMode
+ Hledger.Write.Chart.Text: instance GHC.Show.Show Hledger.Write.Chart.Text.Style
+ Hledger.Write.Chart.Text: styledLinesAsText :: ColourMode -> [StyledLine] -> Text
+ Hledger.Write.Chart.Text: tests_Hledger_Write_Chart_Text :: TestTree
+ Hledger.Write.Chart.Text: type StyledLine = [(Style, Text)]
+ Hledger.Write.Html: borderClass :: Lines border => border -> Maybe Text
+ Hledger.Write.Html: borderClasses :: Lines border => Cell border text -> [Text]
+ Hledger.Write.Html: class Lines border => Lines border
+ Hledger.Write.Html: formatCell :: Lines border => Cell border Html -> Html
+ Hledger.Write.Html: formatTitle :: Text -> Html
+ Hledger.Write.Html: instance Hledger.Write.Html.Lines ()
+ Hledger.Write.Html: instance Hledger.Write.Html.Lines Hledger.Write.Spreadsheet.NumLines
+ Hledger.Write.Html: nl :: Html
+ Hledger.Write.Html: titledTableHtml :: Lines border => Text -> [[Cell border Html]] -> Html
+ Hledger.Write.Html.Attribute: borderStyle :: [(Text, Text)]
+ Hledger.Write.Journal: ItemRenderer :: (Transaction -> Text) -> (Text -> Maybe Text) -> (Text -> Text) -> (Text -> Text) -> ItemRenderer
+ Hledger.Write.Journal: [irCommentBlock] :: ItemRenderer -> Text -> Text
+ Hledger.Write.Journal: [irComment] :: ItemRenderer -> Text -> Text
+ Hledger.Write.Journal: [irDirective] :: ItemRenderer -> Text -> Maybe Text
+ Hledger.Write.Journal: [irTransaction] :: ItemRenderer -> Transaction -> Text
+ Hledger.Write.Journal: data ItemRenderer
+ Hledger.Write.Journal: journalItemRenderer :: (Transaction -> Text) -> ItemRenderer
+ Hledger.Write.Journal: journalItemsAsText :: ItemRenderer -> [JournalItem] -> [Transaction] -> Text
+ Hledger.Write.Ledger: ledgerItemRenderer :: ItemRenderer
+ Hledger.Write.Ledger: showTransactionLedger :: Transaction -> Text
+ Hledger.Write.Ods: instance GHC.Classes.Eq Hledger.Write.Ods.CommodityStyle
+ Hledger.Write.Ods: instance GHC.Classes.Ord Hledger.Write.Ods.CommodityStyle
+ Hledger.Write.Ods: instance GHC.Show.Show Hledger.Write.Ods.CommodityStyle
+ Hledger.Write.Spreadsheet: [cellParts] :: Cell border text -> [text]
+ Hledger.Write.Spreadsheet: [cellTitle] :: Cell border text -> Text
+ Hledger.Write.Spreadsheet: addRowSpanHeaderNE :: Cell border text -> [[Cell border text]] -> [NonEmpty (Cell border text)]
- Hledger.Data: BalancedVirtualPosting :: PostingType
+ Hledger.Data: BalancedVirtualPosting :: PostingRealness
- Hledger.Data: Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> Commodity
+ Hledger.Data: Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> [(Amount, SourcePos)] -> SourcePos -> Commodity
- Hledger.Data: CostBasis :: !Maybe Amount -> !Maybe Day -> !Maybe Text -> CostBasis
+ Hledger.Data: CostBasis :: !Maybe Day -> !Maybe Text -> !Maybe Amount -> CostBasis
- Hledger.Data: Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> POSIXTime -> Journal
+ Hledger.Data: Journal :: Maybe Year -> [Maybe Year] -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> Maybe ParsePos -> Set AmountStyle -> Set Text -> FastPathStats -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [AssertDirective] -> [Transaction] -> [JournalItem] -> [JournalFile] -> [(FilePath, [FilePath])] -> POSIXTime -> Journal
- Hledger.Data: Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting
+ Hledger.Data: Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingRealness -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting
- Hledger.Data: VirtualPosting :: PostingType
+ Hledger.Data: VirtualPosting :: PostingRealness
- Hledger.Data: [jfiles] :: Journal -> [(FilePath, Text)]
+ Hledger.Data: [jfiles] :: Journal -> [JournalFile]
- Hledger.Data: pattern MixedAmountKeyUnitCost :: () => !CommoditySymbol -> !CommoditySymbol -> !Quantity -> MixedAmountKey
+ Hledger.Data: pattern MixedAmountKeyTotalCost :: () => !CommoditySymbol -> !CommoditySymbol -> MixedAmountKey
- Hledger.Data.AccountName: accountNamePostingType :: AccountName -> PostingType
+ Hledger.Data.AccountName: accountNamePostingType :: AccountName -> PostingRealness
- Hledger.Data.AccountName: accountNameWithPostingType :: PostingType -> AccountName -> AccountName
+ Hledger.Data.AccountName: accountNameWithPostingType :: PostingRealness -> AccountName -> AccountName
- Hledger.Data.Amount: AmountFormat :: Bool -> Bool -> Maybe [CommoditySymbol] -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> AmountFormat
+ Hledger.Data.Amount: AmountFormat :: Bool -> Bool -> Maybe [CommoditySymbol] -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> Bool -> AmountFormat
- Hledger.Data.Balancing: BalancingOpts :: Bool -> Bool -> Maybe (Map CommoditySymbol AmountStyle) -> TransactionBalancingPrecision -> Map AccountName AccountType -> BalancingOpts
+ Hledger.Data.Balancing: BalancingOpts :: Bool -> Bool -> Maybe (Map CommoditySymbol AmountStyle) -> TransactionBalancingPrecision -> Bool -> AccountName -> Map AccountName AccountType -> Set CommoditySymbol -> Map AccountName Text -> Bool -> Bool -> BalancingOpts
- Hledger.Data.Journal: journalTransactionsSimilarTo :: Journal -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, Age, SimilarityScore, Transaction)]
+ Hledger.Data.Journal: journalTransactionsSimilarTo :: Journal -> Day -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, TimeDistance, SimilarityScore, Transaction)]
- Hledger.Data.Posting: postingAddHiddenAndMaybeVisibleTag :: Bool -> HiddenTag -> Posting -> Posting
+ Hledger.Data.Posting: postingAddHiddenAndMaybeVisibleTag :: Bool -> Bool -> HiddenTag -> Posting -> Posting
- Hledger.Data.Posting: postingAsLines :: Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
+ Hledger.Data.Posting: postingAsLines :: AmountFormat -> Bool -> Bool -> Int -> Int -> AmountCols -> Posting -> ([Text], PostingWidths)
- Hledger.Data.Posting: postingsAsLines :: Bool -> [Posting] -> [Text]
+ Hledger.Data.Posting: postingsAsLines :: AmountFormat -> Bool -> [Posting] -> [Text]
- Hledger.Data.Posting: showAccountName :: Maybe Int -> PostingType -> AccountName -> Text
+ Hledger.Data.Posting: showAccountName :: Maybe Int -> PostingRealness -> AccountName -> Text
- Hledger.Data.Types: BalancedVirtualPosting :: PostingType
+ Hledger.Data.Types: BalancedVirtualPosting :: PostingRealness
- Hledger.Data.Types: Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> Commodity
+ Hledger.Data.Types: Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> [(Amount, SourcePos)] -> SourcePos -> Commodity
- Hledger.Data.Types: CostBasis :: !Maybe Amount -> !Maybe Day -> !Maybe Text -> CostBasis
+ Hledger.Data.Types: CostBasis :: !Maybe Day -> !Maybe Text -> !Maybe Amount -> CostBasis
- Hledger.Data.Types: Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> POSIXTime -> Journal
+ Hledger.Data.Types: Journal :: Maybe Year -> [Maybe Year] -> Maybe (CommoditySymbol, AmountStyle) -> Maybe DecimalMark -> [AccountName] -> [AccountAlias] -> [AccountAlias] -> [TimeclockEntry] -> [(FilePath, FilePath)] -> Maybe ParsePos -> Set AmountStyle -> Set Text -> FastPathStats -> [(Payee, PayeeDeclarationInfo)] -> [(TagName, TagDeclarationInfo)] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountName [Tag] -> Map AccountType [AccountName] -> Map AccountName AccountType -> Map CommoditySymbol Commodity -> Map CommoditySymbol [Tag] -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [AssertDirective] -> [Transaction] -> [JournalItem] -> [JournalFile] -> [(FilePath, [FilePath])] -> POSIXTime -> Journal
- Hledger.Data.Types: Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting
+ Hledger.Data.Types: Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingRealness -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting
- Hledger.Data.Types: VirtualPosting :: PostingType
+ Hledger.Data.Types: VirtualPosting :: PostingRealness
- Hledger.Data.Types: [jfiles] :: Journal -> [(FilePath, Text)]
+ Hledger.Data.Types: [jfiles] :: Journal -> [JournalFile]
- Hledger.Query: Amt :: OrdPlus -> Quantity -> Query
+ Hledger.Query: Amt :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query
- Hledger.Read.Common: InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> Bool -> DateSpan -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Day -> Bool -> InputOpts
+ Hledger.Read.Common: InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> DateSpan -> Bool -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Day -> Bool -> Maybe FilePath -> Map FilePath Text -> InputOpts
- Hledger.Read.Common: amountp' :: forall (m :: Type -> Type). Bool -> JournalParser m Amount
+ Hledger.Read.Common: amountp' :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
- Hledger.Read.Common: journalAddFile :: (FilePath, Text) -> Journal -> Journal
+ Hledger.Read.Common: journalAddFile :: JournalFile -> Journal -> Journal
- Hledger.Read.Common: lotcostp :: forall (m :: Type -> Type). Quantity -> JournalParser m (Maybe Amount)
+ Hledger.Read.Common: lotcostp :: forall (m :: Type -> Type). Quantity -> JournalParser m CostBasis
- Hledger.Read.Common: rawOptsToInputOpts :: Day -> Bool -> Bool -> RawOpts -> InputOpts
+ Hledger.Read.Common: rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts
- Hledger.Read.InputOptions: InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> Bool -> DateSpan -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Day -> Bool -> InputOpts
+ Hledger.Read.InputOptions: InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> String -> Maybe DateSpan -> Bool -> DateSpan -> Bool -> Bool -> Bool -> Bool -> BalancingOpts -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Day -> Bool -> Maybe FilePath -> Map FilePath Text -> InputOpts
- Hledger.Read.RulesReader: readJournalFromCsv :: CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO Journal
+ Hledger.Read.RulesReader: readJournalFromCsv :: FilePath -> CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO (Journal, String -> String)
- Hledger.Read.RulesReader: readRules :: FilePath -> ExceptT String IO CsvRules
+ Hledger.Read.RulesReader: readRules :: FilePath -> ExceptT String IO (CsvRules, [FilePath])
- Hledger.Read.RulesReader: rulesEncoding :: CsvRules -> ExceptT String IO (Maybe DynEncoding)
+ Hledger.Read.RulesReader: rulesEncoding :: FilePath -> CsvRules -> ExceptT String IO (Maybe DynEncoding)
- Hledger.Reports.AccountTransactionsReport: accountTransactionsReportItems :: Query -> Query -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem]
+ Hledger.Reports.AccountTransactionsReport: accountTransactionsReportItems :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount) -> Int -> MixedAmount -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem]
- Hledger.Reports.ReportOptions: ReportOpts :: Period -> Interval -> [Status] -> Maybe ConversionOp -> Maybe ValuationType -> Bool -> DepthSpec -> Bool -> Bool -> Bool -> Bool -> StringFormat -> Maybe Text -> Bool -> [Text] -> Bool -> Bool -> SortSpec -> Bool -> BalanceCalculation -> BalanceAccumulation -> Maybe Text -> AccountListMode -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe NormalSign -> Bool -> Bool -> Layout -> ReportOpts
+ Hledger.Reports.ReportOptions: ReportOpts :: Period -> Interval -> [Status] -> Maybe ConversionOp -> Maybe ValuationType -> Bool -> DepthSpec -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> Bool -> StringFormat -> Maybe Text -> Bool -> [Text] -> Bool -> Bool -> SortSpec -> Bool -> BalanceCalculation -> BalanceAccumulation -> Maybe Text -> AccountListMode -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe NormalSign -> Bool -> Bool -> Layout -> PeriodTitles -> Maybe Text -> Maybe Text -> Translations -> ReportOpts
- Hledger.Reports.ReportOptions: ReportSpec :: ReportOpts -> Day -> Query -> [QueryOpt] -> ReportSpec
+ Hledger.Reports.ReportOptions: ReportSpec :: ReportOpts -> Day -> Query -> Query -> [QueryOpt] -> ReportSpec
- Hledger.Reports.ReportOptions: reportPeriodName :: BalanceAccumulation -> [DateSpan] -> DateSpan -> Text
+ Hledger.Reports.ReportOptions: reportPeriodName :: ReportOpts -> [DateSpan] -> DateSpan -> Text
- Hledger.Write.Html: toHtml :: forall (m :: Type -> Type). (ToHtml a, Monad m) => a -> HtmlT m ()
+ Hledger.Write.Html: toHtml :: ToMarkup a => a -> Html
- Hledger.Write.Html: type Html = Html ()
+ Hledger.Write.Html: type Html = Markup
- Hledger.Write.Spreadsheet: Cell :: Type -> Border border -> Style -> Span -> Text -> Class -> text -> Cell border text
+ Hledger.Write.Spreadsheet: Cell :: Type -> Border border -> Style -> Span -> Text -> Text -> Class -> [text] -> text -> Cell border text
- Hledger.Write.Spreadsheet: addHeaderBorders :: [Cell () text] -> [Cell NumLines text]
+ Hledger.Write.Spreadsheet: addHeaderBorders :: Functor f => f (Cell () text) -> f (Cell NumLines text)
- Hledger.Write.Spreadsheet: rawTableContent :: [[Cell border text]] -> [[text]]
+ Hledger.Write.Spreadsheet: rawTableContent :: Functor f => [f (Cell border text)] -> [f text]

Files

CHANGES.md view
@@ -5,11 +5,10 @@ | | | |_) | |_|_|_.__/ -Breaking changes--Fixes--Improvements+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.  --> @@ -17,6 +16,128 @@ 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@@ -33,8 +154,8 @@   # 1.52.1 2026-04-28- - ++ # 1.52 2026-03-20  Breaking changes@@ -48,7 +169,7 @@   exception if the amount's quantity was zero. Now it's a no-op in that case.   [#2476] -[#2476]: https://github.com/simonmichael/hledger/issues/2476+[#2476]: https://github.com/hledgerorg/hledger/issues/2476   # 1.51.2 2026-01-08@@ -57,6 +178,8 @@  # 1.51.1 2025-12-08 +# 1.50.5 2025-12-08+ # 1.51 2025-12-05  Breaking changes@@ -73,8 +196,6 @@   [#2468]  -# 1.50.5 2025-12-08- # 1.50.4 2025-12-04  # 1.50.3 2025-11-18@@ -286,7 +407,7 @@ - distinguish oneLineFmt and oneLineNoCostFmt; add fullZeroFmt - matchedPostingsBeforeAndDuring: improve debug output -[#2177]: https://github.com/simonmichael/hledger/issues/2177+[#2177]: https://github.com/hledgerorg/hledger/issues/2177   # 1.32.3 2024-01-28@@ -612,12 +733,12 @@ - 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/simonmichael/hledger/issues/1813) (Stephen Morgan)+  ([#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/simonmichael/hledger/issues/1774)+  ([#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.@@ -710,8 +831,8 @@   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/simonmichael/hledger/issues/1563), -  [#1564](https://github.com/simonmichael/hledger/issues/1564), +  ([#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@@ -734,7 +855,7 @@   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/simonmichael/hledger/issues/1650), Stephen Morgan)+  ([#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@@ -754,7 +875,7 @@    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/simonmichael/hledger/issues/1545).+  [#1545](https://github.com/hledgerorg/hledger/issues/1545).        rsOpts      -> _rsReportOpts       rsToday     -> _rsDay@@ -829,7 +950,7 @@   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/simonmichael/hledger/issues/1638), Stephen Morgan)+  ([#1638](https://github.com/hledgerorg/hledger/issues/1638), Stephen Morgan)  # 1.22.1 2021-08-02 @@ -1287,7 +1408,7 @@ - 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/simonmichael/hledger/pull/1330#issuecomment-684075129+  https://github.com/hledgerorg/hledger/pull/1330#issuecomment-684075129   has some ideas on this.  - Query no longer has a custom Show instance
Hledger.hs view
@@ -31,6 +31,11 @@ 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@@ -38,6 +43,11 @@   ,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   ]  
Hledger/Data.hs view
@@ -11,6 +11,7 @@ module Hledger.Data (                module Hledger.Data.Account,                module Hledger.Data.AccountName,+               module Hledger.Data.AccountType,                module Hledger.Data.Amount,                module Hledger.Data.BalanceData,                module Hledger.Data.Balancing,@@ -22,6 +23,7 @@                module Hledger.Data.JournalChecks,                module Hledger.Data.Json,                module Hledger.Data.Ledger,+               module Hledger.Data.Lots,                module Hledger.Data.Period,                module Hledger.Data.PeriodData,                module Hledger.Data.PeriodicTransaction,@@ -41,6 +43,7 @@ import Hledger.Data.Account import Hledger.Data.BalanceData import Hledger.Data.AccountName+import Hledger.Data.AccountType import Hledger.Data.Amount import Hledger.Data.Balancing import Hledger.Data.Currency@@ -51,6 +54,7 @@ import Hledger.Data.JournalChecks import Hledger.Data.Json import Hledger.Data.Ledger+import Hledger.Data.Lots import Hledger.Data.Period import Hledger.Data.PeriodData import Hledger.Data.PeriodicTransaction
Hledger/Data/AccountName.hs view
@@ -11,6 +11,7 @@ module Hledger.Data.AccountName (    accountLeafName   ,accountNameComponents+  ,accountNameHasEmptyPart   ,accountNameDrop   ,accountNameFromComponents   ,accountNameLevel@@ -24,6 +25,8 @@   ,accountNameInferTypeExcept   ,accountNameType   ,defaultBaseConversionAccount+  ,defaultGainAccount+  ,defaultImbalanceAccount   ,assetAccountRegex   ,cashAccountRegex   ,liabilityAccountRegex@@ -31,6 +34,8 @@   ,conversionAccountRegex   ,revenueAccountRegex   ,gainAccountRegex+  ,unrealisedGainAccountRegex+  ,imbalanceAccountRegex   ,expenseAccountRegex   ,acctsep   ,acctsepchar@@ -77,7 +82,6 @@  import Hledger.Data.Types hiding (asubs) import Hledger.Utils-import Data.List (partition)  -- $setup -- >>> :set -XOverloadedStrings@@ -92,6 +96,14 @@ -- when no other account of type V/Conversion has been declared. defaultBaseConversionAccount = "equity:conversion" +-- The default account name for inferred gain postings,+-- when no other account of type G/Gain has been declared.+defaultGainAccount = "revenues:gain"++-- 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"+ -- | Regular expressions matching common English top-level account names, -- used as a fallback when account types are not declared. assetAccountRegex      = toRegexCI' "^assets?(:|$)"@@ -101,20 +113,32 @@ 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?(:|$)"  -- | 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-  | regexMatchText cashAccountRegex       a = Just Cash-  | regexMatchText assetAccountRegex      a = Just Asset-  | regexMatchText liabilityAccountRegex  a = Just Liability-  | regexMatchText conversionAccountRegex a = Just Conversion-  | regexMatchText equityAccountRegex     a = Just Equity-  | regexMatchText revenueAccountRegex    a = Just Revenue-  | regexMatchText expenseAccountRegex    a = Just Expense-  | otherwise                               = Nothing+  | 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  -- | Like accountNameInferType, but exclude the provided types from the guesses. -- Used eg to prevent "equity:conversion" being inferred as Conversion when a different@@ -138,11 +162,19 @@ accountNameComponents :: AccountName -> [Text] accountNameComponents = T.splitOn acctsep +-- | 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+ accountNameFromComponents :: [Text] -> AccountName accountNameFromComponents = T.intercalate acctsep  accountLeafName :: AccountName -> Text-accountLeafName = last . accountNameComponents+accountLeafName = T.takeWhileEnd (/= acctsepchar)  -- | Truncate all account name components but the last to two characters. accountSummarisedName :: AccountName -> Text@@ -171,23 +203,23 @@ unbudgetedAccountName :: T.Text unbudgetedAccountName = "<unbudgeted>" -accountNamePostingType :: AccountName -> PostingType+accountNamePostingType :: AccountName -> PostingRealness accountNamePostingType a-    | T.null a = RegularPosting+    | T.null a = RealPosting     | T.head a == '[' && T.last a == ']' = BalancedVirtualPosting     | T.head a == '(' && T.last a == ')' = VirtualPosting-    | otherwise = RegularPosting+    | otherwise = RealPosting  accountNameWithoutPostingType :: AccountName -> AccountName accountNameWithoutPostingType a = case accountNamePostingType a of                                     BalancedVirtualPosting -> textUnbracket a                                     VirtualPosting -> textUnbracket a-                                    RegularPosting -> a+                                    RealPosting -> a -accountNameWithPostingType :: PostingType -> AccountName -> AccountName+accountNameWithPostingType :: PostingRealness -> AccountName -> AccountName accountNameWithPostingType BalancedVirtualPosting = wrap "[" "]" . accountNameWithoutPostingType accountNameWithPostingType VirtualPosting         = wrap "(" ")" . accountNameWithoutPostingType-accountNameWithPostingType RegularPosting         = accountNameWithoutPostingType+accountNameWithPostingType RealPosting            = accountNameWithoutPostingType  -- | Prefix one account name to another, preserving posting type -- indicators like concatAccountNames.@@ -199,7 +231,7 @@ -- the resulting account name. concatAccountNames :: [AccountName] -> AccountName concatAccountNames as = accountNameWithPostingType t $ T.intercalate ":" $ map accountNameWithoutPostingType as-    where t = headDef RegularPosting $ filter (/= RegularPosting) $ map accountNamePostingType as+    where t = headDef RealPosting $ filter (/= RealPosting) $ map accountNamePostingType as  -- | Rewrite an account name using all matching aliases from the given list, in sequence. -- Each alias sees the result of applying the previous aliases.@@ -264,8 +296,10 @@ topAccountName :: AccountName -> AccountName topAccountName = T.takeWhile (/= acctsepchar) +-- | 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 = accountNameFromComponents . init . accountNameComponents+parentAccountName = T.dropEnd 1 . T.dropWhileEnd (/= acctsepchar)  parentAccountNames :: AccountName -> [AccountName] parentAccountNames a = parentAccountNames' $ parentAccountName a@@ -286,21 +320,22 @@ subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName] subAccountNamesFrom accts a = filter (`isSubAccountNameOf` a) accts --- | Convert a list of account names to a tree, efficiently.+-- | 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 ("root", expandAccountNames accts)+accountNameTreeFrom accts = unfoldTree grow Nothing   where-    -- unfoldTree :: (b -> (a, [b])) -> b -> Tree a-    -- grow :: (b -> (a, [b]))-    -- a = AccountName                  - the label at each node of the tree-    -- b = (AccountName, [AccountName]) - the next node's account, and the accounts remaining to consume under it-    grow :: ((AccountName, [AccountName]) -> (AccountName, [(AccountName, [AccountName])]))-    grow (a,[])   = (a,[])-    grow (a,rest) = (a, [(s, filter (s `isAccountNamePrefixOf`) deepersubs) | s <- asubs])-      where-        (asubs, deepersubs) = partition (isChildOf a) rest-        isChildOf "root" = (1==) . accountNameLevel-        isChildOf acct   = (`isSubAccountNameOf` acct)+    -- 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:@@ -391,11 +426,13 @@ -- | 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 = ['[', '?', '+', '|', '(', ')', '*', '$', '^', '\\']+    escapedChars = ['[', ']', '?', '+', '|', '(', ')', '*', '$', '^', '\\', '{', '}', '.']  -- | Convert an account name to a regular expression matching it and its subaccounts. accountNameToAccountRegex :: AccountName -> Regexp@@ -420,7 +457,10 @@ --isAccountRegex s = take 1 s == "^" && take 5 (reverse s) == ")$|:("  tests_AccountName = testGroup "AccountName" [-   testCase "accountNameTreeFrom" $ do+   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" []]]@@ -449,14 +489,19 @@     accountNameInferType "revenues"          @?= Just Revenue     accountNameInferType "revenue"           @?= Just Revenue     accountNameInferType "income"            @?= Just Revenue-    -- Gain type is no longer inferred from names; these are now Revenue-    accountNameInferType "income:gains"          @?= Just Revenue-    accountNameInferType "revenue:gain"          @?= Just Revenue-    accountNameInferType "revenues:capital-gains" @?= Just Revenue-    accountNameInferType "income:capitalgain"    @?= Just Revenue-    accountNameInferType "income:losses"         @?= Just Revenue-    accountNameInferType "revenue:capital-loss"  @?= Just Revenue-    accountNameInferType "income:gains:realized" @?= 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"
+ 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
@@ -64,10 +64,15 @@   (@@),   amountWithCommodity,   amountCost,+  amountCostBasis,+  amountSetCostToBasis,   amountIsZero,   amountLooksZero,+  amountSetQuantity,   divideAmount,+  divideAmountAndUpdatePrecision,   multiplyAmount,+  multiplyQuantities,   invertAmount,   -- ** styles   amountstyle,@@ -78,6 +83,7 @@   amountStylesSetRounding,   amountUnstyled,   commodityStylesFromAmounts,+  addAmountStyle,   -- canonicalStyleFrom,   getAmounts, @@ -91,11 +97,15 @@   machineFmt,   showAmount,   showAmountWith,+  showAmountsDistinctly,   showAmountB,+  showAmountQuantity,   showAmountCost,   showAmountCostB,   showAmountCostBasis,   showAmountCostBasisB,+  showAmountCostBasisLedger,+  showAmountCostBasisLedgerB,   cshowAmount,   showAmountWithZeroCommodity,   showAmountDebug,@@ -108,13 +118,13 @@   amountSetFullPrecisionUpTo,   amountInternalPrecision,   amountDisplayPrecision,-  defaultMaxPrecision,+  defaultMaxDisplayPrecision,   setAmountInternalPrecision,   withInternalPrecision,   setAmountDecimalPoint,   withDecimalPoint,   amountStripCost,-+     -- * MixedAmount   nullmixedamt,   missingmixedamt,@@ -134,16 +144,19 @@   mixedAmountStripCosts,   -- ** arithmetic   mixedAmountCost,+  mixedAmountCostBasis,   maNegate,   maPlus,   maMinus,   maSum,   divideMixedAmount,+  divideMixedAmountAndUpdatePrecision,   multiplyMixedAmount,   averageMixedAmounts,   sumAndAverageMixedAmounts,   isNegativeAmount,   isNegativeMixedAmount,+  amountRoundedQuantity,   mixedAmountIsZero,   maIsZero,   maIsNonZero,@@ -156,6 +169,7 @@   -- ** rendering   showMixedAmount,   showMixedAmountWith,+  showMixedAmountsDistinctly,   showMixedAmountOneLine,   showMixedAmountDebug,   showMixedAmountWithoutCost,@@ -165,20 +179,23 @@   showMixedAmountB,   showMixedAmountLinesB,   showMixedAmountLinesPartsB,+  showMixedAmountOneLinePartsB,   wbToText,   wbUnpack,   mixedAmountSetPrecision,   mixedAmountSetFullPrecision,+  mixedAmountSetFullPrecisionCapped,   mixedAmountSetFullPrecisionUpTo,   mixedAmountSetPrecisionMin,   mixedAmountSetPrecisionMax,    -- * misc.+  showPriceDirective,   tests_Amount ) where  import Prelude hiding (Applicative(..))-import Control.Applicative (Applicative(..), (<|>))+import Control.Applicative ((<|>)) import Control.Monad (foldM) import Data.Char (isDigit) import Data.Decimal (DecimalRaw(..), decimalPlaces, normalizeDecimal, roundTo)@@ -191,7 +208,7 @@ import Data.List.NonEmpty (NonEmpty(..), nonEmpty) import Data.Map.Strict qualified as M import Data.Set qualified as S-import Data.Maybe (fromMaybe, isNothing)+import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Semigroup (Semigroup(..)) import Data.Text qualified as T import Data.Text.Lazy.Builder qualified as TB@@ -202,6 +219,7 @@ 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)@@ -222,14 +240,27 @@  -- characters that may not be used in a non-quoted commodity symbol isNonsimpleCommodityChar :: Char -> Bool-isNonsimpleCommodityChar = liftA2 (||) isDigit isOther-  where-    otherChars = "-+.@*;\t\n \"{}=" :: T.Text-    isOther c = T.any (==c) otherChars+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.@@ -252,6 +283,7 @@   , 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.@@ -272,6 +304,7 @@   , displayCostBasis        = True   , displayColour           = False   , displayQuotes           = True+  , displayLedgerLotSyntax  = False   }  -- | Like defaultFmt but show zero amounts with commodity symbol and styling, like non-zero amounts.@@ -349,6 +382,26 @@ 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: --@@ -362,9 +415,28 @@ amountCost a@Amount{aquantity=q, acost=mp} =     case mp of       Nothing                                  -> a-      Just (UnitCost  p@Amount{aquantity=pq}) -> p{aquantity=pq * q}+      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}@@ -377,13 +449,35 @@     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 n = transformAmount (/n)+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 (*n)+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.@@ -424,10 +518,11 @@ amountIsZero = testAmountAndTotalCost (\Amount{aquantity=Decimal _ q} -> q == 0)  -- | Does this amount's internal Decimal representation have the--- maximum number of digits, suggesting that it probably is+-- 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 = (>= 255) . numDigitsInteger . decimalMantissa . aquantity+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@@ -489,15 +584,15 @@   where     p = case mmaxp of       Just maxp -> min maxp $ max disp intp-      Nothing   -> if amountHasMaxDigits a then defaultMaxPrecision else 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.-defaultMaxPrecision :: Word8-defaultMaxPrecision = 8+defaultMaxDisplayPrecision :: Word8+defaultMaxDisplayPrecision = 8  -- | How many internal decimal digits are stored for this amount ? amountInternalPrecision :: Amount -> Word8@@ -621,8 +716,8 @@ amountStyleApplyWithRounding :: Bool -> Quantity -> AmountStyle -> AmountStyle -> AmountStyle amountStyleApplyWithRounding iscost q news@AmountStyle{asprecision=newp, asrounding=newr} AmountStyle{asprecision=oldp} =   case newr of-    NoRounding   -> news{asprecision=oldp}-    SoftRounding -> news{asprecision=if iscost then oldp else newp'}+    NoRounding   -> withprec oldp+    SoftRounding -> withprec $ if iscost then oldp else newp'       where         newp' = case (newp, oldp) of           (Precision new, Precision old) ->@@ -631,8 +726,11 @@             else Precision $ max (min old internal) new               where internal = decimalPlaces $ normalizeDecimal q           _ -> NaturalPrecision-    HardRounding -> news{asprecision=if iscost then oldp else newp}+    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@@ -659,9 +757,19 @@ -- 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 (\a -> M.insertWith canonicalStyle (acommodity a) (astyle a)) mempty+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@@ -715,6 +823,33 @@ 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. @@ -725,8 +860,8 @@                    ,displayForceDecimalMark, displayCost, displayCostBasis, displayColour, displayQuotes}   a@Amount{astyle=style} =     color $ case ascommodityside style of-      L -> (if displayCommodity then wbFromText comm <> space else mempty) <> quantity' <> cost <> costbasis-      R -> quantity' <> (if displayCommodity then space <> wbFromText comm else mempty) <> cost <> costbasis+      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 $@@ -736,7 +871,9 @@       | 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 showAmountCostBasisB 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@@ -755,7 +892,7 @@ showAmountCostDebug (Just (UnitCost pa))  = "@ "  ++ showAmountDebug pa showAmountCostDebug (Just (TotalCost pa)) = "@@ " ++ showAmountDebug pa --- | Show an amount's cost basis as Ledger-style lot syntax: {LOTCOST} [LOTDATE] (LOTNOTE).+-- | Show an amount's cost basis as consolidated lot syntax: {DATE, "LABEL", COST}. showAmountCostBasis :: Amount -> String showAmountCostBasis = wbUnpack . showAmountCostBasisB defaultFmt @@ -763,9 +900,35 @@ 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} ->-    lotcost <> lotdate <> lotnote+    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@@ -864,13 +1027,6 @@     abs    = mapMixedAmount (\amt -> amt { aquantity = abs (aquantity amt)})     signum = error' "error, mixed amounts do not support signum" --- | Calculate the key used to store an Amount within a MixedAmount.-amountKey :: Amount -> MixedAmountKey-amountKey amt@Amount{acommodity=c} = case acost amt of-    Nothing             -> MixedAmountKeyNoCost    c-    Just (TotalCost p) -> MixedAmountKeyTotalCost c (acommodity p)-    Just (UnitCost  p) -> MixedAmountKeyUnitCost  c (acommodity p) (aquantity p)- -- | The empty mixed amount. nullmixedamt :: MixedAmount nullmixedamt = Mixed mempty@@ -885,7 +1041,7 @@ -- 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) = amountKey missingamt `M.member` ma+isMissingMixedAmount (Mixed ma) = mixedAmountKey missingamt `M.member` ma  -- | Convert amounts in various commodities into a mixed amount. mixed :: Foldable t => t Amount -> MixedAmount@@ -893,44 +1049,54 @@  -- | Create a MixedAmount from a single Amount. mixedAmount :: Amount -> MixedAmount-mixedAmount a = Mixed $ M.singleton (amountKey a) a---- | Add an Amount to a MixedAmount, normalising the result.--- Amounts with different costs are kept separate.-maAddAmount :: MixedAmount -> Amount -> MixedAmount-maAddAmount (Mixed ma) a = Mixed $ M.insertWith sumSimilarAmountsUsingFirstCost (amountKey a) a ma---- | Add a collection of Amounts to a MixedAmount, normalising the result.--- Amounts with different costs are kept separate.-maAddAmounts :: Foldable t => MixedAmount -> t Amount -> MixedAmount-maAddAmounts = foldl' maAddAmount+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 MixedAmount, keeping the cost of the first if any.--- Amounts with different costs are kept separate (since 2021).+-- | Sum two MixedAmounts. (Any cost basis on the amounts will be lost.) maPlus :: MixedAmount -> MixedAmount -> MixedAmount-maPlus (Mixed as) (Mixed bs) = Mixed $ M.unionWith sumSimilarAmountsUsingFirstCost as bs+maPlus (Mixed as) (Mixed bs) = Mixed $ M.unionWith sumSimilarAmounts as bs --- | Subtract a MixedAmount from another.--- Amounts with different costs are kept separate.+-- | 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.--- Amounts with different costs are kept separate.-maSum :: Foldable t => t MixedAmount -> MixedAmount+-- | 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 n = transformMixedAmount (/n)+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 (*n)+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@@ -1028,8 +1194,7 @@ -- | 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. lexicographically first by commodity, then by cost commodity, then by--- unit cost from most negative to most positive.+-- i.e. sorted by commodity and transacted cost. amountsRaw :: MixedAmount -> [Amount] amountsRaw (Mixed ma) = toList ma @@ -1052,11 +1217,12 @@       | acommodity amt == acommodity result = Just $ amt + result       | otherwise                           = Nothing --- | Sum same-commodity amounts in a lossy way, applying the first--- cost to the result and discarding any other costs. Only used as a--- rendering helper.-sumSimilarAmountsUsingFirstCost :: Amount -> Amount -> Amount-sumSimilarAmountsUsingFirstCost a b = (a + b){acost=p}+-- | 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))@@ -1067,17 +1233,8 @@ filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount filterMixedAmount p (Mixed ma) = Mixed $ M.filter p ma --- | Return an unnormalised MixedAmount containing just the amounts in the--- requested commodity from the original mixed amount.------ The result will contain at least one Amount of the requested commodity,--- even if the original mixed amount did not (with quantity zero in that case,--- and this would be discarded when the mixed amount is next normalised).------ The result can contain more than one Amount of the requested commodity,--- eg because there were several with different costs,--- or simply because the original mixed amount was was unnormalised.---+-- | 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}@@ -1089,17 +1246,25 @@ 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, cost--- commodity, or unit cost amount). This condition is not checked.+-- 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 (Mixed ma) =-    foldl' (\m a -> maAddAmount m (amountCost a)) (Mixed noCosts) withCosts+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.@@ -1164,6 +1329,30 @@ 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@@ -1262,6 +1451,15 @@         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.@@ -1353,6 +1551,12 @@ 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,@@ -1371,13 +1575,28 @@ mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount mixedAmountSetPrecisionMax p = mapMixedAmountUnsafe (amountSetPrecisionMax p) --- | Remove all costs from a MixedAmount.+-- | Remove all transacted costs and cost bases from a MixedAmount. mixedAmountStripCosts :: MixedAmount -> MixedAmount-mixedAmountStripCosts (Mixed ma) =-    foldl' (\m a -> maAddAmount m a{acost=Nothing}) (Mixed noCosts) withCosts-  where (noCosts, withCosts) = M.partition (isNothing . acost) ma+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 @@ -1389,6 +1608,15 @@        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
Hledger/Data/Balancing.hs view
@@ -18,18 +18,24 @@ , 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)-import "extra" Control.Monad.Extra (whenM)+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)@@ -40,20 +46,23 @@ 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)+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 (fromGregorian)+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 (isAccountNamePrefixOf)+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@@ -66,7 +75,13 @@                                     --   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@@ -74,8 +89,14 @@   { ignore_assertions_     = False   , infer_balancing_costs_ = True   , commodity_styles_      = Nothing-  , txn_balancing_         = TBPExact+  , 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.@@ -96,32 +117,34 @@ --    (using the given display styles if provided) -- transactionCheckBalanced :: BalancingOpts -> Transaction -> [String]-transactionCheckBalanced BalancingOpts{commodity_styles_=_mglobalstyles, txn_balancing_} t = errs+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 ptype p of-            RegularPosting         -> (p:l, r)+        partitionPosting p ~(l, r) = case preal p of+            RealPosting            -> (p:l, r)             BalancedVirtualPosting -> (l, p:r)             VirtualPosting         -> (l, r) -    -- convert a posting's amount to cost,-    -- unless it has been marked as a redundant cost (equivalent to some nearby equity conversion postings),-    -- in which case ignore it.-    postingBalancingAmount p-      | costPostingTagName `elem` map fst (ptags p) = mixedAmountStripCosts $ pamount p-      | otherwise                                   = mixedAmountCost $ pamount p+    postingBalancingAmount = postingBalancingAmountWith setaside -    lookszero = case txn_balancing_ of-      TBPOld    -> lookszeroatglobaldisplayprecision-      TBPExact  -> lookszeroatlocaltransactionprecision+    -- 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) @@ -136,30 +159,121 @@     -- 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. Consider negating some of them."-          | otherwise     = "The real postings' sum should be 0 but is: " ++-              (showMixedAmountWith oneLineNoCostFmt{displayCost=True, displayZeroCommodity=True} $-              mixedAmountSetFullPrecisionUpTo Nothing $ mixedAmountSetFullPrecision-              rsumcost)-              ++ if rsumokold then oldbalancingmsg else ""+          | 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. Consider negating some of them."-          | otherwise     = "The balanced virtual postings' sum should be 0 but is: " ++-              (showMixedAmountWith oneLineNoCostFmt{displayCost=True, displayZeroCommodity=True} $-              mixedAmountSetFullPrecisionUpTo Nothing $ mixedAmountSetFullPrecision-              bvsumcost)-              ++ if bvsumokold then oldbalancingmsg else ""+          | 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-balancing=old to keep it working, or fix it (recommended);"+          ,"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@@ -186,6 +300,95 @@ 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.@@ -193,26 +396,28 @@ balanceTransactionHelper bopts t = do   let lbl = lbl_ "balanceTransactionHelper"   (t', inferredamtsandaccts) <- t-    & (if infer_balancing_costs_ bopts then transactionInferBalancingCosts else id)+    & (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 t', inferredamtsandaccts)+    []   -> Right (txnTieKnot $ transactionRemoveRoundedTags t', inferredamtsandaccts)     errs -> Left $ transactionBalanceError t' errs'       where         ismulticommodity = (length $ transactionCommodities t') > 1         errs' =-          [ "Automatic commodity conversion is not enabled."+          [ "Automatic commodity conversion is disabled by strict mode or the balanced check."           | ismulticommodity && not (infer_balancing_costs_ bopts)           ] ++-          errs ++-          if ismulticommodity-          then-          [ "Consider adjusting this entry's amounts, adding missing postings,"-          , "or recording conversion price(s) with @, @@ or equity postings." -          ]-          else []+          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@@ -248,6 +453,7 @@   -> 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."@@ -266,17 +472,27 @@           )   where     lbl = lbl_ "transactionInferBalancingAmount"-    (amountfulrealps, amountlessrealps) = partition hasAmount (realPostings t)-    realsum = sumPostings amountfulrealps+    -- 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 (balancedVirtualPostings t)-    bvsum = sumPostings amountfulbvps+    (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 ptype p of-          RegularPosting         | not (hasAmount p) -> Just realsum+        minferredamt = case preal p of+          RealPosting            | not (hasAmount p) -> Just realsum           BalancedVirtualPosting | not (hasAmount p) -> Just bvsum           VirtualPosting         | not (hasAmount p) -> Just 0           _                                          -> Nothing@@ -285,20 +501,22 @@           Nothing -> (p, Nothing)           Just a  -> (p{pamount=a', poriginal=Just $ originalPosting p}, Just a')             where-              -- Inferred amounts are converted to cost.+              -- 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-                -- & dbg9With (lbl "balancing amount".showMixedAmountOneLine)                 & mixedAmountCost-                -- & dbg9With (lbl "balancing amount converted to cost".showMixedAmountOneLine)-                & styleAmounts (styles-                                -- Needed until we switch to locally-inferred balancing precisions: XXX #2402-                                -- these had hard rounding set to help with balanced-checking;-                                -- set no rounding now to avoid excessive display precision in output-                                & amountStylesSetRounding NoRounding-                                & dbg9With (lbl "balancing amount styles".show))+                & 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@@ -338,30 +556,95 @@ -- 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 :: Transaction -> Transaction-transactionInferBalancingCosts t@Transaction{tpostings=ps} = t{tpostings=ps'}+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-    ps' = map (costInferrerFor t BalancedVirtualPosting . costInferrerFor t RegularPosting) ps+    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 type (real or balanced virtual) (or if we cannot or should not infer--- costs, leaves the posting unchanged).-costInferrerFor :: Transaction -> PostingType -> (Posting -> Posting)-costInferrerFor t pt = maybe id infercost inferFromAndTo+-- 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"-    postings     = filter ((==pt).ptype) $ tpostings t+    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, and these two have opposite signs. The amount we are-    -- converting from is the first commodity to appear in the ordered list of postings, and the-    -- commodity we are converting to is the other. If we cannot infer prices, return Nothing.+    -- 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 -> asum $ map orderIfMatches pcommodities+      [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)@@ -369,27 +652,49 @@                            | 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 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), ptype p == pt, acommodity a == acommodity fromamount+        | [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-        -- If only one Amount in the posting list matches fromamount we can use TotalCost.+        -- 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 = case filter (== acommodity fromamount) pcommodities of-            [_] -> TotalCost $ negate toamount-            _   -> UnitCost  $ negate unitcost `withPrecision` unitprecision+        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,@@ -422,12 +727,23 @@ -- 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-   bsStyles       :: Maybe (M.Map CommoditySymbol AmountStyle)  -- ^ commodity display styles+   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        :: Bool                                       -- ^ whether to check balance assertions+  ,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@@ -441,9 +757,19 @@  -- | Get this account's current exclusive running balance. getRunningBalanceB :: AccountName -> Balancing s MixedAmount-getRunningBalanceB acc = withRunningBalance $ \BalancingState{bsBalances} -> do-  fromMaybe nullmixedamt <$> H.lookup bsBalances acc+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@@ -456,25 +782,46 @@ -- | 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} -> do+setRunningBalanceB acc amt = withRunningBalance $ \BalancingState{bsBalances, bsAliases} -> do   old <- fromMaybe nullmixedamt <$> H.lookup bsBalances acc   H.insert bsBalances acc amt-  return $ maMinus amt old+  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} -> do-  oldebal  <- fromMaybe nullmixedamt <$> H.lookup bsBalances acc+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-        maSum . map snd $ filter ((acc `isAccountNamePrefixOf`).fst) allebals+        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}  ->@@ -493,7 +840,17 @@ -- assignments, balance assertions and posting dates are interdependent. -- journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal-journalBalanceTransactions bopts' j' =+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'@@ -515,6 +872,12 @@     -- 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@@ -523,8 +886,9 @@         -- 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 balanceSingleTransaction bopts t of+          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'@@ -533,16 +897,26 @@          -- 2. Step through these items in date order (and preserved same-day order),         -- keeping running balances for all accounts.-        runningbals <- lift $ H.newSized (length $ journalAccountNamesUsed j)-        flip runReaderT (BalancingState styles autopostingaccts (not $ ignore_assertions_ bopts) 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+        -- 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.+        -- Return the now fully-balanced and checked transactions,+        -- and any deferred balance assertion failure.         ts' <- lift $ getElems balancedtxns-        return j{jtxns=ts'}+        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." @@ -574,14 +948,24 @@     <&> map snd                 -- discard positions    -- infer any remaining missing amounts, and make sure the transaction is now fully balanced-  styles <- R.reader bsStyles-  case balanceTransactionHelper defbalancingopts{commodity_styles_=styles} t{tpostings=ps'} of+  -- (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-      -- for each amount just inferred, update the running balance-      mapM_ (uncurry addToRunningBalanceB) inferredacctsandamts+      -- 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'+      updateTransactionB t''  type NumberedPosting = (Integer, Posting) @@ -591,25 +975,28 @@ -- 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, pamount=amt, pbalanceassertion=mba})+addOrAssignAmountAndCheckAssertionB (i,p@Posting{paccount=acc, pbalanceassertion=mba})   -- an explicit posting amount   | hasAmount p = do-      newbal <- addToRunningBalanceB acc amt-      whenM (R.reader bsAssrt) $ checkBalanceAssertionB p newbal+      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)+                   -- a partial balance assignment (=, one commodity), keeping the other commodities                    else do-                     oldbalothercommodities <- filterMixedAmount ((acommodity baamount /=) . acommodity) <$> getRunningBalanceB acc+                     oldbalothercommodities <- filterMixedAmount ((acommodity baamount /=) . acommodity) <$> getbal acc                      return $ maAddAmount oldbalothercommodities baamount-      diff <- (if bainclusive then setInclusiveRunningBalanceB else setRunningBalanceB) acc newbal+      diff <- setbal acc newbal       let p' = p{pamount=filterMixedAmount (not . amountIsZero) diff, poriginal=Just $ originalPosting p}-      whenM (R.reader bsAssrt) $ checkBalanceAssertionB p' newbal+      checkOrDeferBalanceAssertionB p' newbal       return (i,p')    -- no explicit posting amount, no balance assignment@@ -622,11 +1009,24 @@ -- need to see the balance as it stands after each individual posting. addAmountAndCheckAssertionB :: Posting -> Balancing s Posting addAmountAndCheckAssertionB p | hasAmount p = do-  newbal <- addToRunningBalanceB (paccount p) $ pamount p-  whenM (R.reader bsAssrt) $ checkBalanceAssertionB p newbal+  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@@ -651,19 +1051,9 @@ checkBalanceAssertionOneCommodityB p@Posting{paccount=assertedacct} assertedcommbal actualbal = do   let isinclusive = maybe False bainclusive $ pbalanceassertion p   let istotal     = maybe False batotal     $ pbalanceassertion p-  -- mstyles <- R.reader bsStyles+  -- mstyles <- R.asks (commodity_styles_ . bsBalancingOpts)   -- let styled = maybe id styleAmounts mstyles-  actualbal' <--    if isinclusive-    then-      -- sum the running balances of this account and any of its subaccounts seen so far-      withRunningBalance $ \BalancingState{bsBalances} ->-        H.foldM-          (\ibal (acc, amt) -> return $-            if assertedacct==acc || assertedacct `isAccountNamePrefixOf` acc then maPlus ibal amt else ibal)-          nullmixedamt-          bsBalances-    else return actualbal+  actualbal' <- if isinclusive then getInclusiveRunningBalanceB assertedacct else return actualbal   let     assertedcomm = acommodity assertedcommbal @@ -692,7 +1082,7 @@         "but the calculated balance is:  %s",         "(difference: %s)",         "To troubleshoot, check this account's running balance with assertions disabled, eg:",-        "hledger reg -I '%s'%s"+        "hledger reg -E --ignore-assertions '%s'%s -e %s%s"       ])        (sourcePosPretty pos)  -- position@@ -707,8 +1097,10 @@         <> if debugLevel >= 2 then " (with costs: " <> T.pack (showMixedAmountWith fmt actualcommbal) <> ")" else ""       )       diffstr  -- their difference-      (acct ++ if isinclusive then "" else "$")  -- query matching the account(s) postings-      (if istotal then "" else (" cur:" ++ quoteForCommandLine (T.unpack assertedcomm)))  -- query matching the commodity(ies)+      (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@@ -717,11 +1109,22 @@         (_,_,_,ex) = makeBalanceAssertionErrorExcerpt p         assertedcommstr = if T.null assertedcomm then "\"\"" else assertedcomm         fmt = oneLineFmt{displayZeroCommodity=True}-        assertedstr = showAmountWith fmt assertedcommbalcostless-        actualstr   = showAmountWith fmt actualcommbalcostless+        (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@@ -987,7 +1390,7 @@             []             [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}             , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}-            , posting {paccount = "d", pamount = mixedAmount (usd 100), ptype = VirtualPosting}+            , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = VirtualPosting}             ]         ,testCase "balanced virtual postings need to balance among themselves" $           assertBool "" $@@ -1006,7 +1409,7 @@             []             [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}             , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}-            , posting {paccount = "d", pamount = mixedAmount (usd 100), ptype = BalancedVirtualPosting}+            , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}             ]         ,testCase "balanced virtual postings need to balance among themselves (2)" $           assertBool "" $@@ -1024,8 +1427,8 @@             []             [ posting {paccount = "b", pamount = mixedAmount (usd 1.00)}             , posting {paccount = "c", pamount = mixedAmount (usd (-1.00))}-            , posting {paccount = "d", pamount = mixedAmount (usd 100), ptype = BalancedVirtualPosting}-            , posting {paccount = "3", pamount = mixedAmount (usd (-100)), ptype = BalancedVirtualPosting}+            , posting {paccount = "d", pamount = mixedAmount (usd 100), preal = BalancedVirtualPosting}+            , posting {paccount = "3", pamount = mixedAmount (usd (-100)), preal = BalancedVirtualPosting}             ]         ] 
Hledger/Data/Currency.hs view
@@ -10,22 +10,29 @@ {-# 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. Usually three upper case letters.+-- | 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 $. Usually one character, sometimes more.--- Different from hledger's more general "CommoditySymbol" type.+-- | 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 ISO 4217 currency code corresponding to this currency symbol.+-- | Look for a currency code corresponding to this currency symbol. -- -- >>> currencySymbolToCode "" -- Nothing@@ -34,13 +41,24 @@ currencySymbolToCode :: CurrencySymbol -> Maybe CurrencyCode currencySymbolToCode s = M.lookup s currencyCodesBySymbol --- | Look for a currency symbol corresponding to this ISO 4217 currency code.+-- | 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] @@ -155,6 +173,24 @@   ("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
@@ -44,9 +44,13 @@   showDateSpan,   showDateSpanDebug,   showDateSpanAbbrev,+  showDateSpanAbbrevWith,+  showDateSpanFull,+  showDateSpanForQuery,   elapsedSeconds,   prevday,   periodexprp,+  reportingintervalp,   parsePeriodExpr,   parsePeriodExpr',   nulldatespan,@@ -98,7 +102,7 @@ import Prelude hiding (Applicative(..)) import Control.Applicative (Applicative(..)) import Control.Applicative.Permutations-import Control.Monad (guard, unless)+import Control.Monad (guard, unless, when) import Control.Monad.Fail qualified as Fail (MonadFail, fail) import Data.Char (digitToInt, isDigit) import Data.Default (def)@@ -154,6 +158,52 @@ 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@@ -1139,13 +1189,29 @@ -- 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 = liftA2 fromToSpan-    (optional ((string' "from" <|> string' "since") *> skipNonNewlineSpaces) *> smartdateorquarterstartp rdate)-    (skipNonNewlineSpaces *> choice [string' "to", string "..", string "-"]-    *> skipNonNewlineSpaces *> smartdateorquarterstartp rdate)+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)@@ -1158,7 +1224,7 @@ fromdatespanp :: Day -> TextParser m DateSpan fromdatespanp rdate = fromSpan <$> choice   [ (string' "from" <|> string' "since") *> skipNonNewlineSpaces *> smartdateorquarterstartp rdate-  , smartdateorquarterstartp rdate <* choice [string "..", string "-"]+  , smartdateorquarterstartp rdate <* choice [string "..", string "-" <* notFollowedBy digitChar]   ]   where     fromSpan b = DateSpan (Just $ fixSmartDate rdate b) Nothing
Hledger/Data/DayPartition.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE CPP #-} {-| A partition of time into contiguous spans, for defining reporting periods. -}@@ -17,11 +18,17 @@ , 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@@ -61,7 +68,7 @@ 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.nub $ NE.sort xs+  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.@@ -181,30 +188,67 @@ -- >>> t (MonthAndDay 11 29) 2012 10 01 2013 10 15 -- Just ((2012-11-29,2013-11-28) :| []) splitSpan :: Bool -> Interval -> DateSpan -> Maybe DayPartition-splitSpan _      _                        (DateSpan Nothing Nothing) = Nothing-splitSpan _      _                        ds | isEmptySpan ds = Nothing-splitSpan _      NoInterval               (DateSpan (Just s) (Just e)) = Just $ boundariesToDayPartition (fromEFDay s :| [fromEFDay e])-splitSpan _      NoInterval               _  = Nothing-splitSpan _      (Days n)                 ds = splitspan id addDays n ds-splitSpan adjust (Weeks n)                ds = splitspan (if adjust then startofweek    else id) addDays                 (7*n) ds-splitSpan adjust (Months n)               ds = splitspan (if adjust then startofmonth   else id) addGregorianMonthsClip  n     ds-splitSpan adjust (Quarters n)             ds = splitspan (if adjust then startofquarter else id) addGregorianMonthsClip  (3*n) ds-splitSpan adjust (Years n)                ds = splitspan (if adjust then startofyear    else id) addGregorianYearsClip   n     ds-splitSpan adjust (NthWeekdayOfMonth n wd) ds = splitspan (startWeekdayOfMonth n wd)              advancemonths           1     ds+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-splitSpan _      (MonthDay dom)           ds = splitspan (nextnthdayofmonth dom) (addGregorianMonthsToMonthday dom) 1 ds-splitSpan _      (MonthAndDay m d)        ds = splitspan (nextmonthandday m d)   addGregorianYearsClip              1 ds-splitSpan _      (DaysOfWeek [])          _  = Nothing-splitSpan _      (DaysOfWeek days@(n:_))  ds = do+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 -- can't show this when debugging, it'll hang:+    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..]-        -- The first representative of each weekday-        starts = map (\d -> addDays (toInteger $ d - n) $ nthdayofweekcontaining n s) days-    spansFromBoundaries e bdrys+    Just (e, bdrys)  -- | Fill in missing start/end dates for calculating 'splitSpan'. dateSpanSplitLimits :: (Day -> Day) -> (Day -> Day) -> DateSpan -> Maybe (Day, Day)@@ -214,18 +258,19 @@ 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) --- Split the given span into exact spans using the provided helper functions:+-- 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 sub-span's start date.+-- 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 sub-spans' start dates, possibly with stride increased by a multiplier.+-- 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.-splitspan :: (Day -> Day) -> (Integer -> Day -> Day) -> Int -> DateSpan -> Maybe DayPartition-splitspan start next mult ds = do+--+-- 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-    let bdrys = mapM (next . toInteger) [0,mult..] $ start s-    spansFromBoundaries e bdrys+    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@@ -267,7 +312,7 @@                    ])      , testCase "match dayOfWeek" $ do-        let dayofweek n = splitspan (nthdayofweekcontaining n) (\w -> (if w == 0 then id else applyN (n-1) nextday . applyN (fromInteger w) nextweek)) 1+        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@@ -281,5 +326,18 @@          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
@@ -6,10 +6,13 @@ {-# LANGUAGE RecordWildCards #-}  module Hledger.Data.Errors (+  decorateExcerpt,   makeAccountTagErrorExcerpt,+  makeCommodityTagErrorExcerpt,   makePriceDirectiveErrorExcerpt,   makeTransactionErrorExcerpt,   makePostingErrorExcerpt,+  makePostingErrorExcerptByIndex,   makePostingAccountErrorExcerpt,   makeBalanceAssertionErrorExcerpt,   transactionFindPostingIndex,@@ -28,8 +31,7 @@ import Data.Maybe import Safe (headMay) import Hledger.Data.Posting (isVirtual)-import Hledger.Data.Dates (showDate)-import Hledger.Data.Amount (showCommoditySymbol, showAmount)+import Hledger.Data.Amount (showPriceDirective)   -- | Given an account name and its account directive, and a problem tag within the latter:@@ -56,9 +58,34 @@       --   col2 = undefined -- col + T.length tagname - 1        showAccountDirective (a, AccountDeclarationInfo{..}) =-  "account " <> a-  <> (if not $ T.null adicomment then "    ; " <> adicomment else "")+  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@@ -89,14 +116,6 @@     merrcols = Nothing     excerpt = decorateExcerpt line merrcols $ showPriceDirective pd <> "\n" -showPriceDirective :: PriceDirective -> Text-showPriceDirective PriceDirective{..} = T.unwords [-   "P"-  ,showDate pddate-  ,showCommoditySymbol pdcommodity-  ,T.pack $ showAmount pdamount -  ]- -- | 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@@ -104,13 +123,18 @@ -- 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 = showTransaction t & textChomp & (<>"\n")+    txntxt = showTransactionForExcerpt t     merrcols = findtxnerrorcolumns t     ex = decorateTransactionErrorExcerpt tl merrcols txntxt @@ -150,15 +174,16 @@         errrelline = case mpindex of           Nothing -> 0           Just pindex ->-            commentExtraLines (tcomment t) + -            sum (map postingLines $ take pindex $ tpostings t)+            -- 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 = unPos tl + errrelline-        txntxt = showTransaction t & textChomp & (<>"\n")+        errabsline = clampToTransactionLines t $ unPos tl + errrelline+        txntxt = showTransactionForExcerpt t         merrcols = findpostingerrorcolumns p t txntxt         ex = decoratePostingErrorExcerpt errabsline errrelline merrcols txntxt @@ -180,6 +205,40 @@       ]     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.
Hledger/Data/Journal.hs view
@@ -20,10 +20,21 @@   ErroringJournalParser,   addPriceDirective,   addTransactionModifier,+  addJournalItem,+  addTransactionItem,   addPeriodicTransaction,+  addAssertDirective,   addTransaction,   journalDbg,   journalInferMarketPricesFromTransactions,+  journalApplyCommodityAliases,+  CommodityAliases,+  journalCommodityAliases,+  convertAliasAmount,+  commodityAliases,+  commodityRedeclare,+  commodityCombine,+  commoditiesAndAliases,   journalInferCommodityStyles,   journalStyleAmounts,   journalCommodityStyles,@@ -38,6 +49,16 @@   journalPostingsAddAccountTags,   journalPostingsKeepAccountTagsOnly,   journalPostingsAddCommodityTags,+  journalInferPostingsTransactedCost,+  journalCommodityUsesLots,+  journalAccountUsesNoLots,+  journalAccountLotsTags,+  accountUsesNoLotsWith,+  journalLotfulCommodities,+  journalCommodityLotsMethod,+  postingLotsMethod,+  parseReductionMethod,+  journalCheckLotsTagValues, -- * Filtering   filterJournalTransactions,   filterJournalPostings,@@ -83,6 +104,8 @@   journalCommodities,   journalCommoditiesFromPriceDirectives,   journalCommoditiesFromTransactions,+  journalBaseCurrency,+  journalBaseCurrencyCode,   journalDateSpan,   journalDateSpanBothDates,   journalStartDate,@@ -91,6 +114,7 @@   journalDescriptions,   journalFilePath,   journalFilePaths,+  journalAllFilePaths,   journalTransactionAt,   journalNextTransaction,   journalPrevTransaction,@@ -103,13 +127,19 @@   journalAddAccountTypes,   -- * Conversion accounts   defaultBaseConversionAccount,+  journalAccountForType,   journalBaseConversionAccount,   journalConversionAccounts,+  -- * Gain accounts+  defaultGainAccount,+  journalBaseGainAccount,+  journalGainAccounts,   -- * Misc   nulljournal,   journalConcat,   journalNumberTransactions,   journalNumberAndTieTransactions,+  journalTieTransactions,   journalUntieTransactions,   journalModifyTransactions,   journalApplyAliases,@@ -126,40 +156,43 @@ 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.List ((\\), find, sortBy, union, intercalate)+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, mapMaybe, maybeToList)+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 Safe (headMay, headDef, maximumMay, minimumMay, lastDef)-import Data.Time.Calendar (Day, addDays, fromGregorian, diffDays)+import Data.Time.Calendar (Day(..), addDays, diffDays, fromGregorian) import Data.Time.Clock.POSIX (POSIXTime)-import Data.Tree (Tree(..), flatten)+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-import System.FilePath (takeFileName)-import Data.Ord (comparing)-import Hledger.Data.Dates (nulldate)-import Data.List (sort)-import Data.Function ((&))--- import Data.Function ((&))   -- | A parser of text that runs in some monad, keeping a Journal as state.@@ -196,12 +229,14 @@   ("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-  ,"jincludefilestack: "         <> shw jincludefilestack+  ,"jparseincludefilestack: "    <> shw jparseincludefilestack   ,"jdeclaredpayees: "           <> shw jdeclaredpayees   ,"jdeclaredtags: "             <> shw jdeclaredtags   ,"jdeclaredaccounts: "         <> shw jdeclaredaccounts@@ -215,9 +250,11 @@   ,"jinferredmarketprices: "     <> shw jinferredmarketprices   ,"jtxnmodifiers: "             <> shw jtxnmodifiers   -- ,"jperiodictxns: "          <> shw jperiodictxns+  ,"jasserts: "                  <> shw jasserts   ,"jtxns: "                     <> shw jtxns-  ,"jfinalcommentlines: "        <> shw jfinalcommentlines+  ,"jitems: "                    <> shw (length jitems)   ,"jfiles: "                    <> shw jfiles+  ,"jauxfiles: "                 <> shw jauxfiles   ,"jlastreadtime: "             <> shw jlastreadtime   ]   -- ++ ["}"]@@ -247,20 +284,26 @@ journalConcat j1 j2 =   let     f1 = takeFileName $ journalFilePath j1-    f2 = maybe "(unknown)" takeFileName $ fmap fst $ headMay $ jincludefilestack j2  -- XXX more accurate than journalFilePath for some reason+    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-    ,jincludefilestack          = jincludefilestack 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@@ -284,7 +327,10 @@     ,jglobalcommoditystyles     = (<>) (jglobalcommoditystyles j1) (jglobalcommoditystyles j2)     --     -- ,jdeclaredcommodities           :: M.Map CommoditySymbol Commodity-    ,jdeclaredcommodities               = (<>) (jdeclaredcommodities j1) (jdeclaredcommodities j2)+    -- 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)@@ -297,9 +343,11 @@     ,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-    ,jfinalcommentlines         = jfinalcommentlines j2  -- XXX discards j1's ?+    ,jitems                     = jitems                     j1 <> jitems                     j2     ,jfiles                     = jfiles                     j1 <> jfiles                     j2+    ,jauxfiles                  = jauxfiles                  j1 <> jauxfiles                  j2     ,jlastreadtime              = max (jlastreadtime j1) (jlastreadtime j2)     } @@ -336,13 +384,19 @@ nulljournal :: Journal nulljournal = Journal {    jparsedefaultyear          = Nothing+  ,jparseapplyyears           = []   ,jparsedefaultcommodity     = Nothing   ,jparsedecimalmark          = Nothing   ,jparseparentaccounts       = []   ,jparsealiases              = []+  ,jparseoptaliases           = []   -- ,jparsetransactioncount     = 0   ,jparsetimeclockentries     = []-  ,jincludefilestack          = []+  ,jparseincludefilestack     = []+  ,jparsepos                  = Nothing+  ,jparseamountstyles         = S.empty+  ,jparsetexts                = S.empty+  ,jparsefastpathstats        = mempty   ,jdeclaredpayees            = []   ,jdeclaredtags              = []   ,jdeclaredaccounts          = []@@ -357,32 +411,68 @@   ,jinferredmarketprices      = []   ,jtxnmodifiers              = []   ,jperiodictxns              = []+  ,jasserts                   = []   ,jtxns                      = []-  ,jfinalcommentlines         = ""+  ,jitems                     = []   ,jfiles                     = []+  ,jauxfiles                  = []   ,jlastreadtime              = 0   }  journalFilePath :: Journal -> FilePath-journalFilePath = fst . mainfile+journalFilePath = jfpath . mainfile  journalFilePaths :: Journal -> [FilePath]-journalFilePaths = map fst . jfiles+journalFilePaths = map jfpath . jfiles -mainfile :: Journal -> (FilePath, Text)-mainfile = headDef ("(unknown)", "") . 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 = j { jtxns = t : jtxns j }+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 = j { jpricedirectives = h : jpricedirectives j }  -- XXX #999 keep sorted+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@@ -448,6 +538,43 @@ 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@@ -530,36 +657,38 @@  type DateWeightedSimilarityScore = Double type SimilarityScore = Double-type Age = Integer+type TimeDistance = Integer --- | Find up to N most similar and most recent transactions matching+-- | 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 age in days compared to the latest transaction date,+-- their distance in days from today, -- their description similarity score,--- and a heuristically date-weighted variant of this that favours more recent transactions.-journalTransactionsSimilarTo :: Journal -> Text -> Query -> SimilarityScore -> Int-  -> [(DateWeightedSimilarityScore, Age, SimilarityScore, Transaction)]-journalTransactionsSimilarTo Journal{jtxns} desc q similaritythreshold n =+-- 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 recency-weighted similarity:":) .+    unlines .+    ("up to 30 transactions above description similarity threshold "<>show similaritythreshold<>" ordered by proximity-weighted similarity:":) .     take 30 .-    map ( \(w,a,s,Transaction{..}) -> printf "weighted:%8.3f  age:%4d similarity:%5.3f  %s %s" w a s (show tdate) tdescription )) $+    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), age t, s, t)) $+  map (\(s,t) -> (weightedScore (s,t), timedistance t, s, t)) $   filter ((> similaritythreshold).fst)   [(compareDescriptions desc $ tdescription t, t) | t <- jtxns, q `matchesTransaction` t]   where-    latest = lastDef nulldate $ sort $ map tdate jtxns-    age = diffDays latest . tdate-    -- Combine similarity and recency heuristically. This gave decent results+    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 (age t) / 4+    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:@@ -644,42 +773,279 @@  -- | 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 = journalMapPostings addtags j-  where addtags p = p `postingAddTags` (journalInheritedAccountTags j $ paccount p)+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 = journalMapPostings addtags j+journalPostingsAddCommodityTags j+  | M.null taggedcommodities = j  -- no commodity tags declared, nothing to add+  | otherwise = journalMapPostings addtags j   where-    addtags p = p `postingAddTags` concatMap (journalCommodityTags j) (postingCommodities p)+    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 --- | 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)+-- | 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)} --- | The account name to use for conversion postings generated by --infer-equity.--- This is the first account declared with type V/Conversion,--- or otherwise the defaultBaseConversionAccount (equity:conversion).+    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 = headDef defaultBaseConversionAccount . journalConversionAccounts+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. @@ -688,12 +1054,16 @@  -- | Keep only transactions matching the query expression. filterJournalTransactions :: Query -> Journal -> Journal-filterJournalTransactions q j@Journal{jtxns} = j{jtxns=filter (matchesTransactionExtra (journalAccountType j) q) jtxns}+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} = j{jtxns=map (filterTransactionPostingsExtra (journalAccountType j) q) ts}+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.@@ -704,7 +1074,9 @@ -- remove any postings with all amounts removed. -- This can leave unbalanced transactions. filterJournalAmounts :: Query -> Journal -> Journal-filterJournalAmounts q j@Journal{jtxns=ts} = j{jtxns=map (filterTransactionAmounts q) ts}+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.@@ -879,8 +1251,10 @@   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     } @@ -889,7 +1263,14 @@ journalSetLastReadTime t j = j{ jlastreadtime = t }  -journalNumberAndTieTransactions = journalTieTransactions . journalNumberTransactions+-- | 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@@ -912,24 +1293,51 @@ -- 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+  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 amounts.+-- | 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 journalapplystyles . journalInferCommodityStyles+journalStyleAmounts = fmap applystyles . journalInferCommodityStyles   where-    journalapplystyles j@Journal{jpricedirectives=pds} =-      journalMapPostings (styleAmounts styles) j{jpricedirectives=map fixpricedirective pds}-      where-        styles = journalCommodityStylesWith NoRounding j  -- defer rounding, in case of print --round=none-        fixpricedirective pd@PriceDirective{pdamount=a} = pd{pdamount=styleAmounts styles a}+    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, @@ -940,12 +1348,23 @@ journalCommodityStyles :: Journal -> M.Map CommoditySymbol AmountStyle journalCommodityStyles j =   -- XXX could be some redundancy here, cf journalStyleInfluencingAmounts-  globalstyles <> declaredstyles <> defaultcommoditystyle <> inferredstyles+  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.@@ -954,12 +1373,31 @@  -- | 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 =-  case commodityStylesFromAmounts $ journalStyleInfluencingAmounts False j of-    Left e   -> Left e-    Right cs -> Right j{jinferredcommoditystyles = dbg7 "journalInferCommodityStyles" cs}+  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@@ -993,6 +1431,156 @@        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}@@ -1003,10 +1591,12 @@ -- 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 = do-  let conversionaccts = journalConversionAccounts j-  ts <- mapM (transactionTagCostsAndEquityAndMaybeInferCosts verbosetags addcosts conversionaccts) $ jtxns j-  return j{jtxns=ts}+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.@@ -1154,8 +1744,10 @@  -- | 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 = t{tpostings = map (postingPivot fieldortagname) . tpostings $ t}+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.@@ -1179,7 +1771,7 @@   | 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 == "acct"        = paccount p+  | 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@@ -1190,6 +1782,7 @@   | 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   = "" 
Hledger/Data/JournalChecks.hs view
@@ -9,9 +9,12 @@  module Hledger.Data.JournalChecks (   journalStrictChecks,+  journalCheckAsserts,   journalCheckAccounts,   journalCheckBalanceAssertions,   journalCheckCommodities,+  journalUndeclaredCommodities,+  journalCheckLots,   journalCheckPayees,   journalCheckPairedConversionPostings,   journalCheckRecentAssertions,@@ -23,25 +26,29 @@  import Data.Char (isSpace) import Data.List.Extra+import Data.Map qualified as M import Data.Maybe-import Data.Map.Strict qualified as M+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 (isVirtual, postingDate, transactionAllTags, conversionPostingTagName, costPostingTagName, postingAsLines, generatedPostingTagName, generatedTransactionTagName, modifiedTransactionTagName)+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, missingamt, oneLineFmt, showMixedAmountWith)+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.@@ -54,29 +61,84 @@  -- | 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}-      | a `elem` journalAccountNamesDeclared j = Right ()+      | 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."-          ,"Consider adding an account directive. Examples:"-          ,""-          ,"account %s"-          ]) f l ex a a+          ]) 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 ()@@ -84,7 +146,8 @@   mapM_ checkPriceDirectiveCommodities $ jpricedirectives j   mapM_ checkPostingCommodities $ journalPostings j   where-    firstUndeclaredOf comms = find (`M.notMember` jdeclaredcommodities j) comms+    declared = commoditiesAndAliases j+    firstUndeclaredOf = find (`S.notMember` declared)      errmsg = unlines [         "%s:%d:"@@ -97,34 +160,19 @@       ,"commodity 1.000,00 %s"       ] -    checkPriceDirectiveCommodities pd@PriceDirective{pdcommodity=c, pdamount=amt} =-      case firstUndeclaredOf [c, acommodity amt] of+    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 firstundeclaredcomm p of-        Nothing                    -> Right ()-        Just (comm, _inpostingamt) -> Left $ printf errmsg f l ex (show comm) comm comm+      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-        -- Find the first undeclared commodity symbol in this posting's amount or balance assertion amount, if any.-        -- and whether it was in the posting amount.-        -- XXX The latter is currently unused, could be used to refine the error highlighting ?-        firstundeclaredcomm :: Posting -> Maybe (CommoditySymbol, Bool)-        firstundeclaredcomm Posting{pamount=amt,pbalanceassertion} =-          case (firstUndeclaredOf postingcomms, firstUndeclaredOf assertioncomms) of-            (Just c, _) -> Just (c, True)-            (_, Just c) -> Just (c, False)-            _           -> Nothing-          where-            assertioncomms = [acommodity a | Just a <- [baamount <$> pbalanceassertion]]-            postingcomms = map acommodity $ filter (not . isIgnorable) $ amountsRaw amt-              where-                isIgnorable a = a==missingamt || (amountIsZero a && T.null (acommodity a))  -- #1767-         -- 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.@@ -162,8 +210,9 @@ journalCheckPayees :: Journal -> Either String () journalCheckPayees j = mapM_ checkpayee (jtxns j)   where+    declaredpayees = S.fromList $ map fst $ jdeclaredpayees j     checkpayee t-      | payee `elem` journalPayeesDeclared j = Right ()+      | payee `S.member` declaredpayees = Right ()       | otherwise = Left $         printf (unlines [            "%s:%d:"@@ -185,23 +234,30 @@             col  = T.length (showTransactionLineFirstPart t') + 2             col2 = col + T.length (transactionPayee t') - 1 --- | Check that all the journal's tags (on accounts, transactions, postings..)+-- | 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 `elem` declaredtags = Right ()+          | 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 `elem` declaredtags = Right ()+          | tagname `S.member` declaredtags = Right ()           | otherwise = Left $ printf msg f l ex (show tagname) tagname             where               (f,l,_mcols,ex) = makeTransactionErrorExcerpt txn finderrcols@@ -212,7 +268,7 @@                     -- where                     --   col  = T.length (showTransactionLineFirstPart txn') + 2                     --   col2 = col + T.length tagname - 1-    declaredtags = journalTagsDeclared j ++ builtinTags+    declaredtags = S.fromList $ map fst (jdeclaredtags j) ++ builtinTags     msg = (unlines [       "%s:%d:"       ,"%s"@@ -229,6 +285,8 @@    "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@@ -243,6 +301,10 @@       ,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.@@ -316,10 +378,14 @@     (showposting firsterrorp)     where       showposting p =-        headDef "" $ first3 $ postingAsLines False True acctw amtw p{pcomment=""}+        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-          amtw  = length $ showMixedAmountWith oneLineFmt $ pamount 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 ()@@ -330,3 +396,10 @@ --       (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
@@ -5,10 +5,12 @@  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)@@ -18,7 +20,10 @@   let     -- we check date ordering within each file, not across files     -- note, relying on txns always being sorted by file here-    txnsbyfile = groupBy (\t1 t2 -> transactionFile t1 == transactionFile t2) $ jtxns j+    -- 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@@ -32,8 +37,8 @@         where           (_,_,_,ex1) = makeTransactionErrorExcerpt tprev (const Nothing)           (f,l,_,ex2) = makeTransactionErrorExcerpt t finderrcols-          -- separate the two excerpts by a space-beginning line to help flycheck-hledger parse them-          ex = T.unlines [textChomp ex1, T.pack " ", textChomp ex2]+          -- 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)     ) 
Hledger/Data/JournalChecks/Uniqueleafnames.hs view
@@ -41,8 +41,8 @@             -- t = fromMaybe nulltransaction ptransaction  -- XXX sloppy             (_,_,_,ex1) = makePostingErrorExcerpt p (\_ _ _ -> Nothing)             (f,l,_,ex2) = makePostingErrorExcerpt p2 finderrcols-            -- separate the two excerpts by a space-beginning line to help flycheck-hledger parse them-            ex = T.unlines [textChomp ex1, T.pack " ...", textChomp ex2]+            -- 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'
Hledger/Data/Json.hs view
@@ -42,7 +42,7 @@   toJSON = toJSON . unPos   toEncoding = toEncoding . unPos --- https://github.com/simonmichael/hledger/issues/1195+-- 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).@@ -107,7 +107,7 @@ instance ToJSON BalanceAssertion instance ToJSON AmountCost instance ToJSON MarketPrice-instance ToJSON PostingType+instance ToJSON PostingRealness  instance ToJSON Posting where   toJSON = object . postingKV@@ -127,7 +127,7 @@     , "paccount"          .= paccount     , "pamount"           .= pamount     , "pcomment"          .= pcomment-    , "ptype"             .= ptype+    , "preal"             .= preal     , "ptags"             .= ptags     , "pbalanceassertion" .= pbalanceassertion     -- To avoid a cycle, show just the parent transaction's index number@@ -155,8 +155,41 @@ instance ToJSON Commodity instance ToJSON TimeclockCode instance ToJSON TimeclockEntry-instance ToJSON Journal +-- 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@@ -219,7 +252,7 @@ instance FromJSON BalanceAssertion instance FromJSON AmountCost instance FromJSON MarketPrice-instance FromJSON PostingType+instance FromJSON PostingRealness instance FromJSON Posting instance FromJSON Transaction instance FromJSON AccountDeclarationInfo
Hledger/Data/Ledger.hs view
@@ -60,7 +60,7 @@ ledgerFromJournal q j = nullledger{ljournal=j'', laccounts=as}   where     (q',depthq)  = (filterQuery (not . queryIsDepth) q, filterQuery queryIsDepth q)-    j'  = filterJournalAmounts (filterQuery queryIsSym q) $ -- remove amount parts which the query's sym: terms would exclude+    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'
+ 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/Period.hs view
@@ -16,6 +16,7 @@   ,periodTextWidth   ,showPeriod   ,showPeriodAbbrev+  ,showPeriodAbbrevWith   ,periodStart   ,periodEnd   ,periodNext@@ -199,11 +200,15 @@ -- >>> showPeriodAbbrev (WeekPeriod (fromGregorian 2024 12 30)) -- "W01" showPeriodAbbrev :: Period -> Text-showPeriodAbbrev (MonthPeriod _ m)                                              -- Jan+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 defaultTimeLocale-showPeriodAbbrev (WeekPeriod b) = T.pack $ formatTime defaultTimeLocale "W%V" b -- Www-showPeriodAbbrev p = showPeriod p+  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
Hledger/Data/PeriodicTransaction.hs view
@@ -7,6 +7,7 @@ -} module Hledger.Data.PeriodicTransaction (     runPeriodicTransaction+  , periodicTransactionDates   , checkPeriodicTransactionStartDate ) where@@ -15,6 +16,7 @@ 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@@ -85,91 +87,91 @@ -- >>> _ptgen "monthly from 2017/1 to 2017/4" -- 2017-01-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/4---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-02-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/4---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-03-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/4---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2017-02-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/5---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-03-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/5---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-04-01 --     ; generated-transaction: ~ monthly from 2017/1 to 2017/5---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2017-03-02 --     ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2017-02-28 --     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-03-30 --     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-04-30 --     ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2017-02-09 --     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- 2017-03-09 --     ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2018-11-29 --     ; generated-transaction: ~ every nov 29th from 2017 to 2019---     a           $1.00+--     a                                             $1.00 -- <BLANKLINE> -- -- >>> _ptgen "2017/1" -- 2017-01-01 --     ; generated-transaction: ~ 2017/1---     a           $1.00+--     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))@@ -180,26 +182,26 @@ -- >>> _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+--     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+--     a                                             $1.00 -- <BLANKLINE> -- 2018-01-04 --     ; generated-transaction: ~ every 3 days from 2018---     a           $1.00+--     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+--     a                                             $1.00 -- <BLANKLINE>  runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]-runPeriodicTransaction verbosetags PeriodicTransaction{..} requestedspan =-    [ t{tdate=d} | (d, _) <- maybe [] dayPartitionToList alltxnspans, spanContainsDate requestedspan d ]+runPeriodicTransaction verbosetags pt@PeriodicTransaction{..} requestedspan =+    [ t{tdate=d} | d <- periodicTransactionDates pt requestedspan ]   where     t = nulltransaction{            tsourcepos   = ptsourcepos@@ -212,8 +214,16 @@           }         & 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 = splitSpan adjust ptinterval span'+    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
Hledger/Data/Posting.hs view
@@ -33,6 +33,7 @@   isEmptyPosting,   hasBalanceAssignment,   hasAmount,+  isExplicitAmount,   postingAllTags,   transactionAllTags,   relatedPostings,@@ -42,6 +43,7 @@   postingStyleAmounts,   postingAddTags,   postingAddHiddenAndMaybeVisibleTag,+  postingRemoveHiddenAndVisibleTag,   -- * date operations   postingDate,   postingDate2,@@ -53,11 +55,17 @@   commentAddTag,   commentAddTagUnspaced,   commentAddTagNextLine,+  commentPrependTag,   generatedTransactionTagName,   modifiedTransactionTagName,   generatedPostingTagName,+  feesplitPostingTagName,+  lotsplitPostingTagName,+  lotParentAssertionTagName,+  postingHasTag,   costPostingTagName,   conversionPostingTagName,+  imbalancePostingTagName,    -- * arithmetic   sumPostings,@@ -68,15 +76,25 @@   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@@ -88,7 +106,7 @@ import Data.Function ((&)) import Data.Map qualified as M import Data.Maybe (fromMaybe, isJust, mapMaybe)-import Data.List (sort, union)+import Data.List (nub, sort, union) #if !MIN_VERSION_base(4,20,0) import Data.List (foldl') #endif@@ -114,13 +132,21 @@ -- 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, generatedPostingTagName :: TagName+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} @@ -151,7 +177,7 @@                 ,paccount=""                 ,pamount=nullmixedamt                 ,pcomment=""-                ,ptype=RegularPosting+                ,preal=RealPosting                 ,ptags=[]                 ,pbalanceassertion=Nothing                 ,ptransaction=Nothing@@ -167,7 +193,7 @@  -- | Make a virtual (unbalanced) posting to an account. vpost :: AccountName -> Amount -> Posting-vpost acc amt = (post acc amt){ptype=VirtualPosting}+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@@ -175,7 +201,7 @@  -- | 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){ptype=VirtualPosting, pbalanceassertion=ass}+vpost' acc amt ass = (post' acc amt ass){preal=VirtualPosting, pbalanceassertion=ass}  nullassertion :: BalanceAssertion nullassertion = BalanceAssertion@@ -201,32 +227,168 @@ balassertTotInc :: Amount -> Maybe BalanceAssertion balassertTotInc amt = Just $ nullassertion{baamount=amt, batotal=True, bainclusive=True} --- | Render a balance assertion, as the =[=][*] symbol and expected amount.-showBalanceAssertion :: BalanceAssertion -> WideBuilder-showBalanceAssertion ba =-    singleton '=' <> eq <> ast <> singleton ' ' <> showAmountB def{displayZeroCommodity=True, displayForceDecimalMark=True} (baamount ba)+-- | 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 False [p]+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 = first3 $ postingAsLines False False maxacctwidth maxamtwidth p+showPostingLines p = fst $ postingAsLines defaultFmt False False maxstatuswidth maxacctwidth dc p   where-    linesWithWidths = map (postingAsLines False False maxacctwidth maxamtwidth) . maybe [p] tpostings $ ptransaction p-    maxacctwidth = maximumBound 0 $ map second3 linesWithWidths-    maxamtwidth  = maximumBound 0 $ map third3 linesWithWidths+    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.+-- | 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).@@ -238,21 +400,113 @@ -- 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. ----- Posting amounts will be aligned with each other, starting about 4 columns--- beyond the widest account name (see postingAsLines for details).--- The postings will appear balanced (amounts summing to zero).--- Amounts' display precisions, which may have been limited by commodity directives,--- will be increased if necessary to ensure this.+-- Note: a few fields of the caller's @AmountFormat@ are overridden internally;+-- see 'postingAsLines' for details. ---postingsAsLines :: Bool -> [Posting] -> [Text]-postingsAsLines onelineamounts ps = concatMap first3 linesWithWidths+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-    linesWithWidths = map (postingAsLines False onelineamounts maxacctwidth maxamtwidth) ps+    -- 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 widths calculated for the account and amount fields.+-- 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.@@ -266,18 +520,49 @@ -- If an amount is zero, any commodity symbol attached to it is shown -- (and the corresponding commodity display style is used). ----- By default, 4 spaces (2 if there's a status flag) are shown between--- account name and start of amount area, which is typically 12 chars wide--- and contains a right-aligned amount (so 10-12 visible spaces between--- account name and amount is typical).--- When given a list of postings to be aligned with, the whitespace will be--- increased if needed to match the posting with the longest account name.--- This is used to align the amounts of a transaction's postings.+-- Three target columns are supplied via 'AmountCols': ---postingAsLines :: Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)-postingAsLines elideamount onelineamounts acctwidth amtwidth p =-    (concatMap (++ newlinecomments) postingblocks, thisacctwidth, thisamtwidth)+-- * @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@@ -286,42 +571,86 @@     postingblocks = [map T.stripEnd . T.lines . TL.toStrict $                        render [ textCell BottomLeft statusandaccount                               , textCell BottomLeft "  "-                              , Cell BottomLeft [pad amt]-                              , Cell BottomLeft [assertion]+                              , Cell BottomLeft [padLeft (decimalcol - acctwidth - statuswidth - 7 - lw) amt]+                              , Cell BottomLeft [asn]                               , textCell BottomLeft samelinecomment                               ]-                    | (amt,assertion) <- shownAmountsAssertions]+                    | (amt, lw, asn) <- amountAssertionRows]     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 (ptype p') (paccount p')+    -- 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) <> " " -    -- 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   = showMixedAmountLinesB displayopts $ pamount p-        where displayopts = defaultFmt{-          displayZeroCommodity=True, displayForceDecimalMark=True, displayOneLine=onelineamounts-          }-    thisamtwidth = maximumBound 0 $ map wbWidth shownAmounts+    -- 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+      } -    -- when there is a balance assertion, show it only on the last posting line-    shownAmountsAssertions = zip shownAmounts shownAssertions+    -- 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 shownAmounts - 1) mempty ++ [assertion]-          where-            assertion = maybe mempty ((WideBuilder (TB.singleton ' ') 1 <>).showBalanceAssertion) $ pbalanceassertion p+        shownAssertions = replicate (length amountRows - 1) mempty ++ [assertionWB] -    -- 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+    -- 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) =@@ -329,11 +658,11 @@                                               c:cs -> (c,cs)  -- | 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 -> Text+-- appropriately bracketed/parenthesised for the given posting realness.+showAccountName :: Maybe Int -> PostingRealness -> AccountName -> Text showAccountName w = fmt   where-    fmt RegularPosting         = maybe id T.take w+    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 @@ -359,17 +688,26 @@   isReal :: Posting -> Bool-isReal p = ptype p == RegularPosting+isReal p = preal p == RealPosting  isVirtual :: Posting -> Bool-isVirtual p = ptype p == VirtualPosting+isVirtual p = preal p == VirtualPosting  isBalancedVirtual :: Posting -> Bool-isBalancedVirtual p = ptype p == BalancedVirtualPosting+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) @@ -470,14 +808,32 @@ -- | 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 -> HiddenTag -> Posting -> Posting-postingAddHiddenAndMaybeVisibleTag verbosetags ht p@Posting{pcomment=c, ptags} =+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 c `commentAddTag` vt else c}+  {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.@@ -485,49 +841,72 @@ 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.+-- | 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+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 mixedAmountCost p+  | otherwise = Just $ postingTransformAmount tocost p   where     nocosts = (not . any (isJust . acost) . amountsRaw) $ pamount p --- | Generate equity conversion postings corresponding to a 'Posting''s cost(s)--- (one pair of conversion postings per cost), wherever they don't already exist.+-- | 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-  -- this posting has no costs-  | null costs = [p]-  -- this posting is already tagged as having associated conversion postings-  | costPostingTagName `elem` map fst (ptags p) = [p]-  -- tag the posting, and for each of its costs, add an equivalent pair of conversion postings after it-  | otherwise =-    postingAddHiddenAndMaybeVisibleTag verbosetags (costPostingTagName,"") p :-    concatMap makeConversionPostings costs+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-    costs = filter (isJust . acost) . amountsRaw $ pamount p-    makeConversionPostings amt = case acost amt of-      Nothing -> []-      Just _  -> [ convp{ paccount = accountPrefix <> amtCommodity-                        , pamount = mixedAmount . negate $ amountStripCost amt-                        }-                 , convp{ paccount = accountPrefix <> costCommodity-                        , pamount = mixedAmount cost-                        }-                 ]+    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-        cost = amountCost amt-        amtCommodity  = commodity amt-        costCommodity = commodity cost-        convp = nullposting{pdate=pdate p, pdate2=pdate2 p, pstatus=pstatus p, ptransaction=ptransaction p}-          & postingAddHiddenAndMaybeVisibleTag verbosetags (conversionPostingTagName,"")-          & postingAddHiddenAndMaybeVisibleTag verbosetags (generatedPostingTagName, "")+        as = filter ((== pair) . commodityPair) costfulamounts         accountPrefix = mconcat [ equityAcct, ":", T.intercalate "-" $ sort [amtCommodity, costCommodity], ":"]-        -- Take the commodity of an amount and collapse consecutive spaces to a single space-        commodity = T.unwords . filter (not . T.null) . T.words . acommodity+    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.@@ -558,6 +937,16 @@     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)@@ -579,7 +968,7 @@ tests_Posting = testGroup "Posting" [    testCase "accountNamePostingType" $ do-    accountNamePostingType "a" @?= RegularPosting+    accountNamePostingType "a" @?= RealPosting     accountNamePostingType "(a)" @?= VirtualPosting     accountNamePostingType "[a]" @?= BalancedVirtualPosting 
Hledger/Data/Timeclock.hs view
@@ -16,7 +16,7 @@ ) where -import Data.List (partition, sortBy, uncons)+import Data.List (intercalate, partition, sortBy, sortOn, uncons) import Data.Maybe (fromMaybe) import Data.Text qualified as T import Data.Time.Calendar (addDays)@@ -86,7 +86,8 @@     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}}+    -- 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@@ -96,7 +97,8 @@   where     (itime,otime) = (tldatetime i,tldatetime o)     (idate,odate) = (localDay itime,localDay otime)-    o' = o{tldatetime=itime{localDay=idate, localTimeOfDay=TimeOfDay 23 59 59}}+    -- 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 -} @@ -142,22 +144,17 @@         (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 = idate, localTimeOfDay = TimeOfDay 23 59 59}}+        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' $ T.unpack $ makeTimeClockErrorExcerpt entry $ T.unlines $ [-            ""-            ,"overlaps with session beginning at:"-            ,""-            ]-            <> map (flip makeTimeClockErrorExcerpt "") activesinthisacct-            <> [ "Overlapping sessions with the same account name are not supported." ]-            -- XXX better to show full session(s)-            -- <> map (T.pack . show) (filter ((`elem` activesinthisacct).in') sessions)+          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.@@ -194,16 +191,26 @@     l = show $ unPos $ sourceLine $ tlsourcepos actual     c = unPos $ sourceColumn $ tlsourcepos actual -makeTimeClockErrorExcerpt :: TimeclockEntry -> T.Text -> T.Text-makeTimeClockErrorExcerpt e@TimeclockEntry{tlsourcepos=pos} msg = T.unlines [-  T.pack (sourcePosPretty pos) <> ":"-  ,l <> " | " <> T.pack (show e)-  -- ,T.replicate (T.length l) " " <> " |" -- <> T.replicate c " " <> "^")-  ] <> msg+-- | 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-    l = T.pack $ show $ unPos $ sourceLine $ tlsourcepos e-    -- c = unPos $ sourceColumn $ tlsourcepos e+    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.@@ -245,24 +252,22 @@       itime    = tldatetime i       otime    = tldatetime o       itod     = localTimeOfDay itime-      otod     = localTimeOfDay otime+      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. Unusually, we also round the internal Decimal value,-      -- since otherwise it will often have large recurring decimal parts which (since 1.21)-      -- print would display all 255 digits of. timeclock amounts have one second resolution,-      -- so two decimal places is precise enough (#1527).-      amt = case mixedAmount $ setAmountInternalPrecision 2 $ hrs hours of+      -- 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' $ printf-          "%s%s:\nThis clockout is earlier than the clockin."-          (makeTimeClockErrorExcerpt i "")-          (makeTimeClockErrorExcerpt o "")-      ps = [posting{paccount=acctname, pamount=amt, ptype=VirtualPosting, ptransaction=Just t}]+        _ -> 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
Hledger/Data/Transaction.hs view
@@ -53,7 +53,9 @@   -- payeeAndNoteFromDescription   -- * rendering , showTransaction+, showTransactionWithLayout , showTransactionOneLineAmounts+, showTransactionOneLine , showTransactionLineFirstPart , transactionFile   -- * transaction errors@@ -65,7 +67,7 @@ import Control.Monad.Trans.State (StateT(..), evalStateT) import Data.Bifunctor (first, second) import Data.Foldable (foldlM)-import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe) import Data.Semigroup (Endo(..)) import Data.Text (Text) import Data.Map qualified as M@@ -80,25 +82,26 @@ import Hledger.Data.Posting import Hledger.Data.Amount import Hledger.Data.Valuation-import Data.Decimal (normalizeDecimal, decimalPlaces)+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. See #2402.+-- | 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 =-    TBPOld+    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.-    -- Small unbalanced remainders can be hidden, and in accounts that are never reconciled, can accumulate over time.-  | TBPExact-    -- ^ Simpler, more robust behaviour, as in Ledger: use precision inferred from the transaction.+    -- 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.-    -- Every imbalance in a transaction is visibly accounted for in that transaction's journal entry.+    -- Imbalances smaller than the entry's precision are still tolerated, and can accumulate.    deriving (Bounded, Enum, Eq, Ord, Read, Show) @@ -170,29 +173,48 @@ (Normally does not happen with this function). -} showTransaction :: Transaction -> Text-showTransaction = TL.toStrict . TB.toLazyText . showTransactionHelper False+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+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*.-showTransactionHelper :: Bool -> Transaction -> TB.Builder-showTransactionHelper onelineamounts t =-      TB.fromText descriptionline <> newline+-- 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) (postingsAsLines onelineamounts $ tpostings t)+    <> foldMap ((<> newline) . TB.fromText) (postingsAsLinesWithLayout defaultFmt onelineamounts layout $ 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)+    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@@ -260,10 +282,35 @@ 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.+-- 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=concatMap (postingAddInferredEquityPostings verbosetags equityAcct) $ tpostings 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) @@ -301,7 +348,10 @@ -- 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 = first (annotateErrorWithTransaction t . T.unpack) $ do+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 @@ -368,8 +418,8 @@          -- 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 verbosetags (costPostingTagName,"")        -- if it's the specified posting number, replace it with the costful posting, and tag it-                 | n == n1 || n == n2 -> p     & postingAddHiddenAndMaybeVisibleTag verbosetags (conversionPostingTagName,"")  -- if it's one of the equity conversion postings, tag it+          (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@@ -406,10 +456,23 @@     costfulPostingIfMatchesBothAmounts a1 a2 costfulp = do         a@Amount{acost=Just _} <- postingSingleAmount costfulp         if-           | dbgamtmatch 1 a1 a (amountsMatch (-a1) a)  &&  dbgcostmatch 2 a2 a (amountsMatch a2 (amountCost a)) -> Just costfulp-           | dbgamtmatch 2 a2 a (amountsMatch (-a2) a)  &&  dbgcostmatch 1 a1 a (amountsMatch a1 (amountCost a)) -> Just costfulp+           | 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<>" ?")  @@ -445,7 +508,7 @@     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 False xs+    annotateWithPostings xs str = T.unlines $ str : postingsAsLines defaultFmt False xs  dbgShowAmountPrecision a =   case asprecision $ astyle a of@@ -502,11 +565,14 @@ transactionAmounts :: Transaction -> [MixedAmount] transactionAmounts = map pamount . tpostings --- | Get the canonical amount styles inferred from this transaction's amounts.+-- | 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) . tpostings+  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.@@ -535,7 +601,7 @@   testGroup "Transaction" [        testGroup "showPostingLines" [-          testCase "null posting" $ showPostingLines nullposting @?= ["                   0"]+          testCase "null posting" $ showPostingLines nullposting @?= ["                                                   0"]         , testCase "non-null posting" $            let p =                 posting@@ -543,14 +609,14 @@                   , paccount = "a"                   , pamount = mixed [usd 1, hrs 2]                   , pcomment = "pcomment1\npcomment2\n  tag3: val3  \n"-                  , ptype = RegularPosting+                  , preal = RealPosting                   , ptags = [("ptag1", "val1"), ("ptag2", "val2")]                   }            in showPostingLines p @?=-              [ "    * a         $1.00  ; pcomment1"+              [ "    * a                                           $1.00  ; pcomment1"               , "    ; pcomment2"               , "    ;   tag3: val3  "-              , "    * a         2.00h  ; pcomment1"+              , "    * a                                            2.00h  ; pcomment1"               , "    ; pcomment2"               , "    ;   tag3: val3  "               ]@@ -572,28 +638,28 @@         -- 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 False (tpostings nulltransaction) @?= []-            , testCase "implicit-amount" $ postingsAsLines False (tpostings timp) @?=-                  [ "    a           $1.00"+              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 False (tpostings texp) @?=-                  [ "    a           $1.00"-                  , "    b          $-1.00"+            , testCase "explicit-amounts" $ postingsAsLines defaultFmt False (tpostings texp) @?=+                  [ "    a                                             $1.00"+                  , "    b                                            $-1.00"                   ]-            , testCase "one-explicit-amount" $ postingsAsLines False (tpostings texp1) @?=-                  [ "    (a)           $1.00"+            , testCase "one-explicit-amount" $ postingsAsLines defaultFmt False (tpostings texp1) @?=+                  [ "    (a)                                           $1.00"                   ]-            , testCase "explicit-amounts-two-commodities" $ postingsAsLines False (tpostings texp2) @?=-                  [ "    a             $1.00"-                  , "    b    -1.00h @ $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 False (tpostings texp2b) @?=-                  [ "    a           $1.00"-                  , "    b          -1.00h"+            , testCase "explicit-amounts-not-explicitly-balanced" $ postingsAsLines defaultFmt False (tpostings texp2b) @?=+                  [ "    a                                             $1.00"+                  , "    b                                             -1.00h"                   ]-            , testCase "implicit-amount-not-last" $ postingsAsLines False (tpostings t3) @?=-                  ["    a           $1.00", "    b", "    c          $-1.00"]+            , 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"]@@ -617,7 +683,7 @@                       , paccount = "a"                       , pamount = mixed [usd 1, hrs 2]                       , pcomment = "\npcomment2\n"-                      , ptype = RegularPosting+                      , preal = RealPosting                       , ptags = [("ptag1", "val1"), ("ptag2", "val2")]                       }                   ]@@ -625,9 +691,9 @@           T.unlines             [ "2012-05-14=2012-05-15 (code) desc  ; tcomment1"             , "    ; tcomment2"-            , "    * a         $1.00"+            , "    * a                                           $1.00"             , "    ; pcomment2"-            , "    * a         2.00h"+            , "    * a                                            2.00h"             , "    ; pcomment2"             , ""             ]@@ -650,8 +716,8 @@             in showTransaction t) @?=           (T.unlines              [ "2007-01-28 coopportunity"-             , "    expenses:food:groceries          $47.18"-             , "    assets:checking                 $-47.18"+             , "    expenses:food:groceries                      $47.18"+             , "    assets:checking                             $-47.18"              , ""              ])         , testCase "show an unbalanced transaction, should not elide" $@@ -673,8 +739,8 @@                 ])) @?=           (T.unlines              [ "2007-01-28 coopportunity"-             , "    expenses:food:groceries          $47.18"-             , "    assets:checking                 $-47.19"+             , "    expenses:food:groceries                      $47.18"+             , "    assets:checking                             $-47.19"              , ""              ])         , testCase "show a transaction with one posting and a missing amount" $@@ -710,6 +776,6 @@                 [ 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", ""])+          (T.unlines ["2010-01-01 x", "    a                                              1 @ $2", "    b", ""])         ]     ]
Hledger/Data/TransactionModifier.hs view
@@ -25,7 +25,7 @@ import Hledger.Data.Dates import Hledger.Data.Transaction (txnTieKnot, transactionAddHiddenAndMaybeVisibleTag) import Hledger.Query (Query, filterQuery, matchesAmount, matchesPostingExtra,-                      parseQuery, queryIsAmt, queryIsSym, simplifyQuery)+                      parseQuery, queryIsAmt, queryIsCur, simplifyQuery) import Hledger.Data.Posting (commentJoin, commentAddTag, postingAddTags, modifiedTransactionTagName) import Hledger.Utils (dbg6, wrap) @@ -71,17 +71,17 @@ -- >>> 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: =+--     ping                                          $1.00+--     pong                                          $2.00  ; generated-posting: = -- <BLANKLINE> -- >>> test $ TransactionModifier "miss" ["pong" `tmpost` usd 2] -- 0000-01-01---     ping           $1.00+--     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+--     ping                                          $1.00+--     pong                                          $3.00  ; generated-posting: = ping -- <BLANKLINE> -- transactionModifierToFunction :: (AccountName -> Maybe AccountType)@@ -119,7 +119,7 @@   where     pr = tmprPosting tmpr     qry = "= " <> querytxt-    symq = filterQuery (liftA2 (||) queryIsSym queryIsAmt) query+    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
Hledger/Data/Types.hs view
@@ -46,6 +46,7 @@ --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)@@ -114,8 +115,6 @@ -- EFDay's Ord instance treats them like ordinary dates, ignoring exact/flexible. instance Ord EFDay where compare d1 d2 = compare (fromEFDay d1) (fromEFDay d2) --- instance Ord EFDay where compare = maCompare- fromEFDay :: EFDay -> Day fromEFDay (Exact d) = d fromEFDay (Flex  d) = d@@ -190,8 +189,9 @@   | 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 (used by hledger 2)-  deriving (Eq,Ord,Generic)+  | 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"@@ -203,6 +203,7 @@   show Conversion     = "V"   show Gain           = "G"   show UnrealisedGain = "U"+  show Imbalance      = "M"  isBalanceSheetAccountType :: AccountType -> Bool isBalanceSheetAccountType t = t `elem` [@@ -211,7 +212,8 @@   Equity,   Cash,   Conversion,-  UnrealisedGain+  UnrealisedGain,+  Imbalance   ]  isIncomeStatementAccountType :: AccountType -> Bool@@ -221,24 +223,6 @@   Gain   ] --- | 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 _              _              = False- -- not worth the trouble, letters defined in accountdirectivep for now --instance Read AccountType --  where@@ -329,20 +313,24 @@  -- | A style for displaying digit groups in the integer part of a -- floating point number. It consists of the character used to--- separate groups (comma or period, whichever is not used as decimal--- point), 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].+-- 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+  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.@@ -350,11 +338,31 @@ -- 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 {-  cbCost  :: !(Maybe Amount),    -- ^ nominal acquisition cost (per-unit)   cbDate  :: !(Maybe Day),       -- ^ nominal acquisition date-  cbLabel :: !(Maybe Text)       -- ^ a short label to ensure uniqueness, correct intra-day order, or memorability, if needed+  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"@@ -380,9 +388,52 @@   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) -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 @@ -403,39 +454,8 @@                         Just (TotalCost p) -> aquantity p                         _                   -> 0 --- | Stores the CommoditySymbol of the Amount, along with the CommoditySymbol of--- the cost, and its unit cost if being used.-data MixedAmountKey-  = MixedAmountKeyNoCost   !CommoditySymbol-  | MixedAmountKeyTotalCost !CommoditySymbol !CommoditySymbol-  | MixedAmountKeyUnitCost  !CommoditySymbol !CommoditySymbol !Quantity-  deriving (Eq,Generic,Show)---- | We don't auto-derive the Ord instance because it would give an undesired ordering.--- We want the keys to be sorted lexicographically:--- (1) By the primary commodity of the amount.--- (2) By the commodity of the cost, with no cost being first.--- (3) By the unit cost, from most negative to most positive, with total costs--- before unit costs.--- For example, we would like the ordering to give--- MixedAmountKeyNoCost "X" < MixedAmountKeyTotalCost "X" "Z" < MixedAmountKeyNoCost "Y"-instance Ord MixedAmountKey where-  compare = comparing commodity <> comparing pCommodity <> comparing pCost-    where-      commodity (MixedAmountKeyNoCost    c)     = c-      commodity (MixedAmountKeyTotalCost c _)   = c-      commodity (MixedAmountKeyUnitCost  c _ _) = c--      pCommodity (MixedAmountKeyNoCost    _)      = Nothing-      pCommodity (MixedAmountKeyTotalCost _ pc)   = Just pc-      pCommodity (MixedAmountKeyUnitCost  _ pc _) = Just pc--      pCost (MixedAmountKeyNoCost    _)     = Nothing-      pCost (MixedAmountKeyTotalCost _ _)   = Nothing-      pCost (MixedAmountKeyUnitCost  _ _ q) = Just q--data PostingType = RegularPosting | VirtualPosting | BalancedVirtualPosting-                   deriving (Eq,Show,Generic)+data PostingRealness = RealPosting | VirtualPosting | BalancedVirtualPosting+  deriving (Eq,Show,Generic)  type TagName = Text type TagValue = Text@@ -503,13 +523,13 @@     } 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+      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-      ptype             :: PostingType,+      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,@@ -537,7 +557,7 @@     ,"paccount="          ++ show paccount     ,"pamount="           ++ show pamount     ,"pcomment="          ++ show pcomment-    ,"ptype="             ++ show ptype+    ,"preal="             ++ show preal     ,"ptags="             ++ show ptags     ,"pbalanceassertion=" ++ show pbalanceassertion     ,"ptransaction="      ++ show (ptransaction $> "txn")@@ -610,6 +630,23 @@      ,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 {@@ -646,6 +683,33 @@  -- 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. --@@ -657,14 +721,24 @@ -- data Journal = Journal {   -- parsing-related state-   jparsedefaultyear        :: Maybe Year                             -- ^ the current default year, specified by the most recent Y directive (or current date)+   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, specified by alias directives (& options ?)+  ,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-  ,jincludefilestack        :: [(FilePath, FilePath)]                 -- ^ (absolute path, canonical path) of included files, most recent first+  ,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.@@ -680,18 +754,52 @@   ,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.-  ,jfinalcommentlines       :: Text                                   -- ^ any final trailing comments in the (main) journal file-  ,jfiles                   :: [(FilePath, Text)]                     -- ^ the file path and raw text of the main and-                                                                      --   any included journal files. The main file is first,+  ,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.-                                                                      --   TODO: FilePath is a sloppy type here, don't assume it's a-                                                                      --   real file; values like "" or "-" can be seen+  ,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@@ -824,21 +932,29 @@ 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 PostingType+instance NFData PostingRealness instance NFData PriceDirective instance NFData Side instance NFData Status
Hledger/Data/Valuation.hs view
@@ -17,9 +17,11 @@   ,ValuationType(..)   ,PriceOracle   ,journalPriceOracle+  ,journalAliasPriceDirectives   ,mixedAmountToCost   ,mixedAmountApplyValuation   ,mixedAmountValueAtDate+  ,amountValueAtDate   ,mixedAmountApplyGain   ,mixedAmountGainAtDate   ,marketPriceReverse@@ -55,10 +57,12 @@ ------------------------------------------------------------------------------ -- Types --- | Which operation to perform on conversion transactions.--- (There was also an "infer equity postings" operation, but that is now done +-- | 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+data ConversionOp = NoConversionOp | ToCost | ToTransactedCost   deriving (Show,Eq)  -- | What kind of value conversion should be done on amounts ?@@ -144,14 +148,21 @@   , piInferredDefault :: !DefaultValuationIndex -- ^ Index for inferred prices (fallback for default valuation)   } --- | Build all price indexes from declared and inferred market prices.+-- | 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] -> PriceIndexes-buildPriceIndexes declaredprices inferredprices = PriceIndexes-  { piForward = buildPriceIndex declaredprices inferredprices+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.@@ -177,19 +188,69 @@ -- 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 Journal{jpricedirectives, jinferredmarketprices} =+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-    indexes = buildPriceIndexes declaredprices inferredprices-    makepricegraph = memo $ makePriceGraph indexes+    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-    memo $ uncurry3 $ priceLookup makepricegraph+    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@@ -227,8 +288,9 @@  -- | 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 . amountCost-amountToCost _      NoConversionOp = id+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@@ -288,7 +350,7 @@   case priceoracle (d, acommodity a, mto) of     Nothing           -> a     Just (comm, rate) ->-      nullamt{acommodity=comm, aquantity=rate * aquantity a}+      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.@@ -307,13 +369,25 @@ -- 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` mixedAmountCost 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.@@ -324,7 +398,7 @@ -- 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` mixedAmountCost ma+  mixedAmountValueAtDate priceoracle styles mto d $ ma `maMinus` mixedAmountCostBasis ma  ------------------------------------------------------------------------------ -- Market price lookup@@ -406,12 +480,21 @@       ,p 2000 01 01 "E"  2 "D"       ,p 2001 01 01 "A" 11 "B"       ]-    makepricegraph = makePriceGraph (buildPriceIndexes ps1 [])+    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
Hledger/Query.hs view
@@ -24,10 +24,13 @@   parseQueryTerm,   parseAccountType,   parseDepthSpec,+  parseAmountQueryArg,   -- * modifying+  transformQuery,   simplifyQuery,   filterQuery,   filterQueryOrNotQuery,+  querySplitRowTerms,   matchesQuery,   -- * predicates   queryIsNull,@@ -39,12 +42,19 @@   queryIsDesc,   queryIsTag,   queryIsAcct,+  queryIsFind,   queryIsType,   queryIsDepth,+  queryIsFlatDepth,   queryIsReal,   queryIsAmt,-  queryIsSym,-  queryIsAmtOrSym,+  queryIsCur,+  queryIsAmtOrCur,+  queryIsChange,+  queryIsBalance,+  queryIsRowTerm,+  queryHasBalance,+  queryHasChange,   queryIsStartDateOnly,   queryIsTransactionRelated,   -- * accessors@@ -58,15 +68,17 @@   -- * matching things with queries   matchesTransaction,   matchesTransactionExtra,-  matchesDescription,-  matchesPayeeWIP,+  matchesPayee,   matchesPosting,   matchesPostingExtra,+  postingQueryForAccount,   matchesAccount,   matchesAccountExtra,   matchesMixedAmount,   matchesAmount,+  matchesRowAmounts,   matchesCommodity,+  matchesCommodityExtra,   matchesTag,   -- patternsMatchTags,   matchesPriceDirective,@@ -78,9 +90,11 @@ where  import Control.Applicative+import Control.Monad (guard) import Data.Default (Default(..))+import Data.Char (isDigit) import Data.Either (partitionEithers)-import Data.List (partition, intercalate)+import Data.List (partition) import Data.Maybe (fromMaybe, isJust, mapMaybe) import Data.Text (Text) import Data.Text qualified as T@@ -93,7 +107,8 @@ import Hledger.Utils hiding (words') import Hledger.Data.Types import Hledger.Data.AccountName-import Hledger.Data.Amount (amountsRaw, mixedAmount, nullamt, usd)+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@@ -118,14 +133,26 @@   | 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      -- ^ match if the amount's numeric quantity is less than/greater than/equal to/unsignedly equal to some value-  | Sym Regexp                -- ^ match if the commodity symbol is fully-matched by this regexp+  | 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 for transactions (any:, all:)-  -- If used in a non transaction-matching context, these are equivalent to And.+  -- 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)@@ -134,17 +161,17 @@  -- | Construct a query for the payee: tag payeeTag :: Maybe Text -> Either RegexError Query-payeeTag = fmap (Tag (toRegexCI' "payee")) . maybe (pure Nothing) (fmap Just . toRegexCI)+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 . toRegexCI)+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: queries. The Abs* variants+-- | 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)@@ -212,6 +239,7 @@   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@@ -241,11 +269,11 @@         let prefix :: T.Text             prefix = not' <> next         p <- singleQuotedPattern <|> doubleQuotedPattern-        return $ prefix <> stripquotes p+        return $ prefix <> textStripQuotes p       singleQuotedPattern :: SimpleTextParser T.Text-      singleQuotedPattern = stripquotes . T.pack <$> between (char '\'') (char '\'') (many $ noneOf ("'" :: [Char]))+      singleQuotedPattern = textStripQuotes . T.pack <$> between (char '\'') (char '\'') (many $ noneOf ("'" :: [Char]))       doubleQuotedPattern :: SimpleTextParser T.Text-      doubleQuotedPattern = stripquotes . T.pack <$> between (char '"') (char '"') (many $ noneOf ("\"" :: [Char]))+      doubleQuotedPattern = textStripQuotes . T.pack <$> between (char '"') (char '"') (many $ noneOf ("\"" :: [Char]))       patterns :: SimpleTextParser T.Text       patterns = T.pack <$> many (noneOf (" \n\r" :: [Char])) @@ -256,6 +284,8 @@      "inacctonly"     ,"inacct"     ,"amt"+    ,"change"+    ,"balance"     ,"code"     ,"desc"     ,"payee"@@ -266,14 +296,15 @@     ,"status"     ,"cur"     ,"real"-    ,"empty"     ,"depth"     ,"tag"     ,"type"     ,"expr"     ,"any"     ,"all"+    ,"find"     ]+    ++ ["::"]  -- short form of find:  defaultprefix :: T.Text defaultprefix = "acct"@@ -297,27 +328,35 @@   case parseQueryTerm d s of     Right (q, qopts) -> Right (Not q, qopts)     Left err         -> Left err-parseQueryTerm _ (T.stripPrefix "code:" -> Just s) = (,[]) . Code <$> toRegexCI s-parseQueryTerm _ (T.stripPrefix "desc:" -> Just s) = (,[]) . Desc <$> toRegexCI s+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 <$> toRegexCI 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 $ "\"date2:"++T.unpack s++"\" gave a "++showDateParseError e+        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 $ "\"date:"++T.unpack s++"\" gave a "++showDateParseError e+        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 parseAmountQueryTerm s of-  Right (ord, q) -> Right (Amt ord q, [])-  Left err       -> Left err+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) = (,[]) . Sym <$> toRegexCI ("^" <> s <> "$") -- support cur: as an alias+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@@ -427,8 +466,8 @@                             -- if it is not one of the keywords "not", "and", "or".                             queryArgP :: SimpleTextParser T.Text                             queryArgP = choice'-                              [ stripquotes . T.pack <$> between (char '\'') (char '\'') (many $ noneOf ("'" :: [Char])),-                                stripquotes . T.pack <$> between (char '"') (char '"') (many $ noneOf ("\"" :: [Char])),+                              [ 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@@ -436,6 +475,17 @@                                 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.@@ -479,10 +529,64 @@     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 <- toRegexCI $ if T.null v then s else n-    body <- if T.null v then pure Nothing else Just <$> toRegexCI (T.tail v)+    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 @@ -491,8 +595,9 @@     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 $ "depth: should be a positive number, but received " ++ depthString-    regexp <- mapM toRegexCI $ if T.null b then Nothing else Just a+        _ -> 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)]@@ -515,40 +620,6 @@   where     help = "type:'s argument should be one or more of " ++ accountTypeChoices False -accountTypeChoices :: Bool -> String-accountTypeChoices allowlongform =-  intercalate ", "-    -- keep synced with parseAccountType-    $ ["A","L","E","R","X","C","V","G","U"]-    ++ if allowlongform then ["Asset","Liability","Equity","Revenue","Expense","Cash","Conversion","Gain","UnrealisedGain"] else []---- | Case-insensitively parse one single-letter code, or one long-form word if permitted, to an account type.--- On failure, returns the unparseable text.-parseAccountType :: Bool -> Text -> Either String AccountType-parseAccountType allowlongform s =-  case T.toLower s of-    -- keep synced with accountTypeChoices-    "a"                               -> Right Asset-    "l"                               -> Right Liability-    "e"                               -> Right Equity-    "r"                               -> Right Revenue-    "x"                               -> Right Expense-    "c"                               -> Right Cash-    "v"                               -> Right Conversion-    "g"                               -> Right Gain-    "u"                               -> Right UnrealisedGain-    "asset"          | allowlongform  -> Right Asset-    "liability"      | allowlongform  -> Right Liability-    "equity"         | allowlongform  -> Right Equity-    "revenue"        | allowlongform  -> Right Revenue-    "expense"        | allowlongform  -> Right Expense-    "cash"           | allowlongform  -> Right Cash-    "conversion"     | allowlongform  -> Right Conversion-    "gain"           | allowlongform  -> Right Gain-    "unrealisedgain" | allowlongform  -> Right UnrealisedGain-    "unrealizedgain" | allowlongform  -> Right UnrealisedGain-    _                                 -> Left $ T.unpack s- -- | 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@@ -566,6 +637,22 @@  -- * 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@@ -621,6 +708,40 @@     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 ?@@ -673,6 +794,10 @@ queryIsAcct (Acct _) = True queryIsAcct _ = False +queryIsFind :: Query -> Bool+queryIsFind (Find _ _) = True+queryIsFind _ = False+ queryIsType :: Query -> Bool queryIsType (Type _) = True queryIsType _ = False@@ -682,21 +807,48 @@ 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 (Amt{}) = True queryIsAmt _         = False -queryIsSym :: Query -> Bool-queryIsSym (Sym _) = True-queryIsSym _ = False+queryIsCur :: Query -> Bool+queryIsCur (Cur _) = True+queryIsCur _       = False -queryIsAmtOrSym :: Query -> Bool-queryIsAmtOrSym = liftA2 (||) queryIsAmt queryIsSym+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.@@ -720,7 +872,7 @@   ||| queryIsDesc   ||| queryIsReal   ||| queryIsAmt-  ||| queryIsSym+  ||| queryIsCur   )  (|||) :: (a->Bool) -> (a->Bool) -> (a->Bool)@@ -823,7 +975,8 @@ -- matching things with queries  matchesCommodity :: Query -> CommoditySymbol -> Bool-matchesCommodity (Sym r)          s = regexMatchText r s+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@@ -832,6 +985,17 @@ 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@@ -841,8 +1005,8 @@ 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) a = compareAmount ord n a-matchesAmount (Sym r) a = matchesCommodity (Sym r) (acommodity a)+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 ?@@ -858,14 +1022,33 @@                                                        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 ?--- A matching in: clause is also considered a match.+-- 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@@ -873,10 +1056,10 @@ 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 (Tag _ _) _ = False-matchesAccount _ _ = True+matchesAccount _ _ = False  -- | Like matchesAccount, but with optional extra matching features: --@@ -896,43 +1079,71 @@ 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 = all (`matchesPosting` p) qs-matchesPosting (AllPostings qs) p = all1 (`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 (Sym r) Posting{pamount=as} = any (matchesCommodity (Sym r) . acommodity) $ amountsRaw as+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 = all (\q -> matchesPostingExtra atype q p) qs-matchesPostingExtra atype (AllPostings qs)  p = all1 (\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)@@ -945,8 +1156,47 @@   ) 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@@ -957,24 +1207,28 @@ 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@(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@(Sym _) 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@@ -983,27 +1237,59 @@ matchesTransactionExtra atype q@(Type _) t = any (matchesPostingExtra atype q) $ tpostings t matchesTransactionExtra _ q t = matchesTransaction q t --- | Does the query match this transaction description ?--- Non-desc: query terms are ignored (this might disrupt some boolean queries).-matchesDescription :: Query -> Text -> Bool-matchesDescription (Not q) d          = not $ q `matchesDescription` d-matchesDescription (Any) _            = True-matchesDescription (None) _           = False-matchesDescription (Or qs) d          = any (`matchesDescription` d) $ filter queryIsDesc qs-matchesDescription (And qs) d         = all (`matchesDescription` d) $ filter queryIsDesc qs-matchesDescription (AnyPosting  qs) d = all (`matchesDescription` d) $ filter queryIsDesc qs-matchesDescription (AllPostings qs) d = all1 (`matchesDescription` d) $ filter queryIsDesc qs-matchesDescription (Code _) _         = False-matchesDescription (Desc r) d         = regexMatchText r d-matchesDescription _ _                = False+-- | 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 the query match this transaction payee ?--- Tests desc: (and payee: ?) terms, any other terms are ignored.--- XXX Currently an alias for matchDescription. I'm not sure if more is needed,--- There's some shenanigan with payee: and "payeeTag" to figure out.-matchesPayeeWIP :: Query -> Payee -> Bool-matchesPayeeWIP = matchesDescription+-- | 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)@@ -1031,12 +1317,21 @@ 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@(Sym _) p        = matchesCommodity q (pdcommodity p)+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" [@@ -1058,6 +1353,10 @@      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"), [])@@ -1113,8 +1412,11 @@      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, [])-     parseQueryTerm nulldate "amt:>10000.10"                    @?= Right (Amt AbsGt 10000.1, [])+     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@@ -1128,6 +1430,64 @@      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@@ -1150,8 +1510,8 @@      assertBool "" $ Depth 2 `matchesAccount` "a"      assertBool "" $ Depth 2 `matchesAccount` "a:b"      assertBool "" $ not $ Depth 2 `matchesAccount` "a:b:c"-     assertBool "" $ Date nulldatespan `matchesAccount` "a"-     assertBool "" $ Date2 nulldatespan `matchesAccount` "a"+     assertBool "" $ not $ Date nulldatespan `matchesAccount` "a"+     assertBool "" $ not $ Date2 nulldatespan `matchesAccount` "a"      assertBool "" $ not $ Tag (toRegex' "a") Nothing `matchesAccount` "a"    ,testCase "matchesAccountExtra" $ do@@ -1170,9 +1530,9 @@       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{ptype=RegularPosting}-    ,testCase "real:1 on virtual posting fails" $ assertBool "" $ not $ (Real True) `matchesPosting` nullposting{ptype=VirtualPosting}-    ,testCase "real:1 on balanced virtual posting fails" $ assertBool "" $ not $ (Real True) `matchesPosting` nullposting{ptype=BalancedVirtualPosting}+    ,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@@ -1189,6 +1549,24 @@       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@@ -1203,18 +1581,18 @@      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]+     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]+     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] `matchesTransaction`+     assertBool "" $ AllPostings [Amt Eq 0 Nothing] `matchesTransaction`       nulltransaction{tpostings = [nullposting{paccount = "cash"}, nullposting{paccount = "food"}]}-     assertBool "" $ not $ AllPostings [Acct $ toRegex' "cash", Amt Eq 0] `matchesTransaction`+     assertBool "" $ not $ AllPostings [Acct $ toRegex' "cash", Amt Eq 0 Nothing] `matchesTransaction`       nulltransaction{tpostings = [nullposting{paccount = "cash"}, nullposting{paccount = "food"}]}  ]
Hledger/Read.hs view
@@ -118,17 +118,17 @@   orDieTrying,    -- * Misc-  saveLatestDates,-  saveLatestDatesForFiles,   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,@@ -137,35 +137,35 @@  --- ** imports import Control.Exception qualified as C-import Control.Monad (unless, when, forM, (>=>))+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 (group, sort, sortBy)+import Data.List (intercalate, union) import Data.List.NonEmpty (nonEmpty, NonEmpty((:|)))-import Data.Maybe (catMaybes, fromMaybe)-import Data.Ord (comparing)+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 Data.Time (Day)-import Safe (headDef) import System.Directory (createDirectoryIfMissing, doesFileExist) import System.Environment (getEnv)-import System.FilePath ((<.>), (</>), splitDirectories, splitFileName, takeDirectory, takeFileName)+import System.FilePath ((</>), splitDirectories, takeDirectory, takeFileName) import System.Info (os) import System.IO (Handle, hPutStrLn, stderr)-import Text.Printf (printf) -import Hledger.Data.Dates (getCurrentDay, parsedate, showDate)-import Hledger.Data.Journal (journalNumberTransactions, nulljournal)+import Hledger.Data.Amount (nullamt, showAmount)+import Hledger.Data.Dates (getCurrentDay)+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.LatestDates import Hledger.Read.CsvReader (tests_CsvReader) import Hledger.Read.RulesReader (tests_RulesReader) import Hledger.Utils@@ -322,10 +322,13 @@   let     (mfmt, f) = splitReaderPrefix prefixedfile     iopts' = iopts{mformat_=asum [mfmt, mformat_ iopts]}-  liftIO $ requireJournalFileExists f+  -- 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 $ openFileOrStdin 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@@ -348,7 +351,7 @@       exists <- liftIO $ doesFileExist f       if exists         then readJournalFile iopts prefixedfile-        else return $ nulljournal{jfiles = [(f, "")]}+        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.@@ -361,7 +364,7 @@     let iopts' = iopts{_defer=True}     j1 <- readPossibleJournalFile iopts' f     js <- mapM (readJournalFile iopts') fs-    let combined = journalNumberTransactions $ sconcat (j1 :| js)+    let combined = journalNumberAndTieTransactions $ sconcat (j1 :| js)     when (strict_ iopts) $ liftEither $ journalStrictChecks combined     return combined @@ -382,25 +385,50 @@ -- and is done only if strict checks pass. -- readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal-readJournalFiles iopts@InputOpts{strict_, new_, new_save_} prefixedfiles = do+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_ $ liftEither $ journalStrictChecks j+  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, ensuring their tindex values are unique;+-- 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-  return (journalNumberTransactions $ maybe def sconcat $ nonEmpty js, catMaybes lastdates)+  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@@ -465,74 +493,6 @@ newJournalContent = do   d <- getCurrentDay   return $ "; journal created " <> T.pack (show d) <> " by hledger\n"---- A "LatestDates" is zero or more copies of the same date,--- representing the latest transaction date read from a file,--- and how many transactions there were on that date.-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---- | 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---- | Where to save latest transaction dates for the given file path.--- (.latest.FILE)-latestDatesFileFor :: FilePath -> FilePath-latestDatesFileFor f = dir </> ".latest" <.> fname-  where-    (dir, fname) = splitFileName f---- | 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  --- ** tests 
Hledger/Read/Common.hs view
@@ -30,1722 +30,2520 @@ --- ** exports module Hledger.Read.Common (   Reader (..),-  PrefixedFilePath,-  isStdin,-  InputOpts(..),-  HasInputOpts(..),-  definputopts,-  rawOptsToInputOpts,-  handleReadFnToTextReadFn,--  -- * parsing utilities-  parseAndFinaliseJournal,-  initialiseAndParseJournal,-  journalFinalise,-  journalAddForecast,-  journalAddAutoPostings,-  setYear,-  getYear,-  setDefaultCommodityAndStyle,-  getDefaultCommodityAndStyle,-  getDefaultAmountStyle,-  getAmountStyle,-  addDeclaredAccountTags,-  addDeclaredAccountType,-  pushParentAccount,-  popParentAccount,-  getParentAccount,-  addAccountAlias,-  getAccountAliases,-  clearAccountAliases,-  journalAddFile,--  -- * parsers-  -- ** transaction bits-  statusp,-  codep,-  descriptionp,--  -- ** dates-  datep,-  datetimep,-  secondarydatep,--  -- ** account names-  modifiedaccountnamep,-  accountnamep,-  accountnamenosemicolonp,--  -- ** account aliases-  accountaliasp,--  -- ** amounts-  spaceandamountormissingp,-  amountp,-  amountp',-  commoditysymbolp,-  costp,-  balanceassertionp,-  lotcostp,-  numberp,-  fromRawNumber,-  rawnumberp,-  parseamount,-  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.Applicative.Permutations (runPermutation, toPermutationWithDefault)-import Control.Monad (foldM, join, liftM2, when, unless, (>=>), (<=<))-import Control.Monad.Fail qualified as Fail (fail)-import Control.Monad.Except (ExceptT(..), liftEither, withExceptT)-import Control.Monad.IO.Class (MonadIO, liftIO)-import Control.Monad.State.Strict (MonadState, evalStateT, modify', get, put)-import Control.Monad.Trans.Class (lift)-import Data.Bifunctor (bimap, 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, union)-import Data.List.NonEmpty (NonEmpty(..))-import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe)-import Data.Map qualified as M-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 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.-  ,rParser :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal-  }--instance Show (Reader m) where show r = show (rFormat r) ++ " reader"---- | 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 -> Bool -> RawOpts -> InputOpts-rawOptsToInputOpts day usecoloronstdout autopostingtags 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-balancing: '" ++ 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-      ,auto_posting_tags_ = autopostingtags-      ,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-      ,balancingopts_     = defbalancingopts{-                                 ignore_assertions_     = boolopt "ignore-assertions" rawopts-                               , infer_balancing_costs_ = not noinferbalancingcosts-                               , txn_balancing_         = txnbalancingprecision-                               , 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 <=< 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 . stripquotes $ 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)--transactionBalancingPrecisionFromOpts :: RawOpts -> Either String TransactionBalancingPrecision-transactionBalancingPrecisionFromOpts rawopts =-  case maybestringopt "txn-balancing" rawopts of-    Nothing      -> Right TBPExact-    Just "old"   -> Right TBPOld-    Just "exact" -> Right TBPExact-    Just s       -> Left $ s<>", should be one of: old, exact"---- | 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-  where-    y = first3 . toGregorian $ _ioDay iopts-    initJournal cf = nulljournal{jparsedefaultyear = Just y, jincludefilestack = [(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)--{- 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 Journal that has just been parsed or generated, in this order:------ - add misc info (file path, read time) ------ - reverse transactions into their original parse order------ - apply canonical commodity styles------ - propagate account tags to postings------ - maybe add forecast transactions------ - propagate account tags to postings (again to affect forecast transactions)------ - maybe add auto postings------ - propagate account tags to postings (again to affect auto postings)------ - evaluate balance assignments and balance each transaction------ - maybe check balance assertions------ - maybe infer costs from equity postings------ - maybe infer equity postings from costs------ - manye infer market prices from costs------ One correctness check (parseable) has already passed when this function is called.--- Up to four more are performed here:------  - ordereddates (when enabled)------  - assertions (when enabled)------  - autobalanced (and with --strict, balanced ?), in the journalBalanceTransactions step.------ Others (commodities, accounts..) are done later by journalStrictChecks.----journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal-journalFinalise iopts@InputOpts{auto_,balancingopts_,infer_costs_,infer_equity_,strict_,auto_posting_tags_,verbose_tags_,_ioDay} f txt pj = do-  let-    BalancingOpts{commodity_styles_, ignore_assertions_} = balancingopts_-    fname = "journalFinalise " <> takeFileName f-    lbl = lbl_ fname-    -- Some not so pleasant hacks-    -- We want to know when certain checks have been explicitly requested with the check command,-    -- but it does not run until later. For now, inspect the command line with unsafePerformIO.-    checking checkname = "check" `elem` args && checkname `elem` args where args = progArgs-    -- We will check ordered dates when "check ordereddates" is used.-    checkordereddates = checking "ordereddates"-    -- We will check balance assertions by default, unless -I is used, but always if -s or "check assertions" are used.-    checkassertions = not ignore_assertions_ || strict_ || checking "assertions"--  t <- liftIO getPOSIXTime-  liftEither $-    pj{jglobalcommoditystyles=fromMaybe mempty commodity_styles_}-      &   journalSetLastReadTime t                       -- save the last read time-      &   journalAddFile (f, txt)                        -- save the main file's info-      &   journalReverse                                 -- convert all lists to the order they were parsed-      &   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 ?-      &   journalStyleAmounts                            -- Infer and apply commodity styles (but don't round) - should be done early-      <&> journalAddForecast verbose_tags_ (forecastPeriod iopts pj)   -- Add forecast transactions if enabled-      <&> (if auto_posting_tags_ then journalPostingsAddAccountTags else id)     -- Maybe propagate account tags to postings-      >>= journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ False   -- Tag equity conversion postings and redundant costs, to help journalBalanceTransactions ignore them.-      >>= (if auto_ && not (null $ jtxnmodifiers pj)-            then journalAddAutoPostings verbose_tags_ _ioDay balancingopts_  -- Add auto postings if enabled, and account tags if needed. Does preliminary transaction balancing.-            else pure)-      -- XXX how to force debug output here ?-       -- >>= Right . dbg0With (concatMap (T.unpack.showTransaction).jtxns)-       -- >>= \j -> deepseq (concatMap (T.unpack.showTransaction).jtxns $ j) (return j)-      <&> dbg9With (lbl "amounts after styling, forecasting, auto-posting".showJournalPostingAmountsDebug)-      >>= (\j -> if checkordereddates then journalCheckOrdereddates j $> j else Right j)  -- check ordereddates before assertions. The outer parentheses are needed.-      >>= (\j -> journalBalanceTransactions balancingopts_{ignore_assertions_=not checkassertions, account_types_ = jaccounttypes j} j)  -- infer balance assignments and missing amounts, and maybe check balance assertions.-      <&> dbg9With (lbl "amounts after transaction-balancing".showJournalPostingAmountsDebug)-      -- <&> dbg9With (("journalFinalise amounts after styling, forecasting, auto postings, transaction balancing"<>).showJournalPostingAmountsDebug)-      >>= journalInferCommodityStyles                    -- infer commodity styles once more now that all posting amounts are present-      -- >>= Right . dbg0With (pshow.journalCommodityStyles)-      <&> (if auto_posting_tags_ then journalPostingsAddCommodityTags else id)  -- Maybe propagate commodity tags to postings (after amounts are inferred)-      >>= (if infer_costs_  then journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ True else pure)  -- With --infer-costs, infer costs from equity postings where possible-      <&> (if infer_equity_ then journalInferEquityFromCosts verbose_tags_ else id)          -- With --infer-equity, infer equity postings from costs where possible-      <&> dbg9With (lbl "amounts after equity-inferring".showJournalPostingAmountsDebug)-      <&> journalInferMarketPricesFromTransactions       -- infer market prices from commodity-exchanging transactions-      -- <&> dbg6Msg fname  -- debug logging-      <&> dbgJournalAcctDeclOrder (fname <> ": acct decls           : ")-      <&> journalRenumberAccountDeclarations-      <&> dbgJournalAcctDeclOrder (fname <> ": acct decls renumbered: ")---- | 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--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 = do-  Journal{jparsedecimalmark} <- get-  let mdecmarkStyle = (\c -> Just $ amountstyle{asdecimalmark=Just c}) =<< jparsedecimalmark-  return mdecmarkStyle--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 = do-  Journal{jdeclaredcommodities} <- get-  let mspecificStyle = M.lookup commodity jdeclaredcommodities >>= cformat-  mdefaultStyle <- fmap snd <$> getDefaultCommodityAndStyle-  return $ listToMaybe $ catMaybes [mspecificStyle, mdefaultStyle]--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})--popParentAccount :: JournalParser m ()-popParentAccount = do-  j <- get-  case jparseparentaccounts j of-    []       -> unexpected (Tokens ('E' :| "nd of apply account block with no beginning"))-    (_:rest) -> put j{jparseparentaccounts=rest}--getParentAccount :: JournalParser m AccountName-getParentAccount = fmap (concatAccountNames . reverse . jparseparentaccounts) get--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--clearAccountAliases :: MonadState Journal m => m ()-clearAccountAliases = modify' (\j -> j{jparsealiases=[]})---- 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 :: (FilePath,Text) -> 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 =-  choice'-    [ skipNonNewlineSpaces >> char '*' >> return Cleared-    , skipNonNewlineSpaces >> char '!' >> return Pending-    , return Unmarked-    ]--codep :: TextParser m Text-codep = option "" $ do-  try $ do-    skipNonNewlineSpaces1-    char '('-  code <- takeWhileP Nothing $ \c -> c /= ')' && c /= '\n'-  char ')' <?> "closing bracket ')' for transaction code"-  pure code---- | 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 <- timeOfDay-  optional timeZone -- ignoring time zones-  pure $ LocalTime day 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 any parent account prefix and/or account aliases currently in effect,--- in that order. Ie first add the parent account prefix, then rewrite with aliases.--- 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 = do-  parent  <- getParentAccount-  als     <- getAccountAliases-  -- off1    <- getOffset-  a       <- lift $ if allowsemicolon then accountnamep else accountnamenosemicolonp-  -- off2    <- getOffset-  -- XXX or accountNameApplyAliasesMemo ? doesn't seem to make a difference (retest that function)-  case accountNameApplyAliases als $ joinAccountNames parent a of-    Right a' -> return $! a'-    -- should not happen, regexaliasp will have displayed a better error already:-    -- (XXX why does customFailure cause error to be displayed there, but not here ?)-    -- Left e  -> customFailure $! parseErrorAtRegion off1 off2 err-    Left e   -> error' err  -- PARTIAL:-      where-        err = "problem in account alias applied to "++T.unpack a++": "++e---- | 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 spaces (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.)--- 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 = singlespacedtext1p---- Like accountnamep, but stops parsing if it reaches a semicolon.-accountnamenosemicolonp :: TextParser m AccountName-accountnamenosemicolonp = singlespacednoncommenttext1p---- | 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 <- many $ try $ singlespacep *> partp-  pure $! T.unwords $ firstPart : otherParts-  where-    partp = takeWhile1P Nothing (\c -> f c && not (isSpace c))---- | Parse one non-newline whitespace character that is not followed by another one.-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, ---    we use that------ 2. Or if the journal has a commodity declaration for the amount's commodity,---    we get the decimal mark from  that------ 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' False---- An amount with optional cost, valuation, and/or cost basis, as described above.--- A flag indicates whether we are parsing a multiplier amount;--- if not, a commodity-less amount will have the default commodity applied to it.-amountp' :: Bool -> JournalParser m Amount-amountp' mult =-  -- dbg "amountp'" $-  label "amount" $ do-  let spaces = lift $ skipNonNewlineSpaces-  amt <- simpleamountp mult <* spaces-  (mcost, _valuationexpr, mlotcost, mlotdate, mlotnote) <- runPermutation $-    -- costp, valuationexprp, lotnotep all parse things beginning with parenthesis, try needed-    (,,,,) <$> toPermutationWithDefault Nothing (Just <$> try (costp amt) <* spaces)-          <*> toPermutationWithDefault Nothing (Just <$> valuationexprp <* spaces)  -- XXX no try needed here ?-          <*> toPermutationWithDefault Nothing (Just <$> lotcostp (aquantity amt) <* spaces)-          <*> toPermutationWithDefault Nothing (Just <$> lotdatep <* spaces)-          <*> toPermutationWithDefault Nothing (Just <$> lotnotep <* spaces)-  let mcostbasis =-        case (mlotcost, mlotdate, mlotnote) of-          (Nothing, Nothing, Nothing) -> Nothing-          _ -> Just $ CostBasis { cbCost = join mlotcost, cbDate = mlotdate, 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 False-  spaces-  mprice <- optional $ costp amt <* spaces-  pure $ amt { acost = mprice }---- An amount with no cost or cost basis.--- A flag indicates whether we are parsing a multiplier amount;--- if not, a commodity-less amount will have the default commodity applied to it.-simpleamountp :: Bool -> JournalParser m Amount-simpleamountp mult = -  -- dbg "simpleamountp" $-  do-  sign <- lift signp-  leftsymbolamountp sign <|> rightornosymbolamountp sign--  where-  -- An amount with commodity symbol on the left.-  leftsymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount-  leftsymbolamountp sign = label "amount" $ do-    c <- 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 $ optional $ try exponentp-    offAfterNum <- getOffset-    let numRegion = (offBeforeNum, offAfterNum)-    (q,prec,mdec,mgrps) <- lift $ interpretNumber numRegion suggestedStyle ambiguousRawNum mExponent-    let s = 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 $ optional $ try exponentp-    offAfterNum <- getOffset-    let numRegion = (offBeforeNum, offAfterNum)-    mSpaceAndCommodity <- lift $ optional $ try $ (,) <$> skipNonNewlineSpaces' <*> commoditysymbolp-    case mSpaceAndCommodity of-      -- right symbol amount-      Just (commodityspaced, c) -> do-        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) <- lift $ interpretNumber numRegion msuggestedStyle ambiguousRawNum mExponent-        let s = 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) <- lift $ 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)-        defcs <- getDefaultCommodityAndStyle-        let (c,s) = case (mult, defcs) of-              (False, Just (defc,defs)) -> (defc, defs{asprecision=max (asprecision defs) prec})-              _ -> ("", amountstyle{asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps})-        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 throw parse errors (for convenience).-  interpretNumber-    :: (Int, Int) -- offsets-    -> Maybe AmountStyle-    -> Either AmbiguousNumber RawNumber-    -> Maybe Integer-    -> TextParser m (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)-  interpretNumber posRegion msuggestedStyle ambiguousNum mExp =-    let rawNum = either (disambiguateNumber msuggestedStyle) id ambiguousNum-    in  case fromRawNumber rawNum mExp of-          Left errMsg -> customFailure $-                           uncurry parseErrorAtRegion posRegion errMsg-          Right (q,p,d,g) -> pure (q, Precision p, d, g)---- | 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)---- | 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 = ((char '-' $> negate <|> char '+' $> id) <* skipNonNewlineSpaces) <|> pure id--commoditysymbolp :: TextParser m CommoditySymbol-commoditysymbolp =-  quotedcommoditysymbolp <|> 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.-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-  parenthesised <- option False $ char '(' >> pure True-  char '@'-  totalCost <- char '@' $> True <|> pure False-  when parenthesised $ void $ char ')'--  lift skipNonNewlineSpaces-  priceAmount <- simpleamountp False -- <?> "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---- | 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 <- fmap isJust $ optional $ try $ char '='-  isinclusive <- fmap isJust $ optional $ try $ 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 a Ledger-style lot cost:--- {UNITCOST} or {{TOTALCOST}} or {=FIXEDUNITCOST} or {{=FIXEDTOTALCOST}} or {}.--- If total cost syntax {{}} is used, converts it to unit cost by dividing by the posting quantity.-lotcostp :: Quantity -> JournalParser m (Maybe Amount)-lotcostp postingqty =-  -- dbg "lotcostp" $-  label "ledger-style lot cost" $ do-  char '{'-  doublebrace <- option False $ char '{' >> pure True-  lift skipNonNewlineSpaces-  _fixed <- fmap isJust $ optional $ char '='-  lift skipNonNewlineSpaces-  ma <- optional $ simpleamountp False-  lift skipNonNewlineSpaces-  char '}'-  when (doublebrace) $ void $ char '}'-  pure $ fmap (convertToUnitCost doublebrace) ma-  where-    -- Convert {{TOTALCOST}} to {UNITCOST} by dividing by posting quantity-    convertToUnitCost isTotal lotamt =-      if isTotal && postingqty /= 0-      then lotamt { aquantity = aquantity lotamt / postingqty }-      else lotamt---- 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).-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 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-    rawNum <- either (disambiguateNumber suggestedStyle) id <$> rawnumberp-    mExp <- optional $ try $ exponentp-    dbg7 "numberp suggestedStyle" suggestedStyle `seq` return ()-    case dbg7 "numberp quantity,precision,mdecimalpoint,mgrps"-           $ fromRawNumber rawNum 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"---- | 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)-    return (quantity, precision, mDecPt raw, digitGroupStyle raw)-  where-    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-    isValidDecimalBy :: Char -> AmountStyle -> Bool-    isValidDecimalBy c = \case-      AmountStyle{asdecimalmark = Just d} -> d == c-      AmountStyle{asdigitgroups = Just (DigitGroups g _)} -> g /= c-      AmountStyle{asprecision = Precision 0} -> False-      _ -> 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)----rawnumberp :: TextParser m (Either AmbiguousNumber RawNumber)-rawnumberp = label "number" $ do-  rawNumber <- fmap Right leadingDecimalPt <|> leadingDigits--  -- Guard against mistyped numbers-  mExtraDecimalSep <- optional $ lookAhead $ satisfy isDecimalMark-  when (isJust mExtraDecimalSep) $-    Fail.fail "invalid number (invalid use of separator)"--  mExtraFragment <- optional $ lookAhead $ try $-    char ' ' *> getOffset <* digitChar-  case mExtraFragment of-    Just off -> customFailure $-                  parseErrorAt off "invalid number (excessive trailing digits)"-    Nothing -> 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-    withSeparators grp1 <|> fmap Right (trailingDecimalPt grp1)-                        <|> 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 = isDecimalMark 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-  skiplinecommentp <|> 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-  sameLine <- try headerp *> ((:[]) <$> match' contentp) <|> pure []-  _ <- eolof-  -- there can be 0 or more nextLines-  nextLines <- many $-    try (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--{-# 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)----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--    dateValue :: Text -> TextParser m ([Tag], [DateTag])-    dateValue 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.-aliasesFromOpts :: InputOpts -> [AccountAlias]-aliasesFromOpts = map (\a -> fromparse $ runParser accountaliasp ("--alias "++quoteIfNeeded a) $ T.pack a)-                  . aliases_--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 = 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.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" ""+  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)
Hledger/Read/CsvReader.hs view
@@ -26,14 +26,16 @@  --- ** imports import Prelude hiding (Applicative(..))-import Control.Monad.Except       (ExceptT(..), liftEither)+import Control.Monad.Except       (ExceptT(..), liftEither, withExceptT) import Control.Monad.IO.Class     (MonadIO)-import System.IO                  (Handle)+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(..), journalFinalise)-import Hledger.Read.RulesReader (readJournalFromCsv, getRulesFile, rulesEncoding, readRules)+import Hledger.Read.Common (aliasesFromOpts, Reader(..), InputOpts(..), includeFileParser, journalFinalise)+import Hledger.Read.RulesReader (readParsedJournalFromCsv, getRulesFile, rulesEncoding, readRules) import Control.Monad.Trans (lift)  --- ** doctest setup@@ -47,32 +49,39 @@   {rFormat     = Sep sep   ,rExtensions = [show sep]   ,rReadFn     = parse sep-  ,rParser     = const $ fail "sorry, CSV files can't be included yet"-    -- This unnecessarily shows the CSV file's first line in the error message,-    -- but gives a more useful message than just calling error'.-    -- XXX Note every call to error' in Hledger.Read.* is potentially a similar problem --    -- the error message is good enough when the file was specified directly by the user,-    -- but not good if it was loaded by a possibly long chain of include directives.+  -- 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 currently ignores the provided input file handle, and reads from the data file itself,--- inferring a corresponding rules file to help convert it.+-- 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-  rules <- readRules $ getRulesFile f (mrules_file_ iopts)-  mencoding <- rulesEncoding rules-  csvtext <- lift $ hGetContentsPortably mencoding h-  readJournalFromCsv rules f csvtext (Just sep)+  (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.-  >>= liftEither . journalApplyAliases (aliasesFromOpts iopts)-      -- journalFinalise assumes the journal's items are-      -- reversed, as produced by JournalReader's parser.-      -- But here they are already properly ordered. So we'd-      -- better preemptively reverse them once more. XXX inefficient-      . journalReverse-  >>= journalFinalise iopts{balancingopts_=(balancingopts_ iopts){ignore_assertions_=True}} f ""+  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 
Hledger/Read/InputOptions.hs view
@@ -11,14 +11,20 @@   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)+import Hledger.Data.Journal (journalEndDate, journalFilePath) import Hledger.Data.Dates (nulldate, nulldatespan) import Hledger.Data.Balancing (BalancingOpts(..), HasBalancingOpts(..), defbalancingopts) import Hledger.Utils (dbg2, makeHledgerClassyLenses)@@ -34,17 +40,42 @@     ,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-    ,auto_posting_tags_ :: Bool                 -- ^ propagate commodity and account tags to postings ? Can be disabled (for beancount export).     ,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@@ -57,18 +88,48 @@     , new_save_          = True     , pivot_             = ""     , forecast_          = Nothing-    , auto_posting_tags_ = False     , 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:
Hledger/Read/JournalReader.hs view
@@ -64,1172 +64,2194 @@   statusp,   emptyorcommentlinep,   followingcommentp,-  accountaliasp--  -- * Tests-  ,tests_JournalReader-)-where----- ** imports-import Control.Exception qualified as C-import Control.Monad (forM_, when, void, unless, filterM, forM)-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.Char (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.FilePath-import "Glob" System.FilePath.Glob hiding (match)--- import "filepattern" System.FilePattern.Directory--import Hledger.Data-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-      -- reverse parsed aliases to ensure that they are applied in order given on commandline-      mapM_ addAccountAlias (reverse $ 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-  get---- | A side-effecting parser; parses any kind of journal item--- and updates the parse state accordingly.-addJournalItemP :: MonadIO m => InputOpts -> ErroringJournalParser m ()-addJournalItemP iopts =-  -- all journal line types can be distinguished by the first-  -- character, can use choice without backtracking-  choice [-      directivep iopts-    , transactionp          >>= modify' . addTransaction-    , transactionmodifierp  >>= modify' . addTransactionModifier-    , periodictransactionp  >>= modify' . addPeriodicTransaction-    , marketpricedirectivep >>= modify' . addPriceDirective-    , void (lift emptyorcommentlinep)-    , void (lift multilinecommentp)-    ] <?> "transaction or directive"----- *** directives---- | Parse any journal directive and update the parse state accordingly.--- 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-   ,aliasdirectivep-   ,endaliasesdirectivep-   ,accountdirectivep-   ,applyaccountdirectivep-   ,applyfixeddirectivep-   ,applytagdirectivep-   ,assertdirectivep-   ,bucketdirectivep-   ,capturedirectivep-   ,checkdirectivep-   ,commandlineflagdirectivep-   ,commoditydirectivep-   ,commodityconversiondirectivep-   ,decimalmarkdirectivep-   ,defaultyeardirectivep-   ,defaultcommoditydirectivep-   ,definedirectivep-   ,endapplyaccountdirectivep-   ,endapplyfixeddirectivep-   ,endapplytagdirectivep-   ,endapplyyeardirectivep-   ,endtagdirectivep-   ,evaldirectivep-   ,exprdirectivep-   ,ignoredpricecommoditydirectivep-   ,payeedirectivep-   ,pythondirectivep-   ,tagdirectivep-   ,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-  string "include"-  -- notFollowedBy newline <?> "a file path or glob pattern argument"-  prefixedglob <- (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.-  forM_ prefixedpaths $ parseIncludedFile iopts eoff--  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 = jincludefilestack 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.-      when (null files2) $ 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)") $-          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--      -- Read the file's content, or throw an error-      childInput <- lift $ readFilePortably filepath & handleIOError off "failed to read a file"-      cfilepath <- liftIO $ canonicalizePath filepath-      parentj <- get-      let initChildj = newJournalWithParseStateFrom filepath cfilepath parentj--      -- 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)--      -- Parse the file (and its own includes, if any) to a Journal-      -- with file path and source text attached. Or throw an error.-      updatedChildj <- journalAddFile (filepath, childInput) <$>-                        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 $ jincludefilestack 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-          ,jparsedefaultcommodity = jparsedefaultcommodity j-          ,jparseparentaccounts   = jparseparentaccounts j-          ,jparsedecimalmark      = jparsedecimalmark j-          ,jparsealiases          = jparsealiases j-          ,jdeclaredcommodities           = jdeclaredcommodities j-          -- ,jparsetransactioncount = jparsetransactioncount j-          ,jparsetimeclockentries = jparsetimeclockentries j-          ,jincludefilestack      = (filepath, cfilepath) : jincludefilestack 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-  acct <- (notFollowedBy (char '(' <|> char '[') <?> "account name without brackets") >>-          modifiedaccountnamep True--  -- maybe a comment, on this and/or following lines-  (cmt, tags) <- lift transactioncommentp--  -- maybe Ledger-style subdirectives (ignored)-  skipMany indentedlinep--  -- an account type may have been set by account type code or a tag;-  -- the latter takes precedence-  let-    metype = parseAccountTypeCode <$> lookup accountTypeTagName tags--  -- 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"--parseAccountTypeCode :: Text -> Either String AccountType-parseAccountTypeCode s =-  case T.toLower s of-    "asset"            -> Right Asset-    "a"                -> Right Asset-    "liability"        -> Right Liability-    "l"                -> Right Liability-    "equity"           -> Right Equity-    "e"                -> Right Equity-    "revenue"          -> Right Revenue-    "r"                -> Right Revenue-    "expense"          -> Right Expense-    "x"                -> Right Expense-    "cash"             -> Right Cash-    "c"                -> Right Cash-    "conversion"       -> Right Conversion-    "v"                -> Right Conversion-    "gain"             -> Right Gain-    "g"                -> Right Gain-    "unrealisedgain"   -> Right UnrealisedGain-    "u"                -> Right UnrealisedGain-    _                  -> Left err-  where-    err = T.unpack $ "invalid account type code "<>s<>", should be one of " <>-            T.intercalate ", " ["A","L","E","R","X","C","V","G","U","Asset","Liability","Equity","Revenue","Expense","Cash","Conversion","Gain","UnrealisedGain"]---- 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 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, Amount{acommodity,astyle}) <- try $ do-    string "commodity"-    lift skipNonNewlineSpaces1-    off <- getOffset-    amt <- amountp-    pure $ (off, amt)-  lift skipNonNewlineSpaces-  (comment, tags) <- lift transactioncommentp-  let comm = Commodity{csymbol=acommodity, cformat=Just $ dbg7 "style from commodity directive" astyle, ccomment=comment, ctags=tags}-  if isNothing $ asdecimalmark astyle-  then customFailure $ parseErrorAt off pleaseincludedecimalpoint-  else modify' (\j -> j{jdeclaredcommodities=M.insert acommodity comm $ jdeclaredcommodities j-                       ,jdeclaredcommoditytags=if null tags then jdeclaredcommoditytags j-                                               else M.insert acommodity tags $ jdeclaredcommoditytags j})--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"-  lift skipNonNewlineSpaces1-  sym <- lift commoditysymbolp-  (comment, tags) <- lift transactioncommentp-  -- 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}-  modify' (\j -> j{jdeclaredcommodities=M.insert sym comm $ jdeclaredcommodities j-                  ,jdeclaredcommoditytags=if null tags then jdeclaredcommoditytags j-                                          else M.insert sym tags $ jdeclaredcommoditytags j})-  where-    indented = (lift skipNonNewlineSpaces1 >>)---- | 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-  _ <- 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---- More Ledger directives, ignore for now:--- apply fixed, apply tag, assert, bucket, A, capture, check, define, expr-applyfixeddirectivep, endapplyfixeddirectivep, applytagdirectivep, endapplytagdirectivep,-  assertdirectivep, bucketdirectivep, capturedirectivep, checkdirectivep, -  endapplyyeardirectivep, 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 ()-endapplyyeardirectivep  = do string "end apply year" >> lift restofline >> return ()-assertdirectivep        = do string "assert"  >> 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 accountnamep-  newline-  pushParentAccount parent--endapplyaccountdirectivep :: JournalParser m ()-endapplyaccountdirectivep = do-  keywordsp "end apply account" <?> "end apply account directive"-  popParentAccount--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"-  clearAccountAliases--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" <|> string "apply year") <?> "default year"-  lift skipNonNewlineSpaces-  setYear =<< lift yearp--defaultcommoditydirectivep :: JournalParser m ()-defaultcommoditydirectivep = do-  char 'D' <?> "default commodity"-  lift skipNonNewlineSpaces1-  off <- getOffset-  Amount{acommodity,astyle} <- amountp-  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 <- try (do {LocalTime d _ <- datetimep; return d}) <|> datep -- a time is ignored-  lift skipNonNewlineSpaces1-  symbol <- 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-  postings <- 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 a (possibly unbalanced) transaction.-transactionp :: JournalParser m Transaction-transactionp = do-  -- dbgparse 0 "transactionp"-  startpos <- getSourcePos-  date <- datep <?> "transaction"-  edate <- optional (lift $ secondarydatep date) <?> "secondary date"-  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 $ Transaction 0 "" sourcepos date edate status code description comment tags postings----- *** 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 = many (postingp mTransactionYear) <?> "postings"---- 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"--tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule-tmpostingrulep = fmap (uncurry TMPostingRule) . 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"-    (status, account) <- try $ do-      lift skipNonNewlineSpaces1-      status <- lift statusp-      lift skipNonNewlineSpaces-      account <- modifiedaccountnamep True-      return (status, account)-    let (ptype, account') = (accountNamePostingType account, textUnbracket account)-    lift skipNonNewlineSpaces-    mult <- if isPostingRule then multiplierp else pure False-    amt <- optional $ amountp' mult-    lift skipNonNewlineSpaces-    massertion <- optional balanceassertionp-    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-            , ptype=ptype-            , ptags=tags-            , pbalanceassertion=massertion-            }-    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 "empty inner component" $ assertParseError p "a::c" ""  -- TODO-    -- ,testCase "empty leading component" $ assertParseError p ":b:c" "x"-    -- ,testCase "empty trailing component" $ assertParseError p "a:b:" "x"-    ]--  -- "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",-            ptype=RegularPosting,-            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--    ]--  -- directives+  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
+ 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
@@ -20,1906 +20,2697 @@ {-# LANGUAGE RecordWildCards      #-} {-# LANGUAGE ScopedTypeVariables  #-} {-# LANGUAGE ViewPatterns         #-}-{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE TupleSections #-}----- ** exports-module Hledger.Read.RulesReader (-  -- * Reader-  reader,-  -- * Misc.-  dataFileFor,-  rulesFileFor,-  getRulesFile,-  readRules,-  rulesEncoding,-  readJournalFromCsv,-  parseBalanceAssertionType,-  -- * Tests-  tests_RulesReader,-)-where----- ** imports-import Prelude hiding (Applicative(..))-import Control.Applicative (Applicative(..))-import Control.Concurrent (forkIO)-import Control.DeepSeq (deepseq)-import Control.Monad (unless, void, when)-import Control.Monad.Except       (ExceptT(..), liftEither, throwError)-import Control.Monad.Fail qualified as Fail-import Control.Monad.IO.Class     (MonadIO, liftIO)-import Control.Monad.State.Strict (StateT, get, modify', evalStateT)-import Control.Monad.Trans.Class  (lift)-import Data.Char                  (toLower, 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.List (elemIndex, mapAccumL, nub, sortOn)--- import Data.List (elemIndex, mapAccumL, nub, sortOn, isPrefixOf, sortBy)--- import Data.Ord (Down(..), comparing)-#if !MIN_VERSION_base(4,20,0)-import Data.List (foldl')-#endif-import Data.List.Extra (groupOn)-import Data.Maybe (catMaybes, fromMaybe, isJust)-import Data.MemoUgly (memo)-import Data.Set qualified as S-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, headMay, lastMay, readMay)-import System.Directory (createDirectoryIfMissing, doesFileExist, getHomeDirectory, getModificationTime, removeFile)--- import System.Directory (createDirectoryIfMissing, doesFileExist, getHomeDirectory, getModificationTime, listDirectory, renameFile, doesDirectoryExist)-import System.Exit      (ExitCode(..))-import System.FilePath (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.Char (char, newline, string, digitChar)-import Text.Printf (printf)--import Hledger.Data-import Hledger.Utils-import Hledger.Read.Common (aliasesFromOpts, Reader(..), InputOpts(..), amountp, statusp, 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-  ,rParser     = const $ fail "sorry, rules files can't be included yet"-  }--isFileName f = takeFileName f == f--getDownloadDir = do-  home <- getHomeDirectory-  return $ home </> "Downloads"  -- XXX---- | Read, parse and post-process a "Journal" from the given rules file, or give an error.--- This particular reader also provides some extra features like data cleaning/generating commands and data archiving.------ The provided input file handle, and the --rules option, are ignored by this reader.--- Instead, a data file (or data-generating command) is usually specified by the @source@ rule.--- If there's no source rule, the data file is assumed to be named like the rules file without .rules, in the same directory.------ The source rule supports ~ for home directory: @source ~/Downloads/foo.csv@.--- If the argument is a bare filename, its directory is assumed to be ~/Downloads: @source foo.csv@.--- Otherwise if it is a relative path, it is assumed to be relative to the rules file's directory: @source new/foo.csv@.------ 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:--- 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 auto-created data/ directory next to the rules file,--- with a name based on the rules file and the data file's modification date and extension--- (or for a data-generating command, the current date and the ".csv" extension).--- And import will prefer the oldest file matched by a glob pattern (not the newest).------ Balance assertions are not checked by this reader.----parse :: InputOpts -> FilePath -> Handle -> ExceptT String IO Journal-parse iopts rulesfile h = do-  lift $ hClose h -- We don't need it (XXX why ?)--  -- The rules reader does a lot; we must be organised.--  -- 1. gather contextual info-  --  gives: import flag, dryrun flag, rulesdir--  let-    args     = progArgs-    import_  = dbg2 "import" $ any (`elem` args) ["import", "imp"]-    dryrun   = dbg2 "dryrun" $ any (`elem` args) ["--dry-run", "--dry"]-    rulesdir = takeDirectory rulesfile--  -- 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 <- readRules $ dbg1 "reading rules file" rulesfile-  let-    msourcearg = getDirective "source" rules-      -- Nothing -> error' $ rulesfile ++ " source rule must specify a file pattern or a command"-    -- Surrounding whitespace is removed from the whole source argument and from each part of it.-    -- A # before | makes the rest of line a comment.-    -- A # after | is left for the shell to interpret; it could be part of the command or the start of a comment.-    stripspaces = T.strip-    stripcommentandspaces = stripspaces . T.takeWhile (/= '#')-    mpatandcmd = T.breakOn "|" . stripspaces <$> msourcearg-    mpat = dbg2 "file pattern" $  -- a non-empty file pattern, or nothing-      case T.unpack . stripcommentandspaces . 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, downloads dir-  --  gives: data file, data file description--  (mdatafile, datafiledesc) <- dbg2 "data file found ?" <$> case (mpat, 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  -- look here for the data file if it's specified without a directory-      let-        (startdir, dirdesc)-          | isFileName pat = (dldir,    " in download directory")-          | otherwise      = (rulesdir, "")-      fs <- liftIO $-        expandGlob startdir pat-        >>= sortByModTime-        <&> dbg2 ("matched files"<>dirdesc<>", oldest first")-      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-  cleandata <- dbg1With (\t -> "read "++(show $ length $ T.lines t)++" lines") <$> 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 rules-      liftIO $ do-        raw <- openFileOrStdin f >>= hGetContentsPortably mencoding-        maybe (return raw) (\c -> runCommandAsFilter rulesfile (dbg0Msg ("running: "++c) c) raw) mc--    -- no file pattern, but a data generating command-    (Nothing, _, Just cmd) -> -- trace "data generating command" $-      liftIO $ runCommand rulesfile $ dbg0Msg ("running: " ++ cmd) cmd--    -- 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-  --  needs: clean data, rules, data file if any-  --  gives: journal--  j <- do-    readJournalFromCsv rules (fromMaybe "(cmd)" mdatafile) cleandata Nothing-    -- apply any command line account aliases. Can fail with a bad replacement pattern.-    >>= liftEither . journalApplyAliases (aliasesFromOpts iopts)-        -- journalFinalise assumes the journal's items are-        -- reversed, as produced by JournalReader's parser.-        -- But here they are already properly ordered. So we'd-        -- better preemptively reverse them once more. XXX inefficient-        . journalReverse-    >>= journalFinalise iopts{balancingopts_=(balancingopts_ iopts){ignore_assertions_=True}} rulesfile ""--  -- 7. if non-empty, successfully read and converted, and we're doing a non-dry-run archiving import: archive the data-  --  needs: import/archive/dryrun flags, rules directory, rules file, data file if any, clean data--  when (not (T.null cleandata) && import_ && archive && not dryrun) $-    liftIO $ saveToArchive (rulesdir </> "data") rulesfile mdatafile cleandata--  return j---- | For the given rules file, run the given shell command, in the rules file's directory.--- 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_out = CreatePipe, std_err = CreatePipe }-  withCreateProcess process $ \_ mhout mherr phandle -> do-    case (mhout, mherr) of-      (Just hout, Just herr) -> do-        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).-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-  maybe (return ()) removeFile mdatafile---- | 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-        )---- -- | In the given archive directory, if it exists, find the paths of data files saved for the given rules file.--- -- They will be reverse sorted by name, ie newest first, assuming normal archive file names.--- ----- -- We don't know which extension the data files use, but we look for file names beginning with--- -- the rules file's base name followed by .YYYY-MM-DD, which will normally be good enough.--- ----- archivesFor :: FilePath -> FilePath -> IO [FilePath]--- archivesFor archivedir rulesfile = do---   exists <- doesDirectoryExist archivedir---   if not exists then return []---   else do---     let prefix = takeBaseName rulesfile <> "."---     fs <- listDirectory archivedir---     return $ map (archivedir </>) $ sortBy (comparing Down)---       [f | f <- fs,---         prefix `isPrefixOf` f,---         let nextpart = takeWhile (/= '.') $ drop (length prefix) f,---         isJust $ parsedate nextpart---         ]----- ** 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).-readRules :: FilePath -> ExceptT String IO CsvRules-readRules f =-  liftIO (do-    dbg6IO "using conversion rules file" f-    readFilePortably f >>= expandIncludes (takeDirectory f)-  ) >>= either throwError return . parseAndValidateCsvRules f---- | Read the encoding specified by the @encoding@ rule, if any.--- Or throw an error if an unrecognised encoding is specified.-rulesEncoding :: CsvRules -> ExceptT String IO (Maybe DynEncoding)-rulesEncoding rules = do-  case T.unpack <$> getDirective "encoding" rules of-    Nothing     -> return Nothing-    Just encstr -> case encodingFromStringExplicit $ dbg4 "encoding name" encstr of-      Nothing  -> throwError $ "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.--- Unfortunately this means that the parser won't see accurate file paths and positions with included files.-expandIncludes :: FilePath -> Text -> IO Text-expandIncludes dir0 content = mapM (expandLine dir0) (T.lines content) <&> T.unlines-  where-    expandLine dir1 line =-      case line of-        (T.stripPrefix "include " -> Just f) -> expandIncludes dir2 =<< T.readFile f'-          where-            f' = dir1 </> T.unpack (T.dropWhile isSpace f)-            dir2 = takeDirectory f'-        _ -> return line---- 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.-parseAndValidateCsvRules :: FilePath -> T.Text -> Either String CsvRules-parseAndValidateCsvRules rulesfile s =-  case parseCsvRules rulesfile s of-    Left err    -> Left $ customErrorBundlePretty err-    Right rules -> first makeFancyParseError $ validateCsvRules rules-  where-    makeFancyParseError :: String -> String-    makeFancyParseError errorString =-      parseErrorPretty (FancyError 0 (S.singleton $ ErrorFail errorString) :: ParseError Text String)--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       :: [(HledgerFieldName, FieldTemplate)],-    -- ^ top-level assignments to hledger fields, as (field name, value template) pairs-  rconditionalblocks :: [ConditionalBlock],-    -- ^ conditional blocks, 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---- | A reference to a regular expression match group. Eg \1.-type MatchGroupReference = Text---- | 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.------ Three types of rule are allowed inside conditional blocks: field--- assignments, skip, end. (A skip or end rule is stored as if it was--- a field assignment, and executed in validateCsv. XXX)-data ConditionalBlock = CB {-   cbMatchers    :: [Matcher]-  ,cbAssignments :: [(HledgerFieldName, FieldTemplate)]-  } deriving (Show, Eq)--dbgShowConditionalBlock :: ConditionalBlock -> String-dbgShowConditionalBlock = unwords . map dbgShowMatcher . cbMatchers--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-      maybeMemo = if length conditionalblocks >= 15 then memo else id-  in-    CsvRules' {-    rdirectives=reverse $ rdirectives rules,-    rcsvfieldindexes=rcsvfieldindexes rules,-    rassignments=reverse $ rassignments rules,-    rconditionalblocks=conditionalblocks,-    rblocksassigning = maybeMemo (\f -> filter (any ((==f).fst) . cbAssignments) conditionalblocks)-    }----- *** 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 :: (HledgerFieldName, FieldTemplate) -> CsvRulesParsed -> CsvRulesParsed-addAssignment a r = r{rassignments=a:rassignments r}--setIndexesAndAssignmentsFromList :: [CsvFieldName] -> CsvRulesParsed -> CsvRulesParsed-setIndexesAndAssignmentsFromList 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 (f, T.pack $ '%':show (i+1))--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-  _ <- many $ choice-    [blankorcommentlinep                                                <?> "blank or comment line"-    ,(directivep        >>= modify' . addDirective)                     <?> "directive"-    ,(fieldnamelistp    >>= modify' . setIndexesAndAssignmentsFromList) <?> "field name list"-    ,(fieldassignmentp  >>= modify' . addAssignment)                    <?> "field assignment"-    -- conditionalblockp backtracks because it shares "if" prefix with conditionaltablep.-    ,try (conditionalblockp >>= modify' . addConditionalBlock)          <?> "conditional block"-    -- 'reverse' is there to ensure that conditions are added in the order they listed in the file-    ,(conditionaltablep >>= modify' . addConditionalBlocks . reverse)   <?> "conditional table"-    ]-  eof-  mkrules <$> get--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"-  d <- choiceInState $ map (lift . string) directives-  v <- (((char ':' >> lift (many spacenonewline)) <|> lift (some spacenonewline)) >> directivevalp)-       <|> (optional (char ':') >> lift skipNonNewlineSpaces >> lift eolof >> return "")-  return (d, v)-  ) <?> "directive"--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]))--fieldassignmentp :: CsvRulesParser (HledgerFieldName, FieldTemplate)-fieldassignmentp = do-  lift $ dbgparse 8 "trying fieldassignmentp"-  f <- journalfieldnamep-  v <- choiceInState [ assignmentseparatorp >> fieldvalp-                     , lift eolof >> return ""-                     ]-  return (f,v)-  <?> "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 and end are not really fields, but we list it here to allow conditional rules that skip records-  ,"end"-  ]--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.pack <$> anySingle `manyTill` lift eolof---- 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-  string "if" >> ( (newline >> return Nothing)-                  <|> (lift skipNonNewlineSpaces1 >> optional newline))-  ms <- some matcherp-  as <- catMaybes <$>-    many (lift skipNonNewlineSpaces1 >>-          choice [ lift eolof >> return Nothing-                 , fmap Just fieldassignmentp-                 ])-  when (null as) $-    customFailure $ parseErrorAt start $  "start of conditional block found, but no assignment rules afterward\n(assignment rules in a conditional block should be indented)"-  return $ CB{cbMatchers=ms, cbAssignments=as}-  <?> "conditional block"---- A conditional table: "if" followed by separator, followed by some field names,--- followed by many lines, each of which is either:--- a comment line, or ...--- one matcher, followed by field assignments (as many as there were fields in the header)-conditionaltablep :: CsvRulesParser [ConditionalBlock]-conditionaltablep = do-  lift $ dbgparse 8 "trying conditionaltablep"-  start <- getOffset-  string "if"-  sep <- lift $ satisfy (\c -> not (isAlphaNum c || isSpace c))-  fields <- journalfieldnamep `sepBy1` (char sep)-  newline-  body <- catMaybes <$> (flip manyTill (lift eolof) $-          choice [ commentlinep >> return Nothing-                 , fmap Just $ bodylinep sep fields-                 ])-  when (null body) $-    customFailure $ parseErrorAt start $ "start of conditional table found, but no assignment rules afterward"-  return $ flip map body $ \(ms,vs) ->-    CB{cbMatchers=ms, cbAssignments=zip fields vs}-  <?> "conditional table"-  where-    bodylinep :: Char -> [Text] -> CsvRulesParser ([Matcher],[FieldTemplate])-    bodylinep sep fields = do-      off <- getOffset-      ms <- matcherp' (lookAhead . void . char $ sep) `manyTill` char sep-      vs <- T.split (==sep) . T.pack <$> lift restofline-      if (length vs /= length fields)-        then customFailure $ parseErrorAt off $ ((printf "line of conditional table should have %d values, but this one has only %d" (length fields) (length vs)) :: String)-        else return (ms,vs)----- 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--getDirective :: DirectiveName -> CsvRules -> Maybe FieldTemplate-getDirective 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 value template assigned to a hledger field by field--- list/field assignment rules, taking into account the current record and--- conditional rules.-hledgerField :: CsvRules -> CsvRecord -> HledgerFieldName -> Maybe FieldTemplate-hledgerField rules record f = fmap-  (either id (lastCBAssignmentTemplate f))-  (getEffectiveAssignment rules record f)---- | Look up the final value assigned to a hledger field, with csv field--- references and regular expression match group references interpolated.-hledgerFieldValue :: CsvRules -> CsvRecord -> HledgerFieldName -> Maybe Text-hledgerFieldValue rules record f = (flip fmap) (getEffectiveAssignment rules record f)-  $ either (renderTemplate rules record)-  $ \cb -> let-      t = lastCBAssignmentTemplate f cb-      r = rules { rconditionalblocks = [cb] } -- XXX handle rblocksassigning-      in renderTemplate r record t--lastCBAssignmentTemplate :: HledgerFieldName -> ConditionalBlock -> FieldTemplate-lastCBAssignmentTemplate f = snd . last . filter ((==f).fst) . cbAssignments--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--- either the last applicable `ConditionalBlock`, or the final value template--- assigned to this field by a top-level field assignment, if any exist.------ Note conditional blocks' patterns are matched against an approximation of the--- CSV record: all the field values, without enclosing quotes, comma-separated.----getEffectiveAssignment-  :: CsvRules-     -> CsvRecord-     -> HledgerFieldName-     -> Maybe (Either FieldTemplate ConditionalBlock)-getEffectiveAssignment rules record f = lastMay assignments-  where-    -- all active assignments to field f, in order-    assignments = toplevelassignments ++ conditionalassignments-    -- all top level field assignments-    toplevelassignments    = map (Left . snd) $ filter ((==f).fst) $ rassignments rules-    -- all conditional blocks assigning to field f and active for the current csv record-    conditionalassignments = map Right-                           $ filter (any (==f) . map fst . cbAssignments)-                           $ dbg'-                           $ filter (isBlockActive rules record)-                           $ (rblocksassigning rules) f--    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 -> CsvRecord -> 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 to text, for whole-record matching.--- This will be only an approximation of the original record;--- values will always be comma-separated,--- and any enclosing quotes and whitespace outside those quotes will be removed.-recordAsApproximateText :: CsvRecord -> Text-recordAsApproximateText = T.intercalate ","---- | Render a field assignment's template, possibly interpolating referenced--- CSV field values or match groups. Outer whitespace is removed from interpolated values.-renderTemplate ::  CsvRules -> CsvRecord -> FieldTemplate -> Text-renderTemplate rules record t =-  maybe t mconcat $ parseMaybe-    (many-      (   literaltextp-      <|> (matchrefp <&> replaceRegexGroupReference rules record)-      <|> (fieldrefp <&> replaceCsvFieldReference   rules record <&> fromMaybe "")-      )-    )-    t-  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 isFieldNameChar)) <?> "percent that does not begin a field reference"-    matchrefp    = liftA2 T.cons (char '\\') (takeWhile1P (Just "matchref")  isDigit)-    fieldrefp    = liftA2 T.cons (char '%')  (takeWhile1P (Just "reference") isFieldNameChar)-    isFieldNameChar c = isAlphaNum c || c == '_' || c == '-'---- | Replace something that looks like a Regex match group reference with the--- resulting match group value after applying the Regex.-replaceRegexGroupReference :: CsvRules -> CsvRecord -> MatchGroupReference -> Text-replaceRegexGroupReference rules record s = case T.uncons s of-    Just ('\\', group) -> fromMaybe "" $ regexMatchValue rules record group-    _                  -> s--regexMatchValue :: CsvRules -> CsvRecord -> 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 -> CsvRecord -> 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" or "%1)--- 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 -> CsvRecord -> CsvFieldReference -> Maybe Text-replaceCsvFieldReference rules record s = case T.uncons s of-    Just ('%', fieldname) -> csvFieldValue rules record fieldname-    _                     -> Nothing---- | Get the (whitespace-stripped) value of a CSV field, identified by its name or--- column number, ("date" or "1"), from the given CSV record, if such a field exists.-csvFieldValue :: CsvRules -> CsvRecord -> CsvFieldName -> Maybe Text-csvFieldValue rules record fieldname = do-  fieldindex <--    if T.all isDigit fieldname-    then readMay $ T.unpack fieldname-    else lookup (T.toLower fieldname) $ rcsvfieldindexes rules-  T.strip <$> atMay record (fieldindex-1)--_CSV_READING__________________________________________ = undefined---- | 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.----readJournalFromCsv :: CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO Journal-readJournalFromCsv 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 and remove all empty/blank lines-    let csvlines1 = dbg9 "csvlines1" $ filter (not . T.null . T.strip) $ dbg9 "csvlines0" $ T.lines csvtext--    -- if there is a top-level skip rule, skip the specified number of non-empty lines-    skiplines <- case getDirective "skip" rules of-                      Nothing -> return 0-                      Just "" -> return 1-                      Just s  -> maybe (throwError $ "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 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-    -- remove any records skipped by conditional skip or end rules-    let csvrecords1 = applyConditionalSkips rules csvrecords0-    -- and check the remaining records for any obvious problems-    csvrecords <- liftEither $ dbg7 "validateCsv" <$> validateCsv csvrecords1-    dbg6IO "first 3 csv records" $ take 3 csvrecords--    -- 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 $ "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" $ snd $ mapAccumL-                     (\pos r ->-                        let-                          SourcePos name line col = pos-                          line' = (mkPos . (+1) . unPos) line-                          pos' = SourcePos name line' col-                        in-                          (pos', transactionFromCsvRecord timesarezoned mtzin tzout pos rules r)-                     )-                     (initialPos parsecfilename) csvrecords-        where-          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--    return nulljournal{jtxns=txns3}---- | 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---- | Scan for csv records where a conditional `skip` or `end` rule applies,--- and apply that rule, removing one or more following records.-applyConditionalSkips :: CsvRules -> [CsvRecord] -> [CsvRecord]-applyConditionalSkips _ [] = []-applyConditionalSkips rules (r:rest) =-  case skipnum r of-    Nothing -> r : applyConditionalSkips rules rest-    Just cnt -> applyConditionalSkips rules $ drop (cnt-1) rest-  where-    skipnum r1 =-      case (hledgerField rules r1 "end", hledgerField rules r1 "skip") of-        (Nothing, Nothing) -> Nothing-        (Just _, _) -> Just maxBound-        (Nothing, Just "") -> Just 1-        (Nothing, Just x) -> Just (read $ T.unpack x)---- | Do some validation on the parsed CSV records:--- check that they all have at least two fields.-validateCsv :: [CsvRecord] -> Either String [CsvRecord]-validateCsv [] = Right []-validateCsv rs@(_first:_) =-  case lessthan2 of-    Just r  -> Left $ printf "CSV record %s has less than two fields" (show r)-    Nothing -> Right rs-  where-    lessthan2 = headMay $ filter ((<2).length) rs---- -- | 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 -> SourcePos -> CsvRules -> CsvRecord -> Transaction-transactionFromCsvRecord timesarezoned mtzin tzout sourcepos 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:--    rule     = csvRule           rules        :: DirectiveName    -> Maybe FieldTemplate-    -- ruleval  = csvRuleValue      rules record :: DirectiveName    -> Maybe String-    field    = hledgerField      rules record :: HledgerFieldName -> Maybe FieldTemplate-    fieldval = hledgerFieldValue rules record :: HledgerFieldName -> Maybe Text-    mdateformat = rule "date-format"-    parseDate = parseDateWithCustomOrDefaultFormats timesarezoned mtzin tzout mdateformat-    mkdateerror datefield datevalue mdateformat' = T.unpack $ 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'-      ,showRecord record-      ,"the "<>datefield<>" rule is:   "<>(fromMaybe "required, but missing" $ field datefield)-      ,"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 $ T.unlines-              ["could not parse status value \""<>s<>"\" (should be *, ! or empty)"-              ,"the parse error is:      "<>T.pack (customErrorBundlePretty err)-              ]-    code        = maybe "" singleline' $ fieldval "code"-    description = maybe "" singleline' $ fieldval "description"-    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-    precomment  = maybe "" unescapeNewlines $ fieldval "precomment"--    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 rules record currency p1IsVirtual n-         ,let mbalance = getBalance rules record currency n-         ,Just (acct,isfinal) <- [getAccount 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 rules record <$> mbalance-                             ,pcomment          = cmt-                             ,ptags             = tags-                             ,ptype             = accountNamePostingType acct-                             }-         ]--    -----------------------------------------------------------------------    -- 4. Build the transaction (and name it, so the postings can reference it).--    t = nulltransaction{-           tsourcepos        = (sourcepos, sourcepos)  -- the CSV line number-          ,tdate             = date'-          ,tdate2            = mdate2'-          ,tstatus           = status-          ,tcode             = code-          ,tdescription      = description-          ,tcomment          = comment-          ,ttags             = ttags-          ,tprecedingcomment = precomment-          ,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 :: CsvRules -> CsvRecord -> Text -> Bool -> Int -> Maybe MixedAmount-getAmount 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 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 . textChomp . T.unlines $-        ["in CSV rules:"-        ,"While processing " <> showRecord record-        ,"while calculating amount for posting " <> T.pack (show n)-        ] ++-        ["rule \"" <> f <> " " <>-          fromMaybe "" (hledgerField rules record f) <>-          "\" assigned value \"" <> wbToText (showMixedAmountB defaultFmt a) <> "\"" -- XXX not sure this is showing all the right info-          | (f,a) <- fs-        ] ++-        [""-        ,"Multiple non-zero amounts were assigned for an amount field."-        ,"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 (and its parse position).-getBalance :: CsvRules -> CsvRecord -> Text -> Int -> Maybe (Amount, SourcePos)-getBalance 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 rules record currency n s-           ,initialPos ""  -- parse position to show when assertion fails,-           )               -- XXX the csv record's line number would be good-  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 symbol to prepend,--- parse as a hledger MixedAmount (as in journal format), or raise an error.--- The whole CSV record is provided for the error message.-parseAmount :: CsvRules -> CsvRecord -> Text -> Text -> MixedAmount-parseAmount rules record currency s =-    either mkerror mixedAmount $-    runParser (evalStateT (amountp <* eof) journalparsestate) "" $-    currency <> simplifySign s-  where-    journalparsestate = nulljournal{jparsedecimalmark=parseDecimalMark rules}-    mkerror e = error' . T.unpack $ T.unlines-      ["could not parse \"" <> s <> "\" as an amount"-      ,showRecord 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 $ catMaybes-  [ (("the "<>fld<>" rule is: ")<>) <$>-    hledgerField rules record fld | fld <- journalfieldnames ]---- 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 :: CsvRules -> CsvRecord -> Text -> Int -> Text -> Amount-parseBalanceAmount rules record currency n s =-  either (mkerror n s) id $-    runParser (evalStateT (amountp <* eof) journalparsestate) "" $-    currency <> simplifySign s-                  -- the csv record's line number would be good-  where-    journalparsestate = nulljournal{jparsedecimalmark=parseDecimalMark rules}-    mkerror n' s' e = error' . T.unpack $ T.unlines-      ["could not parse \"" <> s' <> "\" as balance"<> T.pack (show n') <> " amount"-      ,showRecord record-      ,showRules rules record-      -- ,"the default-currency is: "++fromMaybe "unspecified" mdefaultcurrency-      ,"the parse error is:      "<> T.pack (customErrorBundlePretty e)-      ]---- | Show the approximation of the original CSV record, labelled, for debug output.-showRecord :: CsvRecord -> Text-showRecord = ("record: "<>) . recordAsApproximateText---- 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 <- 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).-mkBalanceAssertion :: CsvRules -> CsvRecord -> (Amount, SourcePos) -> BalanceAssertion-mkBalanceAssertion rules record (amt, pos) = assrt{baamount=amt, baposition=pos}-  where-    assrt =-      case getDirective "balance-type" rules of-        Nothing -> nullassertion-        Just x  ->-          case parseBalanceAssertionType $ T.unpack x of-            Just (total, inclusive) -> nullassertion{batotal=total, bainclusive=inclusive}-            Nothing -> error' . T.unpack $ T.unlines  -- PARTIAL:-              [ "balance-type \"" <> x <>"\" is invalid. Use =, ==, =* or ==*."-              , showRecord 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).-getAccount :: CsvRules -> CsvRecord -> Maybe MixedAmount -> Maybe (Amount, SourcePos) -> Int -> Maybe (AccountName, Bool)-getAccount 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  -> usageError $ errorBundlePretty e-        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---- | 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 = [("account1","")], rconditionalblocks = [CB{cbMatchers=[RecordMatcher Or (toRegex' "foo")],cbAssignments=[("account2","foo")]}]}))-   ]-  ,testGroup "conditionalblockp" [-    testCase "space after conditional" $-      parseWithState' defrules conditionalblockp "if a\n account2 b\n \n" @?=-        (Right $ CB{cbMatchers=[RecordMatcher Or $ toRegexCI' "a"],cbAssignments=[("account2","b")]})-  ],--  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 = [("account2", "foo"), ("comment2", "bar")]-        block = CB matchers assignments-    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=[("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"] [("date","%csvdate")]]}-    in testCase "conditional" $ hledgerField rules ["a","b"] "date" @?= (Just "%csvdate")--   ,let rules = mkrules $ defrules{rcsvfieldindexes=[("csvdate",1)], rconditionalblocks=[CB [FieldMatcher Not "%csvdate" $ toRegex' "a"] [("date","%csvdate")]]}-    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"] [("date","%csvdate")]]}-    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"] [("date","%csvdate")]]}-    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"] [("date","%csvdate")]]}-    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"] [("date","%csvdate")]]}-    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"] [("date","%csvdate")]]}-    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=[ ("account2","equity"), ("amount1","1") ]-          -- ConditionalBlocks here are in reverse order: mkrules reverses the list-          , rconditionalblocks=[ CB { cbMatchers=[FieldMatcher Or "%description" (toRegex' "PREFIX (.*) - (.*)")]-                                    , cbAssignments=[("account1","account:\\1:\\2")] }-                               , CB { cbMatchers=[FieldMatcher Or "%description" (toRegex' "PREFIX (.*)")]-                                    , cbAssignments=[("account1","account:\\1"), ("comment1","\\1")] }-                               ]-          }-        record = ["2019-02-01","PREFIX Text 1 - Text 2"]+{-# 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
@@ -142,6 +142,7 @@ 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)@@ -241,8 +242,10 @@       -- 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.-      a <- optional (try $ lift skipNonNewlineSpaces1 >> modifiedaccountnamep False) <&> fromMaybe ""+      -- 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
Hledger/Read/TimedotReader.hs view
@@ -52,7 +52,6 @@ import Hledger.Data import Hledger.Read.Common import Hledger.Utils-import Data.Decimal (roundTo) import Data.Functor ((<&>)) import Data.List (sort) import Data.List (group)@@ -109,10 +108,28 @@ 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 $ notFollowedBy datelinep >> (lift $ emptyorcommentlinep2 "#;*")+  void $ many $ do+    notFollowedBy datelineattemptp+    lift $ emptyorcommentlinep2 "#;*"  -- | Parse timedot day entries to multi-posting time transactions for that day. -- @@@ -167,14 +184,15 @@  orgheadingprefixp = skipSome (char '*') >> skipNonNewlineSpaces1 --- | Parse a single timedot entry to one (dateless) transaction.+-- | 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 datelinep+  notFollowedBy datelineattemptp   lift $ optional $ choice [orgheadingprefixp, skipNonNewlineSpaces1]   a <- modifiedaccountnamep False   lift skipNonNewlineSpaces@@ -190,7 +208,7 @@     ps = [       nullposting{paccount=a                 ,pamount=mixedAmount $ nullamt{acommodity=c, aquantity=hours, astyle=s}-                ,ptype=VirtualPosting+                ,preal=VirtualPosting                 ,pcomment=comment                 ,ptags=tags                 }@@ -227,24 +245,19 @@   (q, _, _, _) <- numberp Nothing   msymbol <- optional $ choice $ map (string . fst) timeUnits   skipNonNewlineSpaces-  let q' =-        case msymbol of-          Nothing  -> q-          Just sym -> roundTo 2 $-            case lookup sym timeUnits of-              Just mult -> q * mult-              Nothing   -> q  -- shouldn't happen.. ignore-  return q'+  return $ maybe q ($ q) $ msymbol >>= (`lookup` timeUnits) --- (symbol, equivalent in hours).+-- (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",2.777777777777778e-4)-  ,("mo",5040) -- before "m"-  ,("m",1.6666666666666666e-2)-  ,("h",1)-  ,("d",24)-  ,("w",168)-  ,("y",61320)+  [("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,
Hledger/Reports/AccountTransactionsReport.hs view
@@ -10,8 +10,10 @@   AccountTransactionsReport,   AccountTransactionsReportItem,   accountTransactionsReport,+  accountTransactionsReportWithStart,   accountTransactionsReportItems,   transactionRegisterDate,+  transactionRegisterDateExtra,   triOrigTransaction,   triDate,   triAmount,@@ -19,19 +21,22 @@   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)+import Data.Maybe (catMaybes, fromMaybe) import Data.Ord (Down(..), comparing) import Data.Text qualified as T-import Data.Time.Calendar (Day)+import Data.Time.Calendar (Day, fromGregorian)  import Hledger.Data import Hledger.Query+import Hledger.Reports.PostingsReport (registerRunningCalculationFn) import Hledger.Reports.ReportOptions import Hledger.Utils @@ -62,7 +67,9 @@ -- - 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 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@@ -81,7 +88,7 @@   ,Bool        -- is this a split (more than one posting to other accounts) ?   ,[AccountName] -- the other account(s), if any   ,MixedAmount -- the amount posted to the current account(s) (or total amount posted)-  ,MixedAmount -- the register's running total or the current account(s)'s historical balance, after this transaction+  ,MixedAmount -- the register's running total or the current account(s)'s historical balance (or running average), after this transaction   )  instance HasAmounts AccountTransactionsReportItem where@@ -96,7 +103,15 @@ triCommodityBalance c = filterMixedAmountByCommodity c  . triBalance  accountTransactionsReport :: ReportSpec -> Journal -> Query -> AccountTransactionsReport-accountTransactionsReport rspec@ReportSpec{_rsReportOpts=ropts} j thisacctq = items+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.@@ -105,7 +120,7 @@         aregisterq = filterQuery (not . queryIsCurOrAmt) . filterQuery (not . queryIsDepth) $ _rsQuery rspec         periodq = Date . periodAsDateSpan $ period_ ropts     amtq = filterQuery queryIsCurOrAmt $ _rsQuery rspec-    queryIsCurOrAmt q = queryIsSym q || queryIsAmt q+    queryIsCurOrAmt q = queryIsCur q || queryIsAmt q     wd = whichDate ropts      -- Note that within this function, we are only allowed limited@@ -142,25 +157,37 @@         realq   = filterQuery queryIsReal reportq         statusq = filterQuery queryIsStatus reportq -    startbal-      | balanceaccum_ ropts == Historical = sumPostings priorps-      | otherwise                         = nullmixedamt+    -- 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-        priorps = dbg5 "priorps" . filter hasAmount . journalPostings $ filterJournalPostings priorq acctJournal-        priorq = dbg5 "priorq" $ And [thisacctq, tostartdateq, datelessreportq]-        tostartdateq =-          case mstartdate of-            Just _  -> Date (DateSpan Nothing (Exact <$> mstartdate))-            Nothing -> None  -- no start date specified, there are no prior postings-        mstartdate = queryStartDate (date2_ ropts) reportq+        -- 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 thisacctq startbal maNegate (journalAccountType j)+        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 -> (transactionRegisterDate wd reportq thisacctq t, t))+      . 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 @@ -168,26 +195,33 @@ 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, a query specifying--- which account to use as the focus, a starting balance, and a sign-setting--- function.+-- 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 -> MixedAmount -> (MixedAmount -> MixedAmount)+accountTransactionsReportItems :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount)+                               -> Int -> MixedAmount -> MixedAmount -> (MixedAmount -> MixedAmount)                                -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)]                                -> [AccountTransactionsReportItem]-accountTransactionsReportItems reportq thisacctq bal signfn accttypefn =-    catMaybes . snd . mapAccumR (accountTransactionsReportItem reportq thisacctq signfn accttypefn) bal+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 -> (MixedAmount -> MixedAmount)-                              -> (AccountName -> Maybe AccountType) -> MixedAmount -> (Day, Transaction)-                              -> (MixedAmount, Maybe AccountTransactionsReportItem)-accountTransactionsReportItem reportq thisacctq signfn accttypefn bal (d, t)+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 = (bal, Nothing)  -- no matched postings in this transaction, skip it-    | otherwise     = (bal', Just (t, tacct{tdate=d}, numotheraccts > 1, otheraccts, amt, bal'))+    | 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@@ -202,7 +236,8 @@       amt         | null thisacctps = signfn $ sumPostings otheracctps         | otherwise       = signfn . maNegate $ sumPostings thisacctps-      bal' = bal `maPlus` amt+      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 ?@@ -215,11 +250,17 @@ -- - the transaction date, or its secondary date if --date2 was used. -- transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day-transactionRegisterDate wd reportq thisacctq t+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 $ filterTransactionPostings reportq t+    reportps   = tpostings $ filterTransactionPostingsExtra accttypefn reportq t     thisacctps = filter (matchesPosting thisacctq) reportps  -- -- | Generate a short readable summary of some postings, like@@ -278,4 +319,30 @@ -- 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/BudgetReport.hs view
@@ -20,6 +20,7 @@ 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@@ -27,6 +28,7 @@ import Safe (minimumDef)  import Hledger.Data+import Hledger.Query import Hledger.Utils import Hledger.Reports.ReportOptions import Hledger.Reports.ReportTypes@@ -81,8 +83,14 @@     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 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;@@ -91,18 +99,55 @@         (_,    Nothing) -> actualspans         (_, Just bspan) -> unionDayPartitions bspan =<< actualspans -    actualps = dbg5 "actualps" $ getPostings rspec actualj priceoracle reportspan-    budgetps = dbg5 "budgetps" $ getPostings rspec budgetj priceoracle reportspan+    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 rspec actualj priceoracle actualspans actualps-    budgetAcct = dbg5 "budgetAcct" $ generateMultiBalanceAccount rspec budgetj priceoracle budgetspans budgetps+    actualAcct = dbg5 "actualAcct" $ generateMultiBalanceAccount actualrspec actualj priceoracle actualspans actualps+    budgetAcct = dbg5 "budgetAcct" $ generateMultiBalanceAccount budgetrspec budgetj priceoracle budgetspans budgetps -    combinedAcct = dbg5 "combinedAcct" $ if null 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
Hledger/Reports/EntriesReport.hs view
@@ -11,6 +11,7 @@   EntriesReport,   EntriesReportItem,   entriesReport,+  entriesReportUnsorted,   -- * Tests   tests_EntriesReport )@@ -21,7 +22,7 @@ import Data.Time (fromGregorian)  import Hledger.Data-import Hledger.Query (Query(..), filterQuery, queryIsDepth)+import Hledger.Query (Query(..), filterQuery, matchesRowAmounts, queryIsDepth, queryIsNull) import Hledger.Reports.ReportOptions import Hledger.Utils @@ -32,14 +33,22 @@ type EntriesReport = [EntriesReportItem] type EntriesReportItem = Transaction --- | Select transactions for an entries report.+-- | Select transactions for an entries report, sorted by date. entriesReport :: ReportSpec -> Journal -> EntriesReport entriesReport rspec@ReportSpec{_rsReportOpts=ropts} =-      sortBy (comparing $ transactionDateFn ropts)-    . map  (if invert_ ropts then transactionNegate else id)+  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" [
Hledger/Reports/MultiBalanceReport.hs view
@@ -24,10 +24,13 @@    -- * Helper functions   makeReportQuery,+  balanceReportStyles,   getPostings,+  accountRowAmounts,   generateMultiBalanceAccount,   generatePeriodicReport,   makePeriodicReportRow,+  rowTotal,    -- -- * Tests   tests_MultiBalanceReport@@ -38,9 +41,13 @@ 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)@@ -147,7 +154,12 @@             -- XXX in non-thorough way, consider updateReportSpec ?             rspecsub = rspec{_rsReportOpts=ropts, _rsQuery=And [cbcsubreportquery, _rsQuery rspec]}             -- Match and postings for the subreport-            subreportps = filter (matchesPostingExtra (journalAccountType j) cbcsubreportquery) ps+            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 @@ -155,13 +167,16 @@     -- - 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 then id else fmap maNegate) $ prTotals sr+            (if increasestotal || counting then id else fmap maNegate) $ prTotals sr +    counting = balanceCalcIsCount $ balancecalc_ (_rsReportOpts rspec)+     cbr = CompoundPeriodicReport "" (maybeDayPartitionToDateSpans colspans) subreports overalltotals  @@ -181,22 +196,22 @@  -- | Gather postings matching the query within the report period. getPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting]-getPostings rspec@ReportSpec{_rsQuery=query, _rsReportOpts=ropts} j priceoracle reportspan =+getPostings rspec@ReportSpec{_rsQuery=query, _rsRowQuery=rowq, _rsReportOpts=ropts} j priceoracle reportspan =     setPostingsCount-    . filter hasAmount  -- omit postings with no definite amount+    . filter hasAmount  -- omit postings with no definite amount (#2571)     . journalPostings     $ journalValueAndFilterPostingsWith rspec' j priceoracle   where-    -- If doing --count, set all posting amounts to "1".-    setPostingsCount = case balancecalc_ ropts of-        CalcPostingsCount -> map (postingTransformAmount (const $ mixed [num 1]))-        _                 -> id+    -- 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, conversionop_=Just NoConversionOp}  -- If we're valuing after the sum, don't do it now+        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.@@ -210,7 +225,8 @@     -- handles the hledger-ui+future txns case above).     depthlessq = dbg3 "getPostings depthlessq" $ filterQuery (not . queryIsDepth) query -    fullreportspan  = if requiresHistorical ropts then DateSpan Nothing (Exact <$> spanEnd reportspan) else reportspan+    -- 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@@ -223,15 +239,20 @@     mapAccounts (accountSetDeclarationInfo j)     -- Add declared accounts if called with --declared and --empty     . (if (declared_ ropts && empty_ ropts) then addDeclaredAccounts rspec j else id)-    -- Negate amounts if applicable-    . (if invert_ ropts then fmap (mapBalanceData maNegate) 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"@@ -251,6 +272,8 @@     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" .@@ -286,6 +309,7 @@             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@@ -311,9 +335,43 @@     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,_rsReportOpts=ropts}+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@@ -326,7 +384,8 @@       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 && keepWhenEmpty acct      -- We are keeping empty rows and this row meets the criteria+        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@@ -345,12 +404,18 @@         notEnoughSubs = length interestingSubs < minimumSubs         droppedAccount = accountNameLevel (aname acct) <= drop_ ropts         interestingSubs = filter (anyAccounts (not . aboring)) $ asubs acct-        minimumSubs = if no_elide_ ropts then 1 else 2+        minimumSubs = if no_elide_ ropts || atFoldDepth then 1 else 2+        atFoldDepth = fold_depth_ ropts == Just (accountNameLevel (aname acct))      isZeroRow balance = all (mixedAmountLooksZero . balance)-    keepWhenEmpty = case accountlistmode_ ropts of-        ALFlat -> any ((0<) . bdnumpostings) . pdperiods . adata  -- Keep all accounts that have postings in flat mode-        ALTree -> null . asubs                                    -- Keep only empty leaves in tree mode+    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) []@@ -365,8 +430,22 @@ -- Calculate the column totals. These are always the sum of column amounts. generateMultiBalanceReport :: ReportOpts -> Maybe DayPartition -> Account BalanceData -> MultiBalanceReport generateMultiBalanceReport ropts colspans =-    reportPercent ropts . generatePeriodicReport makeMultiBalanceReportRow bdincludingsubs id 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.@@ -463,10 +542,14 @@   where     rowbals = fmap balance . pdperiods $ adata acct     (total, avg) = totalAndAverage rowbals-    -- Total for a cumulative/historical report is always the last column.-    rowtotal = case balanceaccum_ ropts of-        PerPeriod -> total-        _         -> maybe nullEntry snd $ M.lookupMax 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
Hledger/Reports/PostingsReport.hs view
@@ -9,12 +9,15 @@ {-# LANGUAGE RecordWildCards     #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections       #-}+{-# LANGUAGE BangPatterns        #-}  module Hledger.Reports.PostingsReport (   PostingsReport,   PostingsReportItem,   postingsReport,+  postingsReportStartBalances,   mkpostingsReportItem,+  registerRunningCalculationFn,   SortSpec,   defsortspec, @@ -23,8 +26,8 @@ ) where -import Data.List (nub, sortBy, sortOn)-import Data.List.Extra (nubSort)+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)@@ -69,7 +72,7 @@ postingsReport :: ReportSpec -> Journal -> PostingsReport postingsReport rspec@ReportSpec{_rsReportOpts=ropts@ReportOpts{..}} j = items     where-      (reportspan, colspans) = reportSpanBothDates j rspec+      (reportspan, colspans) = reportSpanBothDatesLazy j rspec       whichdate   = whichDate ropts       depthSpec   = queryDepth $ _rsQuery rspec       multiperiod = interval_ /= NoInterval@@ -78,20 +81,34 @@       (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]+        | otherwise   = [(p', Nothing) | p' <- reportps, showempty || not (mixedAmountLooksZero $ pamount p')]         where-          summariseps = summarisePostingsByInterval whichdate (dsFlatDepth depthSpec) showempty colspans+          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.+      -- 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 postings (nullposting,Nothing) whichdate depthSpec startbal runningcalc startnum+        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".@@ -99,9 +116,8 @@           historical = balanceaccum_ == Historical           startbal | average_  = if historical then precedingavg else nullmixedamt                    | otherwise = if historical then precedingsum else nullmixedamt-            where-              precedingsum = sumPostings precedingps-              precedingavg = divideMixedAmount (fromIntegral $ length precedingps) precedingsum+          precedingsum = sumPostings precedingps+          precedingavg = divideMixedAmount (fromIntegral $ length precedingps) precedingsum            runningcalc = registerRunningCalculationFn ropts           startnum = if historical then length precedingps + 1 else 1@@ -110,6 +126,18 @@                         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,@@ -159,7 +187,7 @@     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+      . 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@@ -180,20 +208,24 @@         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.-postingsReportItems :: [(Posting,Maybe Period)] -> (Posting,Maybe Period) -> WhichDate -> DepthSpec -> MixedAmount -> (Int -> MixedAmount -> MixedAmount -> MixedAmount) -> Int -> [PostingsReportItem]-postingsReportItems [] _ _ _ _ _ _ = []-postingsReportItems ((p,mperiod):ps) (pprev,mperiodprev) wd d b runningcalcfn itemnum =-    i:(postingsReportItems ps (p,mperiod) wd d b' runningcalcfn (itemnum+1))+-- 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'+    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-    p' = p{paccount= clipOrEllipsifyAccountName d $ paccount p}-    b' = runningcalcfn itemnum b $ pamount p+    -- 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@@ -210,45 +242,38 @@ -- | 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 -> Maybe Int -> Bool -> Maybe DayPartition -> [Posting] -> [SummaryPosting]-summarisePostingsByInterval wd mdepth showempty colspans =-    concatMap (\(s,ps) -> summarisePostingsInDateSpan s wd mdepth showempty ps)+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)-    . groupByDateSpan showempty (postingDateOrDate2 wd) (maybeDayPartitionToDateSpans colspans)+    -- 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. Each summary posting will have a non-Nothing interval end date.+-- account, sorted by account name. Each summary posting will have a non-Nothing interval end date. ----- When a depth argument is present, postings to accounts of greater--- depth are also aggregated where possible. If the depth is 0, all--- postings in the span are aggregated into a single posting with--- account name "...".+-- 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 -> Maybe Int -> Bool -> [Posting] -> [SummaryPosting]-summarisePostingsInDateSpan spn@(DateSpan b e) wd mdepth showempty ps+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, dateSpanAsPeriod spn)]+  | 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'}-    clippedanames = nub $ map (clipAccountName (DepthSpec mdepth [])) anames-    summaryps | mdepth == Just 0 = [summaryp{paccount="...",pamount=sumPostings ps}]-              | otherwise        = [summaryp{paccount=a,pamount=balance a} | a <- clippedanames]+    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-    anames = nubSort $ map paccount ps-    -- aggregate balances by account, like ledgerFromJournal, then do depth-clipping-    accts = accountsFromPostings (const Nothing) ps-    balance a = maybe nullmixedamt bal $ lookupAccount a accts-      where-        bal = (if isclipped a then bdincludingsubs else bdexcludingsubs) . pdpre . adata-        isclipped a' = maybe False (accountNameLevel a' >=) mdepth   -- tests@@ -417,7 +442,7 @@     -}    ,testCase "summarisePostingsByInterval" $-    summarisePostingsByInterval PrimaryDate Nothing False Nothing [] @?= []+    summarisePostingsByInterval PrimaryDate mempty False [] [] @?= []    -- ,tests_summarisePostingsInDateSpan = [     --  "summarisePostingsInDateSpan" ~: do
Hledger/Reports/ReportOptions.hs view
@@ -4,6 +4,7 @@  -} +{-# LANGUAGE BangPatterns          #-} {-# LANGUAGE FlexibleContexts      #-} {-# LANGUAGE FlexibleInstances     #-} {-# LANGUAGE LambdaCase            #-}@@ -27,10 +28,13 @@   overEither,   setEither,   BalanceCalculation(..),+  balanceCalcIsCount,   BalanceAccumulation(..),   AccountListMode(..),   ValuationType(..),   Layout(..),+  PeriodTitles(..),+  effectiveTitle,   defreportopts,   rawOptsToReportOpts,   defreportspec,@@ -54,11 +58,14 @@   valuationAfterSum,   requiresHistorical,   intervalFromRawOpts,+  intervalFromQueryOpts,   queryFromFlags,   transactionDateFn,   postingDateFn,   reportSpan,   reportSpanBothDates,+  reportSpanLazy,+  reportSpanBothDatesLazy,   reportStartDate,   reportEndDate,   reportPeriodStart,@@ -77,13 +84,14 @@ import Data.Either.Extra (eitherToMaybe) import Data.Functor.Identity (Identity(..)) import Data.List (partition)-import Data.List.Extra (find, isPrefixOf, nubSort, stripPrefix)+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@@ -97,10 +105,15 @@   | 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 =@@ -120,9 +133,15 @@ 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@@ -135,10 +154,28 @@     ,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_            :: 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-    ,no_elide_         :: Bool+    ,full_names_       :: Bool     ,real_             :: Bool     ,format_           :: StringFormat     ,balance_base_url_ :: Maybe T.Text@@ -183,6 +220,18 @@       --   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@@ -196,9 +245,11 @@     , value_            = Nothing     , infer_prices_     = False     , depth_            = DepthSpec Nothing []+    , fold_depth_       = Nothing+    , no_elide_         = False     , date2_            = False     , empty_            = False-    , no_elide_         = False+    , full_names_       = False     , real_             = False     , format_           = def     , balance_base_url_ = Nothing@@ -225,6 +276,10 @@     , 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.@@ -236,39 +291,54 @@ 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-        pretty = fromMaybe False $ ynopt "pretty" rawopts -        format = case parseStringFormat <$> formatstring of+        !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_           = periodFromRawOpts d rawopts-          ,interval_         = intervalFromRawOpts rawopts+          {period_           = period+          ,interval_         = interval           ,statuses_         = statusesFromRawOpts rawopts-          ,conversionop_     = conversionOpFromRawOpts rawopts-          ,value_            = valuationTypeFromRawOpts rawopts+          ,conversionop_     = conversionop+          ,value_            = value           ,infer_prices_     = boolopt "infer-market-prices" rawopts-          ,depth_            = depthFromRawOpts rawopts+          ,depth_            = depth+          ,no_elide_         = boolopt "no-elide" rawopts           ,date2_            = boolopt "date2" rawopts           ,empty_            = boolopt "empty" rawopts-          ,no_elide_         = boolopt "no-elide" 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_         = getSortSpec rawopts+          ,sortspec_         = sortspec           ,txn_dates_        = boolopt "txn-dates" rawopts           ,balancecalc_      = balancecalcopt rawopts           ,balanceaccum_     = balanceaccumopt rawopts           ,budgetpat_        = maybebudgetpatternopt rawopts           ,accountlistmode_  = accountlistmodeopt rawopts-          ,drop_             = posintopt "drop" rawopts+          ,drop_             = drop_n           ,declared_         = boolopt "declared" rawopts           ,row_total_        = boolopt "row-total" rawopts           ,no_total_         = boolopt "no-total" rawopts@@ -279,8 +349,11 @@           ,invert_           = boolopt "invert" rawopts           ,pretty_           = pretty           ,color_            = usecoloronstdout-          ,transpose_        = boolopt "transpose" rawopts+          ,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 @@ -294,7 +367,9 @@ 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+  , _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) @@ -305,6 +380,7 @@     { _rsReportOpts = def     , _rsDay        = nulldate     , _rsQuery      = Any+    , _rsRowQuery   = Any     , _rsQueryOpts  = []     } @@ -321,6 +397,23 @@       "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"@@ -374,6 +467,7 @@                      , ("tall", LayoutTall)                      , ("bare", LayoutBare)                      , ("tidy", LayoutTidy)+                     , ("barewide", LayoutBareWide)                      ]         -- For `--layout=elided,n`, elide to the given width         (s,n) = break (==',') $ map toLower opt@@ -382,7 +476,7 @@               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\", or \"tidy\""+        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.@@ -416,7 +510,7 @@       | n == "period" =         case           either (\e -> usageError $ "could not parse period option: "++customErrorBundlePretty e) id $-          parsePeriodExpr d' (stripquotes $ T.pack v)+          parsePeriodExpr d' (textStripQuotes $ T.pack v)         of           (_, DateSpan (Just b) _) -> Just b           _                        -> Nothing@@ -434,7 +528,7 @@       | n == "period" =         case           either (\e -> usageError $ "could not parse period option: "++customErrorBundlePretty e) id $-          parsePeriodExpr d' (stripquotes $ T.pack v)+          parsePeriodExpr d' (textStripQuotes $ T.pack v)         of           (_, DateSpan _ (Just e)) -> Just e           _                        -> Nothing@@ -453,7 +547,7 @@             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-              (stripquotes $ T.pack v)+              (textStripQuotes $ T.pack v)       | n == "daily"     = Just $ Days 1       | n == "weekly"    = Just $ Weeks 1       | n == "monthly"   = Just $ Months 1@@ -517,23 +611,25 @@     directval = lastMay $ collectopts valuationfromrawopt rawopts     valuationfromrawopt (n,v)  -- option name, value       | n == "V"     = Just $ AtEnd Nothing-      | n == "X"     = Just $ AtEnd (Just $ T.pack v)+      | n == "X"     = Just $ AtEnd (Just $ commodityarg v)       | n == "value" = valueopt v       | otherwise    = Nothing     valueopt v-      | t `elem` ["cost","c"]  = AtEnd . Just <$> mc  -- keep supporting --value=cost,COMM for now+      | 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: then|end|now|t|e|n|YYYY-MM-DD"+            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]+        -- parse --value's value: TYPE[,COMM]. A comma with nothing after it selects the no-symbol commodity.         (t,c') = break (==',') v-        mc     = case drop 1 c' of+        mc     = case c' of                    "" -> Nothing-                   c  -> Just $ T.pack c+                   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@@ -548,6 +644,7 @@     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@@ -562,7 +659,7 @@     (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 $ "Unable to parse depth specification: " ++ err+      Left err -> usageError err     depths = listofstringopt "depth" rawopts  -- | Select the Transaction date accessor based on --date2.@@ -623,8 +720,8 @@ --   where --     -- with -r, replace each posting with its sibling postings --     filterJournalPostings' = if related_ ropts then filterJournalRelatedPostings else filterJournalPostings---     amtsymq = dbg1 "amtsymq" $ filterQuery queryIsAmtOrSym q---     reportq = dbg1 "reportq" $ filterQuery (not . queryIsAmtOrSym) q+--     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,@@ -639,7 +736,7 @@   journalApplyValuationFromOptsWith rspec . filterjournal q   where     filterjournal q2 =-      filterJournalAmounts (filterQuery queryIsAmtOrSym q2) .  -- an extra amount filtering pass for #2396+      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@@ -681,8 +778,14 @@     postingperiodend = postingPeriodEnd . postingDateOrDate2 (whichDate ropts)       where         postingPeriodEnd d = fromMaybe err $ case interval_ ropts of-          NoInterval -> fmap (snd . dayPartitionStartEnd)    . snd $ reportSpan j rspec-          _          -> fmap (snd . dayPartitionFind d) . snd $ reportSpanBothDates j rspec+          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"@@ -695,18 +798,12 @@ mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle                                               -> (Day -> MixedAmount -> MixedAmount) mixedAmountApplyValuationAfterSumFromOptsWith ropts j priceoracle =-    case valuationAfterSum ropts of-        Just mc -> case balancecalc_ ropts of-            CalcGain -> gain mc-            _        -> \d -> valuation mc d . costing-        Nothing      -> const id-  where-    valuation mc d = mixedAmountValueAtDate priceoracle styles mc d-    gain mc d = mixedAmountGainAtDate priceoracle styles mc d-    costing = case fromMaybe NoConversionOp $ conversionop_ ropts of-        NoConversionOp -> id-        ToCost         -> styleAmounts styles . mixedAmountCost-    styles = journalCommodityStyles j+  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,@@ -797,9 +894,53 @@ reportSpanBothDates = reportSpanHelper True  reportSpanHelper :: Bool -> Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)-reportSpanHelper bothdates j ReportSpec{_rsQuery=query, _rsReportOpts=ropts, _rsDay=today} =+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@@ -819,21 +960,9 @@                 mlatestnonfutureprice = dbg3 "latestnonfutureprice" $ -- #2445                   fmap (Exact . addDays 1) . maximumMay . filter (not . (> today)) . map pddate $ jpricedirectives j -    -- 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-      where-        -- 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--    -- 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)+    -- 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@@ -883,14 +1012,16 @@ -- - 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 in the current locale+--   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 :: BalanceAccumulation -> [DateSpan] -> DateSpan -> T.Text-reportPeriodName balanceaccumulation spans =-  case balanceaccumulation of-    PerPeriod -> if multiyear then showDateSpan else showDateSpanAbbrev+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@@ -943,7 +1074,7 @@ -- >>> _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:\n(assets"+-- 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@@ -1002,10 +1133,12 @@     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      = simplifyQuery $ And [queryFromFlags ropts', argsquery]+      , _rsQuery      = query+      , _rsRowQuery   = rowq       , _rsQueryOpts  = queryopts       } 
Hledger/Utils.hs view
@@ -89,6 +89,7 @@ import Lens.Micro.TH (DefName(TopName), lensClass, lensField, makeLensesWith, classyRules)  import Hledger.Utils.Debug+import Hledger.Utils.I18n (tests_I18n) import Hledger.Utils.Parse import Hledger.Utils.IO import Hledger.Utils.Regex@@ -296,7 +297,7 @@ --   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/simonmichael/hledger/pull/1545#issuecomment-881974554+-- https://github.com/hledgerorg/hledger/pull/1545#issuecomment-881974554 makeHledgerClassyLenses :: Name -> DecsQ makeHledgerClassyLenses x = flip makeLensesWith x $ classyRules     & lensField .~ (\_ _ n -> fieldName $ nameBase n)@@ -312,9 +313,9 @@      -- Fields which would cause too many conflicts if we exposed lenses with these names.     commonFields = Set.fromList-        [ "empty", "drop", "color", "transpose"  -- ReportOpts-        , "anon", "new", "auto"                  -- InputOpts-        , "rawopts", "file", "debug", "width"    -- CliOpts+        [ "empty", "drop", "color", "transpose", "title"  -- ReportOpts+        , "anon", "new", "auto"                           -- InputOpts+        , "rawopts", "file", "debug", "width"             -- CliOpts         ]      -- When updating some fields of ReportOpts within a ReportSpec, we need to@@ -329,5 +330,6 @@     queryFields = Set.fromList ["period", "statuses", "depth", "date2", "real", "querystring"]  tests_Utils = testGroup "Utils" [+  tests_I18n,   tests_Text   ]
Hledger/Utils/Debug.hs view
@@ -39,6 +39,9 @@ > 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. @@ -66,7 +69,7 @@ Debug level:  What to show: ------------  --------------------------------------------------------- 0             normal program output only-1             useful warnings, most common troubleshooting info+1             useful warnings, most common troubleshooting info, phase timings 2             common troubleshooting info, more detail 3             report options selection 4             report generation@@ -195,6 +198,11 @@   ,dbg8With   ,dbg9With +  -- * Trace/log phase timings+  ,dbgTime+  ,dbgTimeIO+  ,dbgTimeResetIO+   -- * Utilities   ,lbl_   ,progName@@ -213,11 +221,15 @@   ) where -import Control.DeepSeq (force)+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@@ -225,6 +237,7 @@ import System.Environment (getProgName) -- import System.Exit (exitFailure) import System.IO.Unsafe (unsafePerformIO)+import Text.Printf (printf)  import Hledger.Utils.IO (progArgs, pshow, pshow') @@ -561,6 +574,58 @@  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),
+ 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
@@ -24,6 +24,7 @@   usageError,   warn,   warnIO,+  setWarningHandler,   ansiFormatError,   ansiFormatWarning,   printError,@@ -35,14 +36,19 @@   getCurrentZonedTime,    -- * Files+  dataDirName,+  rulesDirName,   getHomeSafe,   embedFileRelative,+  embedFileRelativeBytes,   expandHomePath,   expandPath,   expandGlob,   expandPathOrGlob,   sortByModTime,   openFileOrStdin,+  withFileOrStdout,+  ensureFilesystemCanAppend,   readFileOrStdinPortably,   readFileOrStdinPortably',   readFileStrictly,@@ -65,6 +71,7 @@   getTerminalHeightWidth,   getTerminalHeight,   getTerminalWidth,+  insideEmacsNotVterm,    -- * Pager output   findPager,@@ -81,6 +88,8 @@   useColorOnStderr,   useColorOnStdoutUnsafe,   useColorOnStderrUnsafe,+  supportsTrueColor,+  supportsTrueColorUnsafe,   bold',   faint',   black',@@ -101,6 +110,10 @@   brightWhite',   rgb',   sgrresetall,+  accent,+  gradientStr,+  titleLine,+  titleAndVersionLine,    -- ** Generic @@ -125,12 +138,14 @@ 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, embedStringFile)+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@@ -147,7 +162,7 @@ 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 (..))+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)@@ -155,8 +170,9 @@ 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)+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)@@ -213,9 +229,13 @@ error' :: String -> a error' = errorWithoutStackTrace . ("Error: "<>) --- | Like error', but add a hint about using -h.+-- | Like error', but add a hint about using -h+-- (on its own line, if the message has several lines). usageError :: String -> a-usageError = error' . (++ " (use -h to see usage)")+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@@ -228,9 +248,22 @@ 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 = liftIO . traceIO . formatWarning+warnIO msg = liftIO $ readIORef warningHandler >>= ($ msg)  formatWarning =   (if useColorOnStderrUnsafe then modifyFirstLine ansiFormatWarning else id) .@@ -419,6 +452,20 @@ 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.@@ -477,6 +524,33 @@ 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.@@ -506,6 +580,11 @@ 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@@ -636,8 +715,19 @@ 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 @@ -670,7 +760,7 @@     windows = os == "mingw32"   pagerno    <- maybe False (not . either error' id . parseYN) <$> getOpt ["pager"]   outputfile <- hasOutputFile-  emacsterm  <- lookupEnv "INSIDE_EMACS" <&> (`notElem` [Nothing, Just "vterm"])+  emacsterm  <- insideEmacsNotVterm   mhw        <- getTerminalHeightWidth   mpager     <- findPager   return $ do@@ -746,11 +836,14 @@ -- lessVarValue :: Maybe String -> Maybe String -> Bool -> String lessVarValue mHLEDGER_LESS mLESS usecolor =-  let extralessopts = unwords $ [lessOptions] <> [lessColourOptions | usecolor]+  let extraopts = words lessOptions <> [lessColourOptions | usecolor]   in case (mHLEDGER_LESS, mLESS) of        (Just hledgerlessvar, _) -> hledgerlessvar-       (_, Just lessvar) -> if extralessopts `isInfixOf` lessvar then lessvar else unwords [lessvar, extralessopts]-       _ -> extralessopts+       (_, 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.@@ -793,13 +886,20 @@ colorOption = maybe Auto (either error' id . parseYNA) <$> getOpt ["color","colour"]  -- | Should ANSI color and styles be used with this output handle ?--- Considers colorOption, the NO_COLOR environment variable, and hSupportsANSIColor.+-- 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 && supports_color)+  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.@@ -823,9 +923,22 @@ 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, demo);+-- 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@@ -854,7 +967,12 @@ sgrbrightmagenta = setSGRCode [SetColor Foreground Vivid Magenta] sgrbrightcyan    = setSGRCode [SetColor Foreground Vivid Cyan] sgrbrightwhite   = setSGRCode [SetColor Foreground Vivid White]-sgrrgb r g b     = setSGRCode [SetRGBColor Foreground $ sRGB r g b]+-- 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@@ -914,6 +1032,58 @@ 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.@@ -964,16 +1134,18 @@  -- 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),--- inside emacs (emacs shell buffers show the escape sequence for some reason),--- or in a non-colour-supporting terminal.+-- 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+  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+  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
@@ -21,6 +21,7 @@   initialPos,   sourcePosPretty,   sourcePosPairPretty,+  sourcePosFileLine,    -- * Parsers and helpers   choice',@@ -34,7 +35,6 @@   parseWithState',   fromparse,   parseerror,-  showDateParseError,   nonspace,   isNewline,   isNonNewlineSpace,@@ -44,6 +44,10 @@   skipNonNewlineSpaces,   skipNonNewlineSpaces1,   skipNonNewlineSpaces',+  peekChar,+  peekChars2,+  peekAfterSpaces,+  manyWhile,    -- ** Trace the state of hledger parsers   dbgparse,@@ -66,6 +70,7 @@    -- ** Pretty-printing custom parse errors   customErrorBundlePretty,+  finalizeCustomErrorBundle,    -- ** "Final" parse errors   FinalParseError,@@ -78,6 +83,7 @@   finalFancyFailure,   finalFail,   finalCustomFailure,+  finalMessageFailure,    -- *** Pretty-printing "final" parse errors   finalErrorBundlePretty,@@ -89,16 +95,14 @@ ) where -import Control.Monad (when)+import Control.Monad (MonadPlus, when) import Data.Text qualified as T-import Safe (tailErr) 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.List import Data.Text (Text) import Text.Megaparsec.Char -- import Text.Megaparsec.Debug (dbg)@@ -140,13 +144,19 @@   where     peeklength = 30 --- | Render a pair of source positions in human-readable form, only displaying the range of lines.+-- | 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 (unPos l1) ++ "-" ++ show l2'+    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@@ -198,8 +208,6 @@ showParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String showParseError e = "parse error at " ++ show e -showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String-showDateParseError e = printf "date parse error (%s)" (intercalate ", " $ tailErr $ lines $ show e)  -- PARTIAL tailError won't be null because showing a parse error  isNewline :: Char -> Bool  isNewline '\n' = True@@ -216,7 +224,7 @@ {-# INLINABLE spacenonewline #-}  restofline :: TextParser m String-restofline = anySingle `manyTill` eolof+restofline = T.unpack <$> takeWhileP Nothing (/= '\n') <* eolof  -- Skip many non-newline spaces. skipNonNewlineSpaces :: (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()@@ -228,11 +236,51 @@ skipNonNewlineSpaces1 = void $ takeWhile1P Nothing isNonNewlineSpace {-# INLINABLE skipNonNewlineSpaces1 #-} --- Skip many non-newline spaces, returning True if any have been skipped.+-- | Skip any non-newline whitespace, and return whether there was any. skipNonNewlineSpaces' :: (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool-skipNonNewlineSpaces' = True <$ skipNonNewlineSpaces1 <|> pure False+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 @@ -400,17 +448,23 @@ -- case for 'ParseErrorBundle's returned from 'runParserT'.  customErrorBundlePretty :: HledgerParseErrors -> String-customErrorBundlePretty errBundle =-  let errBundle' = errBundle { bundleErrors =-        NE.sortWith errorOffset $ -- megaparsec requires that the list of errors be sorted by their offsets-        bundleErrors errBundle >>= finalizeCustomError }-  in  errorBundlePretty errBundle'+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 err+      Nothing -> pure $ limitExpected err        Just errFailAt@(ErrorFailAt startOffset _ _) ->         -- Adjust the offset@@ -431,7 +485,15 @@     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@@ -446,12 +508,15 @@ -- 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.+-- 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') +-- 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'). @@ -462,6 +527,8 @@   | 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@@ -485,9 +552,9 @@ -- -- 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.+-- files. Or, it can hold a complete error message instead (see 'FinalMessage'). data FinalParseErrorBundle' e = FinalParseErrorBundle'-  { finalErrorBundle :: ParseErrorBundle Text e+  { finalErrorBundle :: Either String (ParseErrorBundle Text e)   , includeFileStack :: [FilePath]   } deriving (Show) @@ -516,7 +583,12 @@ 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,@@ -525,7 +597,7 @@ finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String finalErrorBundlePretty bundle =      concatMap showIncludeFilepath (includeFileStack bundle)-  <> customErrorBundlePretty (finalErrorBundle bundle)+  <> either id customErrorBundlePretty (finalErrorBundle bundle)   where     showIncludeFilepath path = "in file included from " <> path <> ",\n" @@ -541,19 +613,24 @@           { bundleErrors = err NE.:| []           , bundlePosState = initialPosState filePath sourceText }     in  FinalParseErrorBundle'-          { finalErrorBundle = bundle+          { finalErrorBundle = Right bundle           , includeFileStack  = [] }    -- A 'ParseErrorBundle' already has the appropriate source and filepath   -- and so needs neither.   FinalBundle peBundle -> FinalParseErrorBundle'-    { finalErrorBundle = peBundle+    { 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
Hledger/Utils/Regex.hs view
@@ -51,6 +51,7 @@   ,toRegexCI   ,toRegex'   ,toRegexCI'+  ,regexEscape    -- * type aliases   ,Replacement   ,RegexError@@ -67,7 +68,7 @@ import Control.DeepSeq (NFData(..), rwhnf) import Control.Monad (foldM) import Data.Aeson (ToJSON(..), Value(String))-import Data.Array ((!), elems, indices)+import Data.Array (Array, (!), elems, indices) import Data.Char (isDigit) #if !MIN_VERSION_base(4,20,0) import Data.List (foldl')@@ -77,7 +78,7 @@ import Data.Text qualified as T import Text.Regex.TDFA (   Regex, CompOption(..), defaultCompOpt, defaultExecOpt,-  makeRegexOptsM, AllMatches(getAllMatches), match, MatchText,+  makeRegexOptsM, AllMatches(getAllMatches), match, MatchArray,   RegexLike(..), RegexMaker(..), RegexOptions(..), RegexContext(..)   ) @@ -132,17 +133,19 @@ 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))  -- Have to unpack here because Text instance in regex-tdfa only appears in 1.3.1+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))  -- Have to unpack here because Text instance in regex-tdfa only appears in 1.3.1+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:\n" <> s+  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@@ -152,6 +155,15 @@ 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 @@ -169,8 +181,9 @@  -- | Tests whether a Regexp matches a Text. ----- This currently unpacks the Text to a String, to work around a performance bug--- in regex-tdfa (#9), which may or may not be relevant here.+-- 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 @@ -201,32 +214,50 @@ -- 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 repl) str (reverse $ match (reCompiled re) str :: [MatchText String])+regexReplaceUnmemo re repl str =+    foldM replaceMatch (0, str, id) (match (reCompiled re) str :: [MatchArray])+    >>= \(_, rest, prependdone) -> Right $ prependdone rest   where-    -- Replace one match within the string with the replacement text-    -- appropriate for this match. Or return an error message.-    replaceMatch :: Replacement -> String -> MatchText String -> Either RegexError String-    replaceMatch replpat s matchgroups =-      case elems matchgroups of -        [] -> Right s-        ((_,(off,len)):_) ->   -- groups should have 0-based indexes, and there should always be at least one, since this is a match-          erpl >>= \rpl -> Right $ pre ++ rpl ++ post-          where-            (pre, post') = splitAt off s-            post = drop len post'-            -- The replacement text: the replacement pattern with all-            -- numeric backreferences replaced by the appropriate groups-            -- from this match. Or an error message.-            erpl = regexReplaceAllByM backrefRegex (lookupMatchGroup matchgroups) replpat-              where-                -- Given some match groups and a numeric backreference,-                -- return the referenced group text, or an error message.-                lookupMatchGroup :: MatchText String -> String -> Either RegexError String-                lookupMatchGroup grps ('\\':s2@(_:_)) | all isDigit s2 =-                  case read s2 of n | n `elem` indices grps -> Right $ fst (grps ! n)  -- PARTIAL: should not fail, all digits-                                  _                         -> Left $ "no match group exists for backreference \"\\"++s++"\""-                lookupMatchGroup _ s2 = Left $ "lookupMatchGroup called on non-numeric-backreference \""++s2++"\", shouldn't happen"+    -- 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
Hledger/Utils/String.hs view
@@ -11,10 +11,16 @@  -- quoting  quoteIfNeeded,  singleQuoteIfNeeded,+ shellQuoteIfNeeded,  quoteForCommandLine,  -- quotechars,  -- whitespacechars,  words',+ wordsmay,+ wordsEither,+ stripQuotes,+ isSingleQuoted,+ isDoubleQuoted,  stripAnsi,  -- * single-line layout  strip,@@ -40,8 +46,9 @@ 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, many, noneOf, sepBy)+import Text.Megaparsec (between, choice, errorBundlePretty, many, noneOf, sepBy, some) import Text.Megaparsec.Char (char) import Text.Printf (printf) @@ -155,6 +162,18 @@ 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.@@ -165,17 +184,22 @@ -- "'\"'" -- >>> 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+-- | 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` "'" = ['\\',c]+    escapeSingleQuote c | c `elem` "'" = "'\\''"     escapeSingleQuote c = [c]  quotechars, whitespacechars, redirectchars, shellchars :: [Char]@@ -184,25 +208,61 @@ redirectchars   = "<>" shellchars      = "<>(){}[]$&?#!~`*+\\" --- | 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.+-- | 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  = map stripquotes $ fromparse $ parsewithString p s  -- PARTIAL+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-      p = (singleQuotedPattern <|> doubleQuotedPattern <|> patterns) `sepBy` skipNonNewlineSpaces1-          -- eof-      patterns = many (noneOf whitespacechars)-      singleQuotedPattern = between (char '\'') (char '\'') (many $ noneOf "'")-      doubleQuotedPattern = between (char '"') (char '"') (many $ noneOf "\"")+      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+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 
Hledger/Utils/Text.hs view
@@ -14,6 +14,7 @@   textChomp,   -- quoting   quoteIfSpaced,+  quoteForQuery,   textQuoteIfNeeded,   -- singleQuoteIfNeeded,   -- quotechars,@@ -23,9 +24,9 @@   -- escapeSingleQuotes,   -- escapeQuotes,   -- words',-  stripquotes,-  -- isSingleQuoted,-  -- isDoubleQuoted,+  textStripQuotes,+  -- textIsSingleQuoted,+  -- textIsDoubleQuoted,   -- * single-line layout   -- elideLeft,   textElideRight,@@ -108,15 +109,27 @@ -- quotes, if it contains whitespace and is not already single- or -- double-quoted. quoteIfSpaced :: T.Text -> T.Text-quoteIfSpaced s | isSingleQuoted s || isDoubleQuoted s = s+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 | isSingleQuoted s || isDoubleQuoted s = s+-- quoteIfSpaced s | textIsSingleQuoted s || textIsDoubleQuoted s = s --                 | not $ any (`elem` s) whitespacechars = s --                 | otherwise = "'"++escapeSingleQuotes s++"'" @@ -152,7 +165,7 @@ -- -- NB correctly handles "a'b" but not "''a''". Can raise an error if parsing fails. -- words' :: String -> [String] -- words' "" = []--- words' s  = map stripquotes $ fromparse $ parsewith p s+-- words' s  = map textStripQuotes $ fromparse $ parsewith p s --     where --       p = do ss <- (singleQuotedPattern <|> doubleQuotedPattern <|> pattern) `sepBy` many1 spacenonewline --              -- eof@@ -162,15 +175,15 @@ --       doubleQuotedPattern = between (char '"') (char '"') (many $ noneOf "\"")  -- | Strip one matching pair of single or double quotes on the ends of a string.-stripquotes :: Text -> Text-stripquotes s = if isSingleQuoted s || isDoubleQuoted s then T.init $ T.tail s else s+textStripQuotes :: Text -> Text+textStripQuotes s = if textIsSingleQuoted s || textIsDoubleQuoted s then T.init $ T.tail s else s -isSingleQuoted :: Text -> Bool-isSingleQuoted s =+textIsSingleQuoted :: Text -> Bool+textIsSingleQuoted s =   T.length s >= 2 && T.head s == '\'' && T.last s == '\'' -isDoubleQuoted :: Text -> Bool-isDoubleQuoted 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.
Hledger/Write/Beancount.hs view
@@ -6,6 +6,11 @@  module Hledger.Write.Beancount (   showTransactionBeancount,+  showPriceDirectiveBeancount,+  beancountTransactions,+  beancountRenameAccounts,+  beancountDirectives,+  beancountItemRenderer,   -- postingsAsLinesBeancount,   -- postingAsLinesBeancount,   -- showAccountNameBeancount,@@ -27,6 +32,7 @@ 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@@ -38,13 +44,17 @@ import Hledger.Data.Amount import Hledger.Data.Currency (currencySymbolToCode) import Hledger.Data.Dates (showDate)-import Hledger.Data.Posting (renderCommentLines, showBalanceAssertion, postingIndent)-import Hledger.Data.Transaction (payeeAndNoteFromDescription')+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)+import Data.List.Extra (groupOnKey, nubSort) import Data.Bifunctor (first)-import Data.List (intersperse, sort)-import Data.Maybe (catMaybes)+import Data.List (intersperse, sort, sortOn)+import Data.Map qualified as M+import Data.Maybe (catMaybes, fromMaybe, isJust)+import Safe (minimumDef)  --- ** doctest setup -- $setup@@ -55,7 +65,8 @@ showTransactionBeancount t =   -- https://beancount.github.io/docs/beancount_language_syntax.html   -- similar to showTransactionHelper, but I haven't bothered with Builder-     firstline <> nl+     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)@@ -78,6 +89,140 @@       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@@ -120,24 +265,25 @@         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 letter) ?+-- | Is this a valid character to start a Beancount metadata name (lowercase ASCII letter) ? isBeancountMetadataNameStartChar :: Char -> Bool-isBeancountMetadataNameStartChar c = isLetter c && islowercase c+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 letter, digit, _ or -) ?+-- | Is this a valid character in the middle of a Beancount metadata name (a lowercase ASCII letter, digit, _ or -) ? isBeancountMetadataNameChar :: Char -> Bool-isBeancountMetadataNameChar c = (isLetter c && islowercase c) || isDigit c || c `elem` ['_', '-']+isBeancountMetadataNameChar c = isAsciiLower c || isDigit c || c `elem` ['_', '-']  -- | Convert a character to one or more characters valid inside a Beancount metadata name.--- Letters are lowercased, spaces are converted to dashes, and unsupported characters are encoded as c<HEXBYTES>.+-- 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-  | isLetter c = T.singleton $ toLower c+  | isAsciiUpper c = T.singleton $ toLower c   | isSpace c = "-"   | otherwise = T.pack $ printf "c%x" c @@ -200,11 +346,16 @@     -- amtwidth at all.     shownAmounts       | elideamount = [mempty]-      | otherwise   = map addCostBasis $ showMixedAmountLinesPartsB displayopts a'+      | otherwise   = map addCostBasisAndCost amtParts         where-          displayopts = defaultFmt{ displayZeroCommodity=True, displayForceDecimalMark=True, displayQuotes=False, displayCostBasis=False }+          -- 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-          addCostBasis (builder, amt) = builder <> showAmountCostBasisBeancountB displayopts amt+          -- 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@@ -217,7 +368,10 @@     -- 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 $ ptags p+    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) =@@ -233,7 +387,7 @@ type BeancountAccountNameComponent = AccountName  -- | Convert a hledger account name to a valid Beancount account name.--- It replaces spaces with dashes and other non-supported characters with C<HEXBYTES>;+-- 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.@@ -244,9 +398,9 @@ accountNameToBeancount :: AccountName -> BeancountAccountName accountNameToBeancount a = b   where-    cs1 =-      map accountNameComponentToBeancount $ accountNameComponents $-      dbg9 "hledger account name  " a+    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@@ -255,14 +409,21 @@               "bad top-level account: " <> c               ,"in beancount account name:           " <> accountNameFromComponents cs1               ,"converted from hledger account name: " <> a-              ,"For Beancount, top-level accounts must be (or be --alias'ed to)"-              ,"one of " <> T.intercalate ", " beancountTopLevelAccounts <> "."-              -- ,"and not: " <> b+              ,"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 $@@ -281,16 +442,20 @@ 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 = if isSpace c then "-" else printf "C%x" c+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--- same story, presumably-islowercase = isLower  -- | Is this a valid character to start a Beancount account name part (capital letter or digit) ? isBeancountAccountStartChar :: Char -> Bool@@ -322,6 +487,8 @@ 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@@ -347,10 +514,11 @@ -- 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 ""--- "C"+-- "CC" -- >>> commodityToBeancount "$" -- "USD" -- >>> commodityToBeancount "Usd"@@ -359,11 +527,14 @@ -- "A1" -- >>> commodityToBeancount "\"A 1!\"" -- "A-1C21"+-- >>> commodityToBeancount "K"+-- "KK" -- commodityToBeancount :: CommoditySymbol -> BeancountCommoditySymbol+commodityToBeancount "" = "CC" commodityToBeancount com =   dbg9 "beancount commodity name" $-  let com' = stripquotes com+  let com' = textStripQuotes com   in case currencySymbolToCode com' of     Just code -> code     Nothing ->@@ -372,6 +543,7 @@       & 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@@ -379,6 +551,9 @@     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
+ 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/Html.hs view
@@ -1,41 +1,219 @@ {- |-HTML writing helpers.-This module would ideally hide the details of which HTML library is used, but it doesn't yet.--Currently hledger-web uses blaze-html, but hledger CLI reports use lucid.-lucid has a more usable API than blaze-html (https://chrisdone.com/posts/lucid).-lucid2's is even better.-Unfortunately lucid* can not render multi-line or indented text.-We want this so that humans can read and troubleshoot our HTML output.-So a transition to blaze-html may be coming.+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 (-  L.toHtml,   Html,+  toHtml,+  Lines(..),+  borderClasses,+  formatCell,   formatRow,+  formatTitle,   htmlAsText,   htmlAsLazyText,+  nl,   styledTableHtml,+  titledTableHtml,   tests_Hledger_Write_Html   ) where -import Data.Text qualified as T (Text)-import Data.Text.Lazy qualified as TL (Text, toStrict)-import Lucid qualified as L (renderText, toHtml)-import Test.Tasty (testGroup)+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.Write.Html.Lucid (Html, formatRow, styledTableHtml)+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 -> T.Text-htmlAsText = TL.toStrict . L.renderText+htmlAsText :: Html -> Text+htmlAsText = TL.toStrict . renderHtml  htmlAsLazyText :: Html -> TL.Text-htmlAsLazyText = L.renderText+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&lt;b&gt;&amp;&quot;c&quot;</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&amp;b\">a</a></td>"+    cell (str "a") {cellAnchor = "register?q=a", cellTitle = "Show \"a\""}+      @?= "<td><a href=\"register?q=a\" title=\"Show &quot;a&quot;\">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 &amp; U</h3>\n<table>\n<tr><th>h</th></tr>\n</table>" html @?= True+   ]
Hledger/Write/Html/Attribute.hs view
@@ -4,13 +4,10 @@ -} module Hledger.Write.Html.Attribute (     stylesheet,-    concatStyles,     tableStylesheet,     tableStyle,+    borderStyle,     bold,-    doubleborder,-    topdoubleborder,-    bottomdoubleborder,     alignright,     alignleft,     aligncenter,@@ -30,10 +27,6 @@     Text.unlines $         "" : [el<>" {"<>styles<>"}" | (el,styles) <- elstyles] -concatStyles :: [Text] -> Text-concatStyles = Text.intercalate "; "-- tableStylesheet :: Text tableStylesheet = stylesheet tableStyle @@ -41,13 +34,25 @@ tableStyle =   [("table", collapse),    ("th, td", lpad),-   ("th.account, td.account", "padding-left:0;")]+   ("th.account, td.account", "padding-left:0;"),+   -- prevent wrapping within dates and individual amounts+   ("td.date, span.amount", "white-space:nowrap")]+  ++ borderStyle -bold, doubleborder, topdoubleborder, bottomdoubleborder :: Text+-- | 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"-doubleborder = "double black"-topdoubleborder    = "border-top:"<>doubleborder-bottomdoubleborder = "border-bottom:"<>doubleborder  alignright, alignleft, aligncenter :: Text alignright  = "text-align:right"
− Hledger/Write/Html/Blaze.hs
@@ -1,79 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{- |-HTML writing helpers using blaze-html.--}--module Hledger.Write.Html.Blaze (-    styledTableHtml,-    formatRow,-    formatCell,-    ) where--import Hledger.Write.Html.Attribute qualified as Attr-import Hledger.Write.Spreadsheet qualified as Spr-import Hledger.Write.Html.HtmlCommon (Lines, borderStyles)-import Hledger.Write.Spreadsheet (Type(..), Style(..), Emphasis(..), Cell(..))--import Text.Blaze.Html4.Transitional.Attributes qualified as HtmlAttr-import Text.Blaze.Html4.Transitional qualified as Html-import Data.Text qualified as Text-import Text.Blaze.Html4.Transitional (Html, toHtml, (!))-import Data.Foldable (traverse_)----- | 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 table = do-    Html.style $ toHtml $ Attr.tableStylesheet-    Html.table $ traverse_ formatRow table--formatRow:: (Lines border) => [Cell border Html] -> Html-formatRow = Html.tr . traverse_ formatCell--formatCell :: (Lines border) => Cell border Html -> Html-formatCell cell =-    let str = cellContent cell in-    let content =-            if Text.null $ cellAnchor cell-                then str-                else Html.a str !-                        HtmlAttr.href (Html.textValue (cellAnchor cell)) in-    let style =-            case borderStyles cell of-                [] -> []-                ss -> [HtmlAttr.style $ Html.textValue $-                        Attr.concatStyles ss] in-    let class_ =-            map (HtmlAttr.class_ . Html.textValue) $-            filter (not . Text.null) [Spr.textFromClass $ cellClass cell] in-    let span_ makeCell attrs =-            case Spr.cellSpan cell of-                Spr.NoSpan -> foldl (!) makeCell attrs-                Spr.Covered -> pure ()-                Spr.SpanHorizontal n ->-                    foldl (!) makeCell-                        (HtmlAttr.colspan (Html.stringValue $ show n) : attrs)-                Spr.SpanVertical n ->-                    foldl (!) makeCell-                        (HtmlAttr.rowspan (Html.stringValue $ show n) : attrs)-            in-    case cellStyle cell of-        Head -> span_ (Html.th content) (style++class_)-        Body emph ->-            let align =-                    case cellType cell of-                        TypeString -> []-                        TypeDate -> []-                        _ -> [HtmlAttr.align "right"]-                valign =-                    case Spr.cellSpan cell of-                        Spr.SpanVertical n ->-                            if n>1 then [HtmlAttr.valign "top"] else []-                        _ -> []-                withEmph =-                    case emph of-                        Item -> id-                        Total -> Html.b-            in  span_ (Html.td $ withEmph content) $-                style++align++valign++class_
− Hledger/Write/Html/HtmlCommon.hs
@@ -1,39 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{- |-Common definitions used by both Html.Blaze and Html.Lucid.--}--module Hledger.Write.Html.HtmlCommon (-    Lines(..),-    borderStyles,-    ) where--import Data.Text (Text)--import           Hledger.Write.Spreadsheet (Cell(..))-import Hledger.Write.Spreadsheet qualified as Spr---borderStyles :: Lines border => Cell border text -> [Text]-borderStyles cell =-    let border field access =-            map (field<>) $ borderLines $ access $ cellBorder cell in-    let leftBorder   = border "border-left:"   Spr.borderLeft   in-    let rightBorder  = border "border-right:"  Spr.borderRight  in-    let topBorder    = border "border-top:"    Spr.borderTop    in-    let bottomBorder = border "border-bottom:" Spr.borderBottom in-    leftBorder++rightBorder++topBorder++bottomBorder---class (Spr.Lines border) => Lines border where-    borderLines :: border -> [Text]--instance Lines () where-    borderLines () = []--instance Lines Spr.NumLines where-    borderLines prop =-        case prop of-            Spr.NoLine -> []-            Spr.SingleLine -> ["black"]-            Spr.DoubleLine -> ["double black"]
− Hledger/Write/Html/Lucid.hs
@@ -1,82 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{- |-HTML writing helpers using lucid.--}--module Hledger.Write.Html.Lucid (-    Html,-    L.toHtml,-    styledTableHtml,-    formatRow,-    formatCell,-    ) where--import           Data.Foldable (traverse_)-import Data.Text qualified as Text-import Lucid.Base qualified as L-import Lucid qualified as L--import Hledger.Write.Html.Attribute qualified as Attr-import           Hledger.Write.Html.HtmlCommon-import           Hledger.Write.Spreadsheet (Type(..), Style(..), Emphasis(..), Cell(..))-import Hledger.Write.Spreadsheet qualified as Spr---type Html = L.Html ()---- | 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 table = do-    L.link_ [L.rel_ "stylesheet", L.href_ "hledger.css"]-    L.style_ Attr.tableStylesheet-    L.table_ $ traverse_ formatRow table--formatRow:: (Lines border) => [Cell border Html] -> Html-formatRow = L.tr_ . traverse_ formatCell--formatCell :: (Lines border) => Cell border Html -> Html-formatCell cell =-    let str = cellContent cell in-    let content =-            if Text.null $ cellAnchor cell-                then str-                else L.a_ [L.href_ $ cellAnchor cell] str in-    let style =-            case borderStyles cell of-                [] -> []-                ss -> [L.style_ $ Attr.concatStyles ss] in-    let class_ =-            map L.class_ $-            filter (not . Text.null) [Spr.textFromClass $ cellClass cell] in-    let span_ makeCell attrs cont =-            case Spr.cellSpan cell of-                Spr.NoSpan -> makeCell attrs cont-                Spr.Covered -> pure ()-                Spr.SpanHorizontal n ->-                    makeCell (L.colspan_ (Text.pack $ show n) : attrs) cont-                Spr.SpanVertical n ->-                    makeCell (L.rowspan_ (Text.pack $ show n) : attrs) cont-            in-    case cellStyle cell of-        Head -> span_ L.th_ (style++class_) content-        Body emph ->-            let align =-                    case cellType cell of-                        TypeString -> []-                        TypeDate -> []-                        _ -> [L.makeAttribute "align" "right"]-                valign =-                    case Spr.cellSpan cell of-                        Spr.SpanVertical n ->-                            if n>1-                                then [L.makeAttribute "valign" "top"]-                                else []-                        _ -> []-                withEmph =-                    case emph of-                        Item -> id-                        Total -> L.b_-            in  span_ L.td_ (style++align++valign++class_) $-                withEmph content-
+ 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
@@ -34,8 +34,10 @@  import Hledger.Write.Spreadsheet qualified as Spr import Hledger.Write.Spreadsheet (Type(..), Style(..), Emphasis(..), Cell(..))-import Hledger.Data.Types (CommoditySymbol, AmountPrecision(..))-import Hledger.Data.Types (acommodity, aquantity, astyle, asprecision)+import Hledger.Data.Types+        (Amount, CommoditySymbol, AmountPrecision(..), DigitGroupStyle(..),+         acommodity, aquantity, astyle, asprecision, asdigitgroups,+        )  printFods ::     IO.TextEncoding ->@@ -145,7 +147,7 @@         TypeString -> DataString         TypeInteger -> DataInteger         TypeDate -> DataDate-        TypeAmount amt -> DataAmount (acommodity amt) (asprecision $ astyle amt)+        TypeAmount amt -> DataAmount $ commodityStyleFromAmount amt         TypeMixedAmount -> DataMixedAmount  cellStyles ::@@ -158,27 +160,50 @@             ((cellBorder cell, cellStyle cell),              dataStyleFromType $ cellType cell)) -numberStyleName :: (CommoditySymbol, AmountPrecision) -> String-numberStyleName (comm, prec) =-    printf "%s-%s" comm $-    case prec of-        NaturalPrecision -> "natural"-        Precision k -> show k+data CommodityStyle =+    CommodityStyle {+        commodityStyle :: CommoditySymbol,+        commodityPrecision :: AmountPrecision,+        commodityGrouping :: Bool+    } deriving (Eq, Ord, Show) -numberParams :: DataStyle -> Set (CommoditySymbol, AmountPrecision)-numberParams (DataAmount comm prec) = Set.singleton (comm, prec)+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 :: (CommoditySymbol, AmountPrecision) -> [String]-numberConfig (comm, prec) =+numberConfig :: CommodityStyle -> [String]+numberConfig commStyle@(CommodityStyle comm prec grp) =     let precStr =             case prec of                 NaturalPrecision -> ""                 Precision k -> printf " number:decimal-places='%d'" k-        name = numberStyleName (comm, prec)+        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/>" precStr :+    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>" :@@ -241,7 +266,7 @@       DataString     | DataInteger     | DataDate-    | DataAmount CommoditySymbol AmountPrecision+    | DataAmount CommodityStyle     | DataMixedAmount     deriving (Eq, Ord, Show) @@ -355,8 +380,8 @@             (printf "%s-%s-date" cstyleName bordName, Just "iso-date")         DataInteger ->             (printf "%s-%s-integer" cstyleName bordName, Just "integer")-        DataAmount comm prec ->-            let name = numberStyleName (comm, prec) in+        DataAmount commStyle ->+            let name = numberStyleName commStyle in             (printf "%s-%s-%s" cstyleName bordName name,                 Just $ printf "number-%s" name)         DataMixedAmount ->
Hledger/Write/Spreadsheet.hs view
@@ -21,6 +21,7 @@     horizontalSpan,     addHeaderBorders,     addRowSpanHeader,+    addRowSpanHeaderNE,     rawTableContent,     cellFromMixedAmount,     cellsFromMixedAmount,@@ -32,7 +33,10 @@ 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)@@ -145,13 +149,22 @@         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 class_ content) =-        Cell typ border style span anchor class_ $ f content+    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 =@@ -161,7 +174,9 @@         cellStyle = Body Item,         cellSpan = NoSpan,         cellAnchor = mempty,+        cellTitle = mempty,         cellClass = Class mempty,+        cellParts = [],         cellContent = text     } @@ -182,9 +197,9 @@ transpose = List.transpose . map (map transposeCell)  -addHeaderBorders :: [Cell () text] -> [Cell NumLines text]+addHeaderBorders :: (Functor f) => f (Cell () text) -> f (Cell NumLines text) addHeaderBorders =-    map (\c -> c {cellBorder = noBorder {borderBottom = DoubleLine}})+    fmap (\c -> c {cellBorder = noBorder {borderBottom = DoubleLine}})  horizontalSpan ::     (Lines border, Monoid text) =>@@ -198,31 +213,54 @@ addRowSpanHeader ::     Cell border text ->     [[Cell border text]] -> [[Cell border text]]-addRowSpanHeader header rows =+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]+        [row] -> [header:|row]         _ ->-            zipWith (:)+            zipWith (:|)                 (header{cellSpan = SpanVertical (length rows)} :                  repeat header{cellSpan = Covered})                 rows -rawTableContent :: [[Cell border text]] -> [[text]]-rawTableContent = map (map cellContent)+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 = cls,+        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+            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 ::@@ -232,7 +270,9 @@     map         (\(str,amt) ->             (defaultCell str) {-                cellClass = cls,+                cellClass =+                  markNegative+                    (Amt.isNegativeAmount amt && not (Amt.amountLooksZero amt)) cls,                 cellType = amountType bopts amt             })         (Amt.showMixedAmountLinesPartsB bopts mixedAmt)@@ -242,7 +282,9 @@     AmountFormat -> (Class, (wb, Amount)) -> Cell border wb cellFromAmount bopts (cls, (str,amt)) =     (defaultCell str) {-        cellClass = cls,+        cellClass =+          markNegative+            (Amt.isNegativeAmount amt && not (Amt.amountLooksZero amt)) cls,         cellType = amountType bopts amt     } 
Text/Tabular/AsciiWide.hs view
@@ -173,33 +173,50 @@               -> Builder renderColumns TableOpts{prettyTable=pretty, tableBorders=borders, borderSpaces=spaces} is h =     mconcat . intersperse "\n"                   -- Put each line on its own line-    . map (addBorders . mconcat) . transpose     -- Change to a list of lines and add borders-    . map (either hsep padCell) . flattenHeader  -- We now have a matrix of strings-    . zipHeader 0 is $ padRow <$> h  -- Pad cell height and add width marker+    . 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-    -- Pad each cell to have the appropriate width-    padCell (w, Cell TopLeft     ls) = map (\x -> wbBuilder x <> fromText (T.replicate (w - wbWidth x) " ")) ls-    padCell (w, Cell BottomLeft  ls) = map (\x -> wbBuilder x <> fromText (T.replicate (w - wbWidth x) " ")) ls-    padCell (w, Cell TopRight    ls) = map (\x -> fromText (T.replicate (w - wbWidth x) " ") <> wbBuilder x) ls-    padCell (w, Cell BottomRight ls) = map (\x -> fromText (T.replicate (w - wbWidth x) " ") <> wbBuilder x) ls-+    -- 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 -    -- Pad each cell to have the same number of lines-    padRow (Cell TopLeft     ls) = Cell TopLeft     $ ls ++ replicate (nLines - length ls) mempty-    padRow (Cell TopRight    ls) = Cell TopRight    $ ls ++ replicate (nLines - length ls) mempty-    padRow (Cell BottomLeft  ls) = Cell BottomLeft  $ replicate (nLines - length ls) mempty ++ ls-    padRow (Cell BottomRight ls) = Cell BottomRight $ replicate (nLines - length ls) mempty ++ ls+    blankLines w ls = replicate (nLines - length ls) (addSpaces w) -    hsep :: Properties -> [Builder]-    hsep NoLine     = replicate nLines $ if spaces then "  " else ""-    hsep SingleLine = replicate nLines $ midBar pretty spaces-    hsep DoubleLine = replicate nLines $ doubleMidBar pretty spaces+    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
hledger-lib.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           hledger-lib-version:        1.52.4+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@@ -34,16 +34,28 @@ license-file:   LICENSE build-type:     Simple tested-with:-    ghc==9.6.7, ghc==9.8.4, ghc==9.10.2, ghc==9.12.4+    ghc==9.6.7, ghc==9.8.4, ghc==9.10.3, ghc==9.12.4, ghc==9.14.1 extra-source-files:     CHANGES.md     README.md+    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/simonmichael/hledger+  location: https://github.com/hledgerorg/hledger  flag debug   description: Build with GHC 9.10+ stack traces enabled@@ -56,6 +68,7 @@       Hledger.Data       Hledger.Data.Account       Hledger.Data.AccountName+      Hledger.Data.AccountType       Hledger.Data.Amount       Hledger.Data.BalanceData       Hledger.Data.Balancing@@ -65,10 +78,12 @@       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@@ -86,6 +101,7 @@       Hledger.Read.CsvReader       Hledger.Read.InputOptions       Hledger.Read.JournalReader+      Hledger.Read.LatestDates       Hledger.Read.RulesReader       Hledger.Read.TimeclockReader       Hledger.Read.TimedotReader@@ -100,6 +116,7 @@       Hledger.Reports.ReportTypes       Hledger.Utils       Hledger.Utils.Debug+      Hledger.Utils.I18n       Hledger.Utils.IO       Hledger.Utils.Parse       Hledger.Utils.Regex@@ -107,12 +124,15 @@       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.Html.Blaze-      Hledger.Write.Html.HtmlCommon-      Hledger.Write.Html.Lucid+      Hledger.Write.Journal+      Hledger.Write.Ledger       Hledger.Write.Ods       Hledger.Write.Spreadsheet       Text.Tabular.AsciiWide@@ -124,17 +144,18 @@   hs-source-dirs:       ./   ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind-  cpp-options: -DVERSION="1.52.4"+  cpp-options: -DVERSION="2.0"   build-depends:       Decimal >=0.5.1     , Glob >=0.9-    , aeson >=1 && <2.4+    , 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@@ -145,13 +166,12 @@     , data-default >=0.5     , deepseq     , directory >=1.2.6.1-    , doclayout >=0.3 && <0.6+    , 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-    , lucid     , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9     , microlens >=0.4     , microlens-th >=0.4@@ -161,10 +181,12 @@     , 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@@ -184,17 +206,18 @@   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="1.52.4"+  cpp-options: -DVERSION="2.0"   build-depends:       Decimal >=0.5.1     , Glob >=0.7-    , aeson >=1 && <2.4+    , 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@@ -205,14 +228,13 @@     , data-default >=0.5     , deepseq     , directory >=1.2.6.1-    , doclayout >=0.3 && <0.6+    , 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-    , lucid     , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9     , microlens >=0.4     , microlens-th >=0.4@@ -222,10 +244,12 @@     , 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@@ -245,17 +269,18 @@   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="1.52.4"+  cpp-options: -DVERSION="2.0"   build-depends:       Decimal >=0.5.1     , Glob >=0.9-    , aeson >=1 && <2.4+    , 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@@ -266,14 +291,13 @@     , data-default >=0.5     , deepseq     , directory >=1.2.6.1-    , doclayout >=0.3 && <0.6+    , 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-    , lucid     , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9     , microlens >=0.4     , microlens-th >=0.4@@ -283,10 +307,12 @@     , 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
+ 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 "显示每日余额报表"