-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | This library contains hledger's core functionality. It is used by most
--   hledger* packages so that they support the same command line options,
--   file formats, reports, etc.
--   
--   hledger is a robust, cross-platform set of tools for tracking money,
--   time, or any other commodity, using double-entry accounting and a
--   simple, editable file format, with command-line, terminal and web
--   interfaces. It is a Haskell rewrite of Ledger, and one of the leading
--   implementations of Plain Text Accounting.
--   
--   See also:
--   
--   <ul>
--   <li><a>https://hledger.org</a> - hledger's home page</li>
--   <li><a>https://hledger.org/dev.html</a> - starting point for hledger's
--   developer docs</li>
--   
--   <li><a>https://hackage.haskell.org/package/hledger-lib/docs/Hledger.html</a>
--   - starting point for hledger's haddock docs</li>
--   </ul>
@package hledger-lib
@version 2.0


-- | Currency names, symbols and codes. Reference: -
--   <a>https://www.xe.com/symbols</a> - <a>https://www.xe.com/currency</a>
module Hledger.Data.Currency

-- | An ISO 4217 currency code, like EUR. Generally used for fiat
--   currencies, but may also use the X* convention for non-country
--   currencies (eg XAU, XBT), or ISO 20022 cryptocurrency codes (eg ADA).
type CurrencyCode = Text

-- | A traditional currency symbol like $ or ¥ (as opposed to a currency
--   code like USD or JPY). Usually one character, sometimes more, like C$
--   or BZ$.
type CurrencySymbol = Text
currencies :: [([Char], CurrencyCode, CurrencySymbol)]

-- | 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:
--   <a>https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&amp;order=market_cap_desc&amp;per_page=100&amp;page=1</a>
cryptocurrencies :: [CurrencyCode]

-- | Look for a currency code corresponding to this currency symbol.
--   
--   <pre>
--   &gt;&gt;&gt; currencySymbolToCode ""
--   Nothing
--   
--   &gt;&gt;&gt; currencySymbolToCode "$"
--   Just "USD"
--   </pre>
currencySymbolToCode :: CurrencySymbol -> Maybe CurrencyCode

-- | Look for a currency symbol corresponding to this currency code.
--   
--   <pre>
--   &gt;&gt;&gt; currencyCodeToSymbol "CZK"  -- Just "Kč"
--   Just "K\269"
--   </pre>
currencyCodeToSymbol :: CurrencyCode -> Maybe CurrencySymbol

-- | Like <a>currencySymbolToCode</a>, 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.
--   
--   <pre>
--   &gt;&gt;&gt; toCurrencyCode "$"
--   "USD"
--   
--   &gt;&gt;&gt; toCurrencyCode "BTC"
--   "BTC"
--   </pre>
toCurrencyCode :: CurrencySymbol -> CurrencyCode


-- | Easy regular expression helpers, currently based on regex-tdfa. These
--   should:
--   
--   <ul>
--   <li>be cross-platform, not requiring C libraries</li>
--   <li>support unicode</li>
--   <li>support extended regular expressions</li>
--   <li>support replacement, with backreferences etc.</li>
--   <li>support splitting</li>
--   <li>have mnemonic names</li>
--   <li>have simple monomorphic types</li>
--   <li>work with simple strings</li>
--   </ul>
--   
--   Regex strings are automatically compiled into regular expressions the
--   first time they are seen, and these are cached. If you use a huge
--   number of unique regular expressions this might lead to increased
--   memory usage. Several functions have memoised variants (*Memo), which
--   also trade space for time.
--   
--   Currently two APIs are provided:
--   
--   <ul>
--   <li>The old partial one (with ' suffixes') which will call error on
--   any problem (eg with malformed regexps). This comes from hledger's
--   origin as a command-line tool.</li>
--   <li>The new total one which will return an error message. This is
--   better for long-running apps like hledger-web.</li>
--   </ul>
--   
--   Current limitations:
--   
--   <ul>
--   <li>(?i) and similar are not supported</li>
--   </ul>
module Hledger.Utils.Regex

-- | Regular expression. Extended regular expression-ish syntax ? But does
--   not support eg (?i) syntax.
data Regexp
toRegex :: Text -> Either RegexError Regexp
toRegexCI :: Text -> Either RegexError Regexp
toRegex' :: Text -> Regexp
toRegexCI' :: Text -> Regexp

-- | Escape POSIX extended regex metacharacters in a text so the result
--   matches the input as a literal. Eg <tt>regexEscape "U$"</tt> produces
--   <tt>"U\$"</tt>, which compiled as a regex matches only the
--   two-character string <tt>U$</tt>.
regexEscape :: Text -> Text

-- | A replacement pattern. May include numeric backreferences (N).
type Replacement = String

-- | An error message arising during a regular expression operation. Eg:
--   trying to compile a malformed regular expression, or trying to apply a
--   malformed replacement pattern.
type RegexError = String

-- | Test whether a Regexp matches a String. This is an alias for
--   <a>matchTest</a> for consistent naming.
regexMatch :: Regexp -> String -> Bool

-- | Tests whether a Regexp matches a Text.
--   
--   This unpacks the Text to a String, which measured about 10% faster
--   than matching the Text directly (regex-tdfa 1.3.2.6, 2026-11).
--   regex-tdfa's issue #9, a large slowdown with Text, was about
--   extracting match text (as regexMatchTextGroups does), not this test.
regexMatchText :: Regexp -> Text -> Bool

-- | Return a (possibly empty) list of match groups derived by applying the
--   Regex to a Text.
regexMatchTextGroups :: Regexp -> Text -> [Text]

-- | A memoising version of regexReplace. Caches the result for each search
--   pattern, replacement pattern, target string tuple. This won't generate
--   a regular expression parsing error since that is pre-compiled
--   nowadays, but there can still be a runtime error from the replacement
--   pattern, eg with a backreference referring to a nonexistent match
--   group.
regexReplace :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceAllBy :: Regexp -> (String -> String) -> String -> String
instance GHC.Internal.Classes.Eq Hledger.Utils.Regex.Regexp
instance Control.DeepSeq.NFData Hledger.Utils.Regex.Regexp
instance GHC.Internal.Classes.Ord Hledger.Utils.Regex.Regexp
instance GHC.Internal.Read.Read Hledger.Utils.Regex.Regexp
instance Text.Regex.Base.RegexLike.RegexContext Hledger.Utils.Regex.Regexp GHC.Internal.Base.String GHC.Internal.Base.String
instance Text.Regex.Base.RegexLike.RegexLike Hledger.Utils.Regex.Regexp GHC.Internal.Base.String
instance GHC.Internal.Show.Show Hledger.Utils.Regex.Regexp
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Utils.Regex.Regexp


-- | Most data types are defined here to avoid import cycles. Here is an
--   overview of the hledger data model:
--   
--   <pre>
--   Journal                  -- a journal is read from one or more data files. It contains..
--    [Transaction]           -- journal transactions (aka entries), which have date, cleared status, code, description and..
--     [Posting]              -- multiple account postings, which have account name and amount
--    [MarketPrice]           -- historical market prices for commodities
--   
--   Ledger                   -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..
--    Journal                 -- a filtered copy of the original journal, containing only the transactions and postings we are interested in
--    [Account]               -- all accounts, in tree order beginning with a "root" account", with their balances and sub/parent accounts
--   </pre>
--   
--   For more detailed documentation on each type, see the corresponding
--   modules.
module Hledger.Data.Types
fromEFDay :: EFDay -> Day
isBalanceSheetAccountType :: AccountType -> Bool
isDecimalMark :: Char -> Bool

-- | Does this tag name begin with the hidden tag prefix (_) ?
isHiddenTagName :: TagName -> Bool
isIncomeStatementAccountType :: AccountType -> Bool

-- | Compare two MixedAmounts, substituting 0 for the quantity of any
--   missing commodities in either.
maCompare :: MixedAmount -> MixedAmount -> Ordering

-- | Calculate the key for storing this Amount within a MixedAmount, from
--   its commodity and transacted cost (ignoring cost basis).
mixedAmountKey :: Amount -> MixedAmountKey
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
nullaccountdeclarationinfo :: AccountDeclarationInfo
nullpayeedeclarationinfo :: PayeeDeclarationInfo
nullperiodictransaction :: PeriodicTransaction
nullsourcepos :: SourcePos
nullsourcepospair :: (SourcePos, SourcePos)
nulltagdeclarationinfo :: TagDeclarationInfo
nulltransactionmodifier :: TransactionModifier
showMarketPrice :: MarketPrice -> String
showMarketPrices :: [MarketPrice] -> [Char]

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTag :: Tag -> HiddenTag

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTagName :: TagName -> TagName

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTag :: HiddenTag -> Tag

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTagName :: TagName -> TagName

-- | An account within a hierarchy, with references to its parent and
--   subaccounts if any, and with per-report-period data of type
--   <tt>a</tt>. Only the name is required; the other fields may or may not
--   be present.
data Account a
Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account a] -> Maybe (Account a) -> Bool -> PeriodData a -> Account a

-- | full name
[aname] :: Account a -> AccountName

-- | optional extra info from account directives relationships in the tree
[adeclarationinfo] :: Account a -> Maybe AccountDeclarationInfo

-- | subaccounts
[asubs] :: Account a -> [Account a]

-- | parent account
[aparent] :: Account a -> Maybe (Account a)

-- | used in some reports to indicate elidable accounts
[aboring] :: Account a -> Bool

-- | associated data per report period
[adata] :: Account a -> PeriodData a
data AccountAlias
BasicAlias :: AccountName -> AccountName -> AccountAlias
RegexAlias :: Regexp -> Replacement -> AccountAlias

-- | Extra information about an account that can be derived from its
--   account directive (and the other account directives).
data AccountDeclarationInfo
AccountDeclarationInfo :: Text -> [Tag] -> Int -> SourcePos -> AccountDeclarationInfo

-- | any comment lines following an account directive for this account
[adicomment] :: AccountDeclarationInfo -> Text

-- | tags extracted from the account comment, if any
[aditags] :: AccountDeclarationInfo -> [Tag]

-- | the order in which this account was declared, relative to other
--   account declarations, during parsing (1..)
[adideclarationorder] :: AccountDeclarationInfo -> Int

-- | source file and position
[adisourcepos] :: AccountDeclarationInfo -> SourcePos
type AccountName = Text
data AccountType
Asset :: AccountType
Liability :: AccountType
Equity :: AccountType
Revenue :: AccountType
Expense :: AccountType

-- | a subtype of Asset - liquid assets to show in cashflow report
Cash :: AccountType

-- | a subtype of Equity - account with which to balance commodity
--   conversions
Conversion :: AccountType

-- | a subtype of Revenue - realised capital gains/losses
Gain :: AccountType

-- | a subtype of Equity - accumulated unrealised capital gains/losses
UnrealisedGain :: AccountType

-- | a subtype of Equity - transactions' tolerated imbalances, shown by
--   --infer-imbalance
Imbalance :: AccountType
data Amount
Amount :: CommoditySymbol -> Quantity -> AmountStyle -> Maybe AmountCost -> Maybe CostBasis -> Amount
[acommodity] :: Amount -> CommoditySymbol
[aquantity] :: Amount -> Quantity
[astyle] :: Amount -> AmountStyle

-- | transacted exchange rate - the unit or total cost, in another
--   commodity, used for this amount within its transaction
[acost] :: Amount -> Maybe AmountCost

-- | the cost basis of an investment lot represented by this amount. Or, a
--   matcher to select such a lot from the available lots.
[acostbasis] :: Amount -> Maybe CostBasis

-- | An amount's per-unit or total cost/selling price in another commodity,
--   as recorded in the journal entry eg with <tt> or </tt>@. <a>Cost</a>,
--   formerly AKA "transaction price". The amount is always positive.
data AmountCost
UnitCost :: Amount -> AmountCost
TotalCost :: Amount -> AmountCost

-- | The "display precision" for a hledger amount, by which we mean the
--   number of decimal digits to display to the right of the decimal mark.
data AmountPrecision

-- | show this many decimal digits (0..255)
Precision :: Word8 -> AmountPrecision

-- | show all significant decimal digits stored internally
NaturalPrecision :: AmountPrecision

-- | Display styles for amounts - things which can be detected during
--   parsing, such as commodity side and spacing, digit group marks,
--   decimal mark, number of decimal digits etc. Every <a>Amount</a> has an
--   AmountStyle. After amounts are parsed from the input, for each
--   <a>Commodity</a> a standard style is inferred and then used when
--   displaying amounts in that commodity. Related to <a>AmountFormat</a>
--   but higher level.
--   
--   See also: - hledger manual &gt; Commodity styles - hledger manual &gt;
--   Amounts - hledger manual &gt; Commodity display style
data AmountStyle
AmountStyle :: Side -> Bool -> Maybe DigitGroupStyle -> Maybe Char -> AmountPrecision -> Rounding -> AmountStyle

-- | show the symbol on the left or the right ?
[ascommodityside] :: AmountStyle -> Side

-- | show a space between symbol and quantity ?
[ascommodityspaced] :: AmountStyle -> Bool

-- | show the integer part with these digit group marks, or not
[asdigitgroups] :: AmountStyle -> Maybe DigitGroupStyle

-- | show this character (should be . or ,) as decimal mark, or use the
--   default (.)
[asdecimalmark] :: AmountStyle -> Maybe Char

-- | "display precision" - show this number of digits after the decimal
--   point
[asprecision] :: AmountStyle -> AmountPrecision

-- | "rounding strategy" - kept here for convenience, for now: when
--   displaying an amount, it is ignored, but when applying this style to
--   another amount, it determines how hard we should try to adjust that
--   amount's display precision.
[asrounding] :: AmountStyle -> Rounding

-- | 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 :: AssertQuantifier -> Maybe (Interval, DateSpan) -> Text -> Text -> [DateSpan] -> Text -> SourcePos -> AssertDirective
[adQuantifier] :: AssertDirective -> AssertQuantifier

-- | the period expression, if any: the rule is checked in each of its
--   periods
[adPeriod] :: AssertDirective -> Maybe (Interval, DateSpan)

-- | the period expression as written, or empty
[adPeriodText] :: AssertDirective -> Text

-- | the query as written
[adQueryText] :: AssertDirective -> Text

-- | the periods of its skip subdirectives, whose checks are skipped
[adSkips] :: AssertDirective -> [DateSpan]

-- | the directive's lines as written (the assert line and any skip lines),
--   for error excerpts
[adSourceText] :: AssertDirective -> Text
[adSourcePos] :: AssertDirective -> SourcePos

-- | Which rows an assert directive's query must match: none, or at least
--   one.
data AssertQuantifier
AssertNone :: AssertQuantifier
AssertSome :: AssertQuantifier

-- | A balance assertion is a declaration about an account's expected
--   balance at a certain point (posting date and parse order). They
--   provide additional error checking and readability to a journal file.
--   
--   A balance assignments is an instruction to hledger to adjust an
--   account's balance to a certain amount at a certain point.
--   
--   The <a>BalanceAssertion</a> type is used for representing both of
--   these.
--   
--   hledger supports multiple kinds of balance assertions/assignments,
--   which differ in whether they refer to a single commodity or all
--   commodities, and the (subaccount-)inclusive or exclusive account
--   balance.
data BalanceAssertion
BalanceAssertion :: Amount -> Bool -> Bool -> SourcePos -> BalanceAssertion

-- | the expected balance in a particular commodity
[baamount] :: BalanceAssertion -> Amount

-- | disallow additional non-asserted commodities ?
[batotal] :: BalanceAssertion -> Bool

-- | include subaccounts when calculating the actual balance ?
[bainclusive] :: BalanceAssertion -> Bool

-- | the assertion's file position, for error reporting
[baposition] :: BalanceAssertion -> SourcePos

-- | Data that's useful in "balance" reports: subaccount-exclusive and
--   -inclusive amounts, typically representing either a balance change or
--   an end balance; and a count of postings.
data BalanceData
BalanceData :: MixedAmount -> MixedAmount -> Int -> BalanceData

-- | balance data excluding subaccounts
[bdexcludingsubs] :: BalanceData -> MixedAmount

-- | balance data including subaccounts
[bdincludingsubs] :: BalanceData -> MixedAmount

-- | the number of postings
[bdnumpostings] :: BalanceData -> Int
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> [(Amount, SourcePos)] -> SourcePos -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle

-- | any comment lines following the commodity directive
[ccomment] :: Commodity -> Text

-- | tags extracted from the comment, if any
[ctags] :: Commodity -> [Tag]

-- | 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
[caliases] :: Commodity -> [(Amount, SourcePos)]

-- | source position of the commodity directive
[csourcepos] :: Commodity -> SourcePos
type CommoditySymbol = Text

-- | The cost basis of an individual lot - some quantity of an asset
--   acquired at a given date and time. This can represent a definite cost
--   basis, which must have a cost and date; the label is optional. Or it
--   can represent a cost basis matcher for selecting lots. Note: cost is
--   always stored as a per-unit cost, even if the user specified total
--   cost with {{}}.
data CostBasis
CostBasis :: Maybe Day -> Maybe Text -> Maybe Amount -> CostBasis

-- | nominal acquisition date
[cbDate] :: CostBasis -> Maybe Day

-- | a short label to ensure uniqueness, correct intra-day order, or
--   memorability, if needed
[cbLabel] :: CostBasis -> Maybe Text

-- | nominal acquisition cost (per-unit)
[cbCost] :: CostBasis -> Maybe Amount

-- | A possibly open-ended span of time, from an optional inclusive start
--   date to an optional exclusive end date. Each date can be either exact
--   or flexible. An "exact date span" is a Datepan with exact start and
--   end dates.
data DateSpan
DateSpan :: Maybe EFDay -> Maybe EFDay -> DateSpan
type DateTag = (TagName, Day)

-- | One of the decimal marks we support: either period or comma.
type DecimalMark = Char
data DepthSpec
DepthSpec :: Maybe Int -> [(Regexp, Int)] -> DepthSpec
[dsFlatDepth] :: DepthSpec -> Maybe Int
[dsRegexpDepths] :: DepthSpec -> [(Regexp, Int)]

-- | A style for displaying digit groups in the integer part of a floating
--   point number. It consists of the character used to separate groups
--   (any of the digit group marks accepted when parsing: period, comma,
--   underscore, apostrophe, or one of several unicode spaces; see
--   isDigitSeparatorChar), and the size of each group, starting with the
--   one nearest the decimal point. The last group size is assumed to
--   repeat. Eg, comma between thousands is DigitGroups ',' [3].
data DigitGroupStyle
DigitGroups :: Char -> [Word8] -> DigitGroupStyle

-- | A date which is either exact or flexible. Flexible dates are allowed
--   to be adjusted in certain situations.
data EFDay
Exact :: Day -> EFDay
Flex :: Day -> EFDay

-- | 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 :: Int -> Int -> Int -> Int -> Map Text Int -> FastPathStats

-- | transactions parsed by the fast path
[fpsTxnsFast] :: FastPathStats -> Int

-- | transactions it declined, parsed by the general parser
[fpsTxnsGeneral] :: FastPathStats -> Int

-- | price directives parsed by the fast path
[fpsPricesFast] :: FastPathStats -> Int

-- | price directives it declined
[fpsPricesGeneral] :: FastPathStats -> Int

-- | the number of declines for each reason
[fpsDeclines] :: FastPathStats -> Map Text Int

-- | Types with this class have one or more amounts, which can have display
--   styles applied to them.
class HasAmounts a
styleAmounts :: HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
type HiddenTag = Tag
data Interval
NoInterval :: Interval
Days :: Int -> Interval
Weeks :: Int -> Interval
Months :: Int -> Interval
Quarters :: Int -> Interval
Years :: Int -> Interval
NthWeekdayOfMonth :: Int -> Int -> Interval
MonthDay :: Int -> Interval
MonthAndDay :: Int -> Int -> Interval
DaysOfWeek :: [Int] -> Interval

-- | A journal, containing general ledger transactions; also directives and
--   various other things. This is hledger's main data model.
--   
--   During parsing, it is used as the type alias <a>ParsedJournal</a>. The
--   jparse* fields are mainly used during parsing and included here for
--   convenience. The list fields described as "in parse order" are usually
--   reversed for efficiency during parsing. After parsing,
--   "journalFinalise" converts ParsedJournal to a finalised
--   <a>Journal</a>, which has all lists correctly ordered, and much data
--   inference and validation applied.
data Journal
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

-- | the current default year, specified by the most recent Y or apply year
--   directive (or current date)
[jparsedefaultyear] :: Journal -> 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.
[jparseapplyyears] :: Journal -> [Maybe Year]

-- | the current default commodity and its format, specified by the most
--   recent D directive
[jparsedefaultcommodity] :: Journal -> Maybe (CommoditySymbol, AmountStyle)

-- | the character to always parse as decimal point, if set by CsvReader's
--   decimal-mark (or a future journal directive)
[jparsedecimalmark] :: Journal -> Maybe DecimalMark

-- | the current stack of parent account names, specified by apply account
--   directives
[jparseparentaccounts] :: Journal -> [AccountName]

-- | 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.
[jparsealiases] :: Journal -> [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)
[jparseoptaliases] :: Journal -> [AccountAlias]

-- | timeclock sessions which have not been clocked out
[jparsetimeclockentries] :: Journal -> [TimeclockEntry]

-- | (absolute path, canonical path) of included files, most recent first
[jparseincludefilestack] :: Journal -> [(FilePath, FilePath)]

-- | the most recently calculated source position, if any, from which later
--   ones are calculated cheaply
[jparsepos] :: Journal -> Maybe ParsePos

-- | the distinct amount styles parsed so far, which parsed amounts share
--   to save memory
[jparseamountstyles] :: Journal -> Set AmountStyle

-- | the distinct account names and commodity symbols parsed so far, which
--   parsed items share to save memory
[jparsetexts] :: Journal -> Set Text

-- | how many entries the parser's fast path has accepted or declined so
--   far, and why (with --debug) principal data
[jparsefastpathstats] :: Journal -> FastPathStats

-- | Payees declared by payee directives, in parse order.
[jdeclaredpayees] :: Journal -> [(Payee, PayeeDeclarationInfo)]

-- | Tags declared by tag directives, in parse order.
[jdeclaredtags] :: Journal -> [(TagName, TagDeclarationInfo)]

-- | Accounts declared by account directives, in parse order.
[jdeclaredaccounts] :: Journal -> [(AccountName, AccountDeclarationInfo)]

-- | Accounts which were declared with tags, and those tags.
[jdeclaredaccounttags] :: Journal -> Map AccountName [Tag]

-- | Accounts which were declared with a type: tag, grouped by the type.
[jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName]

-- | All the account types known, from account declarations or account
--   names or parent accounts.
[jaccounttypes] :: Journal -> Map AccountName AccountType

-- | Commodities (and their display styles) declared by commodity
--   directives, in parse order.
[jdeclaredcommodities] :: Journal -> Map CommoditySymbol Commodity

-- | Commodities which were declared with tags, and those tags.
[jdeclaredcommoditytags] :: Journal -> Map CommoditySymbol [Tag]

-- | Commodity display styles inferred from amounts in the journal.
[jinferredcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | Commodity display styles declared by command line options (sometimes
--   augmented, see the import command).
[jglobalcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | P (market price) directives in the journal, in parse order.
[jpricedirectives] :: Journal -> [PriceDirective]

-- | Market prices inferred from transactions in the journal, in parse
--   order.
[jinferredmarketprices] :: Journal -> [MarketPrice]

-- | Auto posting rules declared in the journal.
[jtxnmodifiers] :: Journal -> [TransactionModifier]

-- | Periodic transaction rules declared in the journal.
[jperiodictxns] :: Journal -> [PeriodicTransaction]

-- | Assert directives declared in the journal, in parse order.
[jasserts] :: Journal -> [AssertDirective]

-- | Transactions recorded in the journal. The important bit.
[jtxns] :: Journal -> [Transaction]

-- | 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).
[jitems] :: Journal -> [JournalItem]

-- | the main and any included journal files. The main file is first,
--   followed by any included files in the order encountered.
[jfiles] :: Journal -> [JournalFile]

-- | 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.
[jauxfiles] :: Journal -> [(FilePath, [FilePath])]

-- | 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
[jlastreadtime] :: Journal -> POSIXTime

-- | One of the files a journal was read from.
data JournalFile
JournalFile :: FilePath -> Text -> Int -> JournalFile

-- | 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
[jfpath] :: JournalFile -> FilePath

-- | the file's raw text
[jftext] :: JournalFile -> Text

-- | the file's include depth: 0 for a main file, 1 for a file it includes,
--   and so on
[jfdepth] :: JournalFile -> Int

-- | 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

-- | a transaction: the one in jtxns whose tsourcepos starts here
JITransaction :: SourcePos -> JournalItem

-- | a single top-level comment line (starting with ; # or *)
JIComment :: Text -> JournalItem

-- | a comment ... end comment block
JICommentBlock :: Text -> JournalItem

-- | a directive which should be reproduced when exporting (including P, ~
--   and = rules), without any ! or @ prefix
JIDirective :: Text -> JournalItem

-- | 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
JINonExportedDirective :: Text -> JournalItem

-- | an include directive line; the included file's items follow it
JIInclude :: Text -> JournalItem

-- | one or more blank lines
JIBlank :: JournalItem

-- | A Ledger has the journal it derives from, and the accounts derived
--   from that. Accounts are accessible both list-wise and tree-wise, since
--   each one knows its parent and subs; the first account is the root of
--   the tree and always exists.
data Ledger
Ledger :: Journal -> [Account BalanceData] -> Ledger
[ljournal] :: Ledger -> Journal
[laccounts] :: Ledger -> [Account BalanceData]

-- | 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 :: Day -> Maybe Text -> LotId
[lotDate] :: LotId -> Day
[lotLabel] :: LotId -> Maybe Text

-- | A historical market price (exchange rate) from one commodity to
--   another. A more concise form of a PriceDirective, without the amount
--   display info.
data MarketPrice
MarketPrice :: Day -> CommoditySymbol -> CommoditySymbol -> Quantity -> MarketPrice

-- | Date on which this price becomes effective.
[mpdate] :: MarketPrice -> Day

-- | The commodity being converted from.
[mpfrom] :: MarketPrice -> CommoditySymbol

-- | The commodity being converted to.
[mpto] :: MarketPrice -> CommoditySymbol

-- | One unit of the "from" commodity is worth this quantity of the "to"
--   commodity.
[mprate] :: MarketPrice -> Quantity

-- | 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 :: Map MixedAmountKey Amount -> MixedAmount

-- | 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

-- | amount commodity
MixedAmountKeyNoCost :: CommoditySymbol -> MixedAmountKey
MixedAmountKeyUnitCost :: CommoditySymbol -> CommoditySymbol -> Quantity -> MixedAmountKey
MixedAmountKeyTotalCost :: CommoditySymbol -> CommoditySymbol -> MixedAmountKey
type Month = Int
type MonthDay = Int
type MonthWeek = Int

-- | Whether an account's balance is normally a positive number (in
--   accounting terms, a debit balance) or a negative number (credit
--   balance). Assets and expenses are normally positive (debit), while
--   liabilities, equity and income are normally negative (credit).
--   <a>https://en.wikipedia.org/wiki/Normal_balance</a>
data NormalSign
NormallyPositive :: NormalSign
NormallyNegative :: NormalSign

-- | 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 :: SourcePos -> Int -> Text -> ParsePos
[ppSourcePos] :: ParsePos -> SourcePos
[ppOffset] :: ParsePos -> Int
[ppInput] :: ParsePos -> Text

-- | 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
type Payee = Text

-- | Extra information found in a payee directive.
data PayeeDeclarationInfo
PayeeDeclarationInfo :: Text -> [Tag] -> PayeeDeclarationInfo

-- | any comment lines following the payee directive
[pdicomment] :: PayeeDeclarationInfo -> Text

-- | tags extracted from the comment, if any
[pditags] :: PayeeDeclarationInfo -> [Tag]
data Period
DayPeriod :: Day -> Period
WeekPeriod :: Day -> Period
MonthPeriod :: Year -> Month -> Period
QuarterPeriod :: Year -> Quarter -> Period
YearPeriod :: Year -> Period
PeriodBetween :: Day -> Day -> Period
PeriodFrom :: Day -> Period
PeriodTo :: Day -> Period
PeriodAll :: Period

-- | A general container for storing data values associated with zero or
--   more contiguous report (sub)periods, and with the (open ended)
--   pre-report period. The report periods are typically all the same
--   length, but need not be.
--   
--   Report periods are represented only by their start dates, used as the
--   keys of a Map.
data PeriodData a
PeriodData :: a -> Map Day a -> PeriodData a

-- | data for the period before the report
[pdpre] :: PeriodData a -> a

-- | data for each period within the report
[pdperiods] :: PeriodData a -> Map Day a

-- | A periodic transaction rule, describing a transaction that recurs.
data PeriodicTransaction
PeriodicTransaction :: Text -> Interval -> DateSpan -> (SourcePos, SourcePos) -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> PeriodicTransaction

-- | the period expression as written
[ptperiodexpr] :: PeriodicTransaction -> Text

-- | the interval at which this transaction recurs
[ptinterval] :: PeriodicTransaction -> Interval

-- | the (possibly unbounded) period during which this transaction recurs.
--   Contains a whole number of intervals.
[ptspan] :: PeriodicTransaction -> DateSpan

-- | the file position where the period expression starts, and where the
--   last posting ends
[ptsourcepos] :: PeriodicTransaction -> (SourcePos, SourcePos)

-- | some of Transaction's fields
[ptstatus] :: PeriodicTransaction -> Status
[ptcode] :: PeriodicTransaction -> Text
[ptdescription] :: PeriodicTransaction -> Text
[ptcomment] :: PeriodicTransaction -> Text
[pttags] :: PeriodicTransaction -> [Tag]
[ptpostings] :: PeriodicTransaction -> [Posting]
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingRealness -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting

-- | this posting's date, if different from the transaction's
[pdate] :: Posting -> Maybe Day

-- | this posting's secondary date, if different from the transaction's
[pdate2] :: Posting -> Maybe Day
[pstatus] :: Posting -> Status
[paccount] :: Posting -> AccountName
[pamount] :: Posting -> MixedAmount

-- | this posting's comment lines, as a single non-indented multi-line
--   string
[pcomment] :: Posting -> Text

-- | is this a normal balanced posting, or a virtual/unbalanced one ?
[preal] :: Posting -> PostingRealness

-- | tag names and values, extracted from the posting comment and (after
--   finalisation) the posting account's directive if any
[ptags] :: Posting -> [Tag]

-- | an expected balance in the account after this posting, in a single
--   commodity, excluding subaccounts.
[pbalanceassertion] :: Posting -> Maybe BalanceAssertion

-- | this posting's parent transaction (co-recursive types). Tying this
--   knot gets tedious, Maybe makes it easier/optional.
[ptransaction] :: Posting -> Maybe Transaction

-- | When this posting has been transformed in some way (eg its amount or
--   cost was inferred, or the account name was changed by a pivot or
--   budget report), this references the original untransformed posting
--   (which will have Nothing in this field).
[poriginal] :: Posting -> Maybe Posting
data PostingRealness
RealPosting :: PostingRealness
VirtualPosting :: PostingRealness
BalancedVirtualPosting :: PostingRealness

-- | A market price declaration made by the journal format's P directive.
--   It declares two things: a historical exchange rate between two
--   commodities, and an amount display style for the second commodity.
data PriceDirective
PriceDirective :: SourcePos -> Day -> CommoditySymbol -> Amount -> PriceDirective
[pdsourcepos] :: PriceDirective -> SourcePos
[pddate] :: PriceDirective -> Day
[pdcommodity] :: PriceDirective -> CommoditySymbol
[pdamount] :: PriceDirective -> Amount

-- | The basic numeric type used in amounts.
type Quantity = Decimal
type Quarter = Int

-- | The method used to select lots for disposal or transfer. Per-account
--   methods (scoped to the posting's account): FIFO<i>LIFO select
--   oldest</i>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<i>LIFOALL</i>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 :: ReductionMethod
LIFO :: ReductionMethod
HIFO :: ReductionMethod
AVERAGE :: ReductionMethod
SPECID :: ReductionMethod
FIFOALL :: ReductionMethod
LIFOALL :: ReductionMethod
HIFOALL :: ReductionMethod
AVERAGEALL :: ReductionMethod

-- | "Rounding strategy" - how to apply an AmountStyle's display precision
--   to a posting amount (and its cost, if any). Mainly used to customise
--   print's output, with --round=none|soft|hard|all.
data Rounding

-- | keep display precisions unchanged in amt and cost
NoRounding :: Rounding

-- | do soft rounding of amt and cost amounts (show more or fewer decimal
--   zeros to approximate the target precision, but don't hide significant
--   digits)
SoftRounding :: Rounding

-- | do hard rounding of amt (use the exact target precision, possibly
--   hiding significant digits), and soft rounding of cost
HardRounding :: Rounding

-- | do hard rounding of amt and cost
AllRounding :: Rounding

-- | One of the standard *-separated value file types known by hledger,
data SepFormat
Csv :: SepFormat
Tsv :: SepFormat
Ssv :: SepFormat
data Side
L :: Side
R :: Side

-- | A possibly incomplete year-month-day date provided by the user, to be
--   interpreted as either a date or a date span depending on context.
--   Missing parts "on the left" will be filled from the provided reference
--   date, e.g. if the year and month are missing, the reference date's
--   year and month are used. Missing parts "on the right" are assumed,
--   when interpreting as a date, to be 1, (e.g. if the year and month are
--   present but the day is missing, it means first day of that month); or
--   when interpreting as a date span, to be a wildcard (so it would mean
--   all days of that month). See the <tt>smartdate</tt> parser for more
--   examples.
--   
--   Or, one of the standard periods and a numeric offset relative to the
--   reference date: (last|this|next) (day|week|month|quarter|year), where
--   "this" means the period containing the reference date.
--   
--   Or, (last|this|next) weekdayname, where "this" "next".
--   
--   Or, (last|this|next) monthname, where "this" means the previous 1st if
--   in that month, otherwise the start of the next occurrence of that
--   month.
data SmartDate
SmartCompleteDate :: Day -> SmartDate
SmartAssumeStart :: Year -> Maybe Month -> SmartDate
SmartFromReference :: Maybe Month -> MonthDay -> SmartDate
SmartMonth :: Month -> SmartDate
SmartRelative :: Integer -> SmartInterval -> SmartDate

-- | EQ will be treated like GT
SmartRelativeMonth :: Ordering -> Month -> SmartDate
SmartRelativeWeekDay :: Ordering -> WeekDay -> SmartDate
data SmartInterval
Day :: SmartInterval
Week :: SmartInterval
Month :: SmartInterval
Quarter :: SmartInterval
Year :: SmartInterval

-- | The status of a transaction or posting, recorded with a status mark
--   (nothing, !, or *). What these mean is ultimately user defined.
data Status
Unmarked :: Status
Pending :: Status
Cleared :: Status

-- | The id of a data format understood by hledger, eg <tt>journal</tt> or
--   <tt>csv</tt>. The --output-format option selects one of these for
--   output.
data StorageFormat
Rules :: StorageFormat
Journal' :: StorageFormat
Ledger' :: StorageFormat
Timeclock :: StorageFormat
Timedot :: StorageFormat
Sep :: SepFormat -> StorageFormat

-- | A transaction modifier transformation, which adds an extra posting to
--   the matched posting's transaction. Can be like a regular posting, or
--   can have the tmprIsMultiplier flag set, indicating that it's a
--   multiplier for the matched posting's amount.
data TMPostingRule
TMPostingRule :: Posting -> Bool -> TMPostingRule
[tmprPosting] :: TMPostingRule -> Posting
[tmprIsMultiplier] :: TMPostingRule -> Bool
type Tag = (TagName, TagValue)

-- | Extra information found in a tag directive.
newtype TagDeclarationInfo
TagDeclarationInfo :: Text -> TagDeclarationInfo

-- | any comment lines following the tag directive. No tags allowed here.
[tdicomment] :: TagDeclarationInfo -> Text
type TagName = Text
type TagValue = Text
data TimeclockCode
SetBalance :: TimeclockCode
SetRequiredHours :: TimeclockCode
In :: TimeclockCode
Out :: TimeclockCode
FinalOut :: TimeclockCode
data TimeclockEntry
TimeclockEntry :: SourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> Text -> [Tag] -> TimeclockEntry
[tlsourcepos] :: TimeclockEntry -> SourcePos
[tlcode] :: TimeclockEntry -> TimeclockCode
[tldatetime] :: TimeclockEntry -> LocalTime
[tlaccount] :: TimeclockEntry -> AccountName
[tldescription] :: TimeclockEntry -> Text
[tlcomment] :: TimeclockEntry -> Text
[tltags] :: TimeclockEntry -> [Tag]
data Transaction
Transaction :: Integer -> Text -> (SourcePos, SourcePos) -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Transaction

-- | this transaction's 1-based position in the transaction stream, or 0
--   when not available
[tindex] :: Transaction -> Integer

-- | any comment lines immediately preceding this transaction
[tprecedingcomment] :: Transaction -> Text

-- | the file position where the date starts, and where the last posting
--   ends
[tsourcepos] :: Transaction -> (SourcePos, SourcePos)
[tdate] :: Transaction -> Day
[tdate2] :: Transaction -> Maybe Day
[tstatus] :: Transaction -> Status
[tcode] :: Transaction -> Text
[tdescription] :: Transaction -> Text

-- | this transaction's comment lines, as a single non-indented multi-line
--   string
[tcomment] :: Transaction -> Text

-- | tag names and values, extracted from the comment
[ttags] :: Transaction -> [Tag]

-- | this transaction's postings
[tpostings] :: Transaction -> [Posting]

-- | A transaction modifier rule. This has a query which matches postings
--   in the journal, and a list of transformations to apply to those
--   postings or their transactions. Currently there is one kind of
--   transformation: the TMPostingRule, which adds a posting ("auto
--   posting") to the transaction, optionally setting its amount to the
--   matched posting's amount multiplied by a constant.
data TransactionModifier
TransactionModifier :: Text -> [TMPostingRule] -> TransactionModifier
[tmquerytxt] :: TransactionModifier -> Text
[tmpostingrules] :: TransactionModifier -> [TMPostingRule]
type WeekDay = Int
data WhichDate
PrimaryDate :: WhichDate
SecondaryDate :: WhichDate
type YearDay = Int
type YearWeek = Int
type Year = Integer
instance GHC.Internal.Enum.Bounded Hledger.Data.Types.AccountType
instance GHC.Internal.Enum.Bounded Hledger.Data.Types.Status
instance Data.Default.Internal.Default Hledger.Data.Types.DateSpan
instance Data.Default.Internal.Default Hledger.Data.Types.Interval
instance Data.Default.Internal.Default Hledger.Data.Types.Period
instance GHC.Internal.Enum.Enum Hledger.Data.Types.AccountType
instance GHC.Internal.Enum.Enum Hledger.Data.Types.Status
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AccountAlias
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AccountType
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Amount
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AmountCost
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AmountStyle
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AssertDirective
instance GHC.Internal.Classes.Eq Hledger.Data.Types.AssertQuantifier
instance GHC.Internal.Classes.Eq Hledger.Data.Types.BalanceAssertion
instance GHC.Internal.Classes.Eq Hledger.Data.Types.BalanceData
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Commodity
instance GHC.Internal.Classes.Eq Hledger.Data.Types.CostBasis
instance GHC.Internal.Classes.Eq Hledger.Data.Types.DateSpan
instance GHC.Internal.Classes.Eq Hledger.Data.Types.DepthSpec
instance GHC.Internal.Classes.Eq Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Classes.Eq Hledger.Data.Types.EFDay
instance GHC.Internal.Classes.Eq Hledger.Data.Types.FastPathStats
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Interval
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Journal
instance GHC.Internal.Classes.Eq Hledger.Data.Types.JournalFile
instance GHC.Internal.Classes.Eq Hledger.Data.Types.JournalItem
instance GHC.Internal.Classes.Eq Hledger.Data.Types.LotId
instance GHC.Internal.Classes.Eq Hledger.Data.Types.MarketPrice
instance GHC.Internal.Classes.Eq Hledger.Data.Types.MixedAmount
instance GHC.Internal.Classes.Eq Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Classes.Eq Hledger.Data.Types.NormalSign
instance GHC.Internal.Classes.Eq Hledger.Data.Types.ParsePos
instance GHC.Internal.Classes.Eq Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Period
instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Classes.Eq Hledger.Data.Types.PeriodicTransaction
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Posting
instance GHC.Internal.Classes.Eq Hledger.Data.Types.PostingRealness
instance GHC.Internal.Classes.Eq Hledger.Data.Types.PriceDirective
instance GHC.Internal.Classes.Eq Hledger.Data.Types.ReductionMethod
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Rounding
instance GHC.Internal.Classes.Eq Hledger.Data.Types.SepFormat
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Side
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Status
instance GHC.Internal.Classes.Eq Hledger.Data.Types.StorageFormat
instance GHC.Internal.Classes.Eq Hledger.Data.Types.TMPostingRule
instance GHC.Internal.Classes.Eq Hledger.Data.Types.TagDeclarationInfo
instance GHC.Internal.Classes.Eq Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Classes.Eq Hledger.Data.Types.TimeclockEntry
instance GHC.Internal.Classes.Eq Hledger.Data.Types.Transaction
instance GHC.Internal.Classes.Eq Hledger.Data.Types.TransactionModifier
instance GHC.Internal.Classes.Eq Hledger.Data.Types.WhichDate
instance GHC.Internal.Base.Functor Hledger.Data.Types.Account
instance GHC.Internal.Base.Functor Hledger.Data.Types.PeriodData
instance GHC.Internal.Generics.Generic (Hledger.Data.Types.Account a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountAlias
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AccountType
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Amount
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountCost
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AmountStyle
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AssertDirective
instance GHC.Internal.Generics.Generic Hledger.Data.Types.AssertQuantifier
instance GHC.Internal.Generics.Generic Hledger.Data.Types.BalanceAssertion
instance GHC.Internal.Generics.Generic Hledger.Data.Types.BalanceData
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Commodity
instance GHC.Internal.Generics.Generic Hledger.Data.Types.CostBasis
instance GHC.Internal.Generics.Generic Hledger.Data.Types.DateSpan
instance GHC.Internal.Generics.Generic (Data.Decimal.DecimalRaw a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Generics.Generic Hledger.Data.Types.EFDay
instance GHC.Internal.Generics.Generic Hledger.Data.Types.FastPathStats
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Interval
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Journal
instance GHC.Internal.Generics.Generic Hledger.Data.Types.JournalFile
instance GHC.Internal.Generics.Generic Hledger.Data.Types.JournalItem
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Ledger
instance GHC.Internal.Generics.Generic Hledger.Data.Types.LotId
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MarketPrice
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MixedAmount
instance GHC.Internal.Generics.Generic Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Generics.Generic Hledger.Data.Types.ParsePos
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Period
instance GHC.Internal.Generics.Generic (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PeriodicTransaction
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Posting
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PostingRealness
instance GHC.Internal.Generics.Generic Hledger.Data.Types.PriceDirective
instance GHC.Internal.Generics.Generic Hledger.Data.Types.ReductionMethod
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Rounding
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Side
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Status
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TMPostingRule
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TagDeclarationInfo
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TimeclockEntry
instance GHC.Internal.Generics.Generic Hledger.Data.Types.Transaction
instance GHC.Internal.Generics.Generic Hledger.Data.Types.TransactionModifier
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts [a]
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (GHC.Internal.Maybe.Maybe a)
instance (Hledger.Data.Types.HasAmounts a, Hledger.Data.Types.HasAmounts b) => Hledger.Data.Types.HasAmounts (a, b)
instance GHC.Internal.Base.Monoid Hledger.Data.Types.DepthSpec
instance GHC.Internal.Base.Monoid Hledger.Data.Types.FastPathStats
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountAlias
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountType
instance Control.DeepSeq.NFData Hledger.Data.Types.Amount
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountCost
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountPrecision
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.AssertDirective
instance Control.DeepSeq.NFData Hledger.Data.Types.AssertQuantifier
instance Control.DeepSeq.NFData Hledger.Data.Types.BalanceAssertion
instance Control.DeepSeq.NFData Hledger.Data.Types.Commodity
instance Control.DeepSeq.NFData Hledger.Data.Types.CostBasis
instance Control.DeepSeq.NFData Hledger.Data.Types.DateSpan
instance Control.DeepSeq.NFData Hledger.Data.Types.DigitGroupStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.EFDay
instance Control.DeepSeq.NFData Hledger.Data.Types.FastPathStats
instance Control.DeepSeq.NFData Hledger.Data.Types.Interval
instance Control.DeepSeq.NFData Hledger.Data.Types.Journal
instance Control.DeepSeq.NFData Hledger.Data.Types.JournalFile
instance Control.DeepSeq.NFData Hledger.Data.Types.JournalItem
instance Control.DeepSeq.NFData Hledger.Data.Types.LotId
instance Control.DeepSeq.NFData Hledger.Data.Types.MarketPrice
instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmount
instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmountKey
instance Control.DeepSeq.NFData Hledger.Data.Types.ParsePos
instance Control.DeepSeq.NFData Hledger.Data.Types.PayeeDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.PeriodicTransaction
instance Control.DeepSeq.NFData Hledger.Data.Types.Posting
instance Control.DeepSeq.NFData Hledger.Data.Types.PostingRealness
instance Control.DeepSeq.NFData Hledger.Data.Types.PriceDirective
instance Control.DeepSeq.NFData Hledger.Data.Types.ReductionMethod
instance Control.DeepSeq.NFData Hledger.Data.Types.Rounding
instance Control.DeepSeq.NFData Hledger.Data.Types.Side
instance Control.DeepSeq.NFData Hledger.Data.Types.Status
instance Control.DeepSeq.NFData Hledger.Data.Types.TMPostingRule
instance Control.DeepSeq.NFData Hledger.Data.Types.TagDeclarationInfo
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockCode
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockEntry
instance Control.DeepSeq.NFData Hledger.Data.Types.Transaction
instance Control.DeepSeq.NFData Hledger.Data.Types.TransactionModifier
instance GHC.Internal.Classes.Ord Hledger.Data.Types.AccountAlias
instance GHC.Internal.Classes.Ord Hledger.Data.Types.AccountType
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Amount
instance GHC.Internal.Classes.Ord Hledger.Data.Types.AmountCost
instance GHC.Internal.Classes.Ord Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Classes.Ord Hledger.Data.Types.AmountStyle
instance GHC.Internal.Classes.Ord Hledger.Data.Types.CostBasis
instance GHC.Internal.Classes.Ord Hledger.Data.Types.DateSpan
instance GHC.Internal.Classes.Ord Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Classes.Ord Hledger.Data.Types.EFDay
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Interval
instance GHC.Internal.Classes.Ord Hledger.Data.Types.LotId
instance GHC.Internal.Classes.Ord Hledger.Data.Types.MarketPrice
instance GHC.Internal.Classes.Ord Hledger.Data.Types.MixedAmount
instance GHC.Internal.Classes.Ord Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Period
instance GHC.Internal.Classes.Ord a => GHC.Internal.Classes.Ord (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Classes.Ord Hledger.Data.Types.PriceDirective
instance GHC.Internal.Classes.Ord Hledger.Data.Types.ReductionMethod
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Rounding
instance GHC.Internal.Classes.Ord Hledger.Data.Types.SepFormat
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Side
instance GHC.Internal.Classes.Ord Hledger.Data.Types.Status
instance GHC.Internal.Classes.Ord Hledger.Data.Types.StorageFormat
instance GHC.Internal.Classes.Ord Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Classes.Ord Hledger.Data.Types.TimeclockEntry
instance GHC.Internal.Read.Read Hledger.Data.Types.AccountAlias
instance GHC.Internal.Read.Read Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Read.Read Hledger.Data.Types.AmountStyle
instance GHC.Internal.Read.Read Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Read.Read Hledger.Data.Types.ReductionMethod
instance GHC.Internal.Read.Read Hledger.Data.Types.Rounding
instance GHC.Internal.Read.Read Hledger.Data.Types.Side
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.DepthSpec
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.FastPathStats
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountAlias
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.AccountType
instance GHC.Internal.Show.Show Hledger.Data.Types.Amount
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountCost
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountPrecision
instance GHC.Internal.Show.Show Hledger.Data.Types.AmountStyle
instance GHC.Internal.Show.Show Hledger.Data.Types.AssertQuantifier
instance GHC.Internal.Show.Show Hledger.Data.Types.BalanceAssertion
instance GHC.Internal.Show.Show Hledger.Data.Types.Commodity
instance GHC.Internal.Show.Show Hledger.Data.Types.CostBasis
instance GHC.Internal.Show.Show Hledger.Data.Types.DepthSpec
instance GHC.Internal.Show.Show Hledger.Data.Types.DigitGroupStyle
instance GHC.Internal.Show.Show Hledger.Data.Types.EFDay
instance GHC.Internal.Show.Show Hledger.Data.Types.FastPathStats
instance GHC.Internal.Show.Show Hledger.Data.Types.Interval
instance GHC.Internal.Show.Show Hledger.Data.Types.JournalFile
instance GHC.Internal.Show.Show Hledger.Data.Types.JournalItem
instance GHC.Internal.Show.Show Hledger.Data.Types.LotId
instance GHC.Internal.Show.Show Hledger.Data.Types.MarketPrice
instance GHC.Internal.Show.Show Hledger.Data.Types.MixedAmount
instance GHC.Internal.Show.Show Hledger.Data.Types.MixedAmountKey
instance GHC.Internal.Show.Show Hledger.Data.Types.NormalSign
instance GHC.Internal.Show.Show Hledger.Data.Types.ParsePos
instance GHC.Internal.Show.Show Hledger.Data.Types.PayeeDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.Period
instance GHC.Internal.Show.Show Hledger.Data.Types.Posting
instance GHC.Internal.Show.Show Hledger.Data.Types.PostingRealness
instance GHC.Internal.Show.Show Hledger.Data.Types.PriceDirective
instance GHC.Internal.Show.Show Hledger.Data.Types.ReductionMethod
instance GHC.Internal.Show.Show Hledger.Data.Types.Rounding
instance GHC.Internal.Show.Show Hledger.Data.Types.SepFormat
instance GHC.Internal.Show.Show Hledger.Data.Types.Side
instance GHC.Internal.Show.Show Hledger.Data.Types.SmartDate
instance GHC.Internal.Show.Show Hledger.Data.Types.SmartInterval
instance GHC.Internal.Show.Show Hledger.Data.Types.Status
instance GHC.Internal.Show.Show Hledger.Data.Types.StorageFormat
instance GHC.Internal.Show.Show Hledger.Data.Types.TMPostingRule
instance GHC.Internal.Show.Show Hledger.Data.Types.TagDeclarationInfo
instance GHC.Internal.Show.Show Hledger.Data.Types.Transaction
instance GHC.Internal.Show.Show Hledger.Data.Types.TransactionModifier
instance GHC.Internal.Show.Show Hledger.Data.Types.WhichDate
instance Text.Blaze.ToMarkup Hledger.Data.Types.Quantity


-- | Manipulate the time periods typically used for reports with Period, a
--   richer abstraction than DateSpan. See also Types and Dates.
module Hledger.Data.Period

-- | Convert Periods to exact DateSpans.
--   
--   <pre>
--   &gt;&gt;&gt; periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ Flex $ fromGregorian 2000 1 1) (Just $ Flex $ fromGregorian 2000 2 1)
--   True
--   </pre>
periodAsDateSpan :: Period -> DateSpan

-- | Convert DateSpans to Periods.
--   
--   <pre>
--   &gt;&gt;&gt; dateSpanAsPeriod $ DateSpan (Just $ Exact $ fromGregorian 2000 1 1) (Just $ Exact $ fromGregorian 2000 2 1)
--   MonthPeriod 2000 1
--   </pre>
dateSpanAsPeriod :: DateSpan -> Period

-- | Convert PeriodBetweens to a more abstract period where possible.
--   
--   <pre>
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)
--   YearPeriod 1
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)
--   QuarterPeriod 2000 4
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)
--   MonthPeriod 2000 2
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)
--   WeekPeriod 2016-07-25
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)
--   DayPeriod 2000-01-01
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)
--   PeriodBetween 2000-02-28 2000-03-01
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)
--   DayPeriod 2000-02-29
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)
--   DayPeriod 2000-12-31
--   </pre>
simplifyPeriod :: Period -> Period
isLastDayOfMonth :: (Eq a1, Eq a2, Num a1, Num a2) => Year -> a1 -> a2 -> Bool

-- | Is this period a "standard" period, referencing a particular day,
--   week, month, quarter, or year ? Periods of other durations, or
--   infinite duration, or not starting on a standard period boundary, are
--   not.
isStandardPeriod :: Period -> Bool

-- | The width of a period of this type when displayed.
periodTextWidth :: Period -> Int

-- | Render a period as a compact display string suitable for user output.
--   
--   <pre>
--   &gt;&gt;&gt; showPeriod (WeekPeriod (fromGregorian 2016 7 25))
--   "2016-W30"
--   
--   &gt;&gt;&gt; showPeriod (WeekPeriod (fromGregorian 2024 12 30))
--   "2025-W01"
--   </pre>
showPeriod :: Period -> Text

-- | Like showPeriod, but if it's a month or week period show an
--   abbreviated form. &gt;&gt;&gt; showPeriodAbbrev (WeekPeriod
--   (fromGregorian 2016 7 25)) <a>W30</a> &gt;&gt;&gt; showPeriodAbbrev
--   (WeekPeriod (fromGregorian 2024 12 30)) <a>W01</a>
showPeriodAbbrev :: Period -> Text

-- | Like showPeriodAbbrev, but take the month names from this time locale.
showPeriodAbbrevWith :: TimeLocale -> Period -> Text
periodStart :: Period -> Maybe Day
periodEnd :: Period -> Maybe Day

-- | Move a standard period to the following period of same duration.
--   Non-standard periods are unaffected.
periodNext :: Period -> Period

-- | Move a standard period to the preceding period of same duration.
--   Non-standard periods are unaffected.
periodPrevious :: Period -> Period

-- | Move a standard period to the following period of same duration,
--   staying within enclosing dates. Non-standard periods are unaffected.
periodNextIn :: DateSpan -> Period -> Period

-- | Move a standard period to the preceding period of same duration,
--   staying within enclosing dates. Non-standard periods are unaffected.
periodPreviousIn :: DateSpan -> Period -> Period

-- | Move a standard period stepwise so that it encloses the given date.
--   Non-standard periods are unaffected.
periodMoveTo :: Day -> Period -> Period

-- | Enlarge a standard period to the next larger enclosing standard
--   period, if there is one. Eg, a day becomes the enclosing week. A week
--   becomes whichever month the week's thursday falls into. A year becomes
--   all (unlimited). Non-standard periods (arbitrary dates, or open-ended)
--   are unaffected.
periodGrow :: Period -> Period

-- | Shrink a period to the next smaller standard period inside it,
--   choosing the subperiod which contains today's date if possible,
--   otherwise the first subperiod. It goes like this: unbounded periods
--   and nonstandard periods (between two arbitrary dates) -&gt; current
--   year -&gt; current quarter if it's in selected year, otherwise first
--   quarter of selected year -&gt; current month if it's in selected
--   quarter, otherwise first month of selected quarter -&gt; current week
--   if it's in selected month, otherwise first week of selected month
--   -&gt; today if it's in selected week, otherwise first day of selected
--   week, unless that's in previous month, in which case first day of
--   month containing selected week. Shrinking a day has no effect.
periodShrink :: Day -> Period -> Period
mondayBefore :: Day -> Day
thursdayOfWeekContaining :: Day -> Day
yearMonthContainingWeekStarting :: Day -> (Year, MonthOfYear)
quarterContainingMonth :: Integral a => a -> a
firstMonthOfQuarter :: Num a => a -> a
startOfFirstWeekInMonth :: Year -> MonthOfYear -> Day


-- | Helpers for working with <a>AccountType</a>s. Subtypes (Cash,
--   Conversion, Gain, UnrealisedGain, Imbalance) are recognised as their
--   parent type where appropriate.
module Hledger.Data.AccountType

-- | Check whether the first argument is a subtype of the second: either
--   equal or one of the defined subtypes.
isAccountSubtypeOf :: AccountType -> AccountType -> Bool

-- | Is this an Asset or Cash (subtype of Asset) account type ?
isAssetType :: AccountType -> Bool

-- | Is this a Liability account type ?
isLiabilityType :: AccountType -> Bool

-- | Is this an Equity or Conversion (subtype of Equity) account type ?
isEquityType :: AccountType -> Bool

-- | Is this a Revenue or Gain (subtype of Revenue) account type ?
isRevenueType :: AccountType -> Bool

-- | Is this an Expense account type ?
isExpenseType :: AccountType -> Bool

-- | An account type's long-form name (its one-letter code is its
--   <a>show</a> value).
accountTypeName :: AccountType -> Text

-- | 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

-- | The account type codes, and if permitted their long-form names, for
--   showing in messages.
accountTypeChoices :: Bool -> String

-- | 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 :: LotDirection
Short :: LotDirection

-- | 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

-- | 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
instance GHC.Internal.Classes.Eq Hledger.Data.AccountType.LotDirection
instance GHC.Internal.Classes.Ord Hledger.Data.AccountType.LotDirection
instance GHC.Internal.Show.Show Hledger.Data.AccountType.LotDirection


-- | Helpers and CSS styles for HTML output.
module Hledger.Write.Html.Attribute
stylesheet :: [(Text, Text)] -> Text
tableStylesheet :: Text
tableStyle :: [(Text, Text)]

-- | Rules for the border classes emitted by <a>Hledger.Write.Html</a>, one
--   per side and line kind, eg <tt>.border-top-double</tt>. No color is
--   given, so the lines take the text color and stay visible on any
--   background.
borderStyle :: [(Text, Text)]
bold :: Text
alignright :: Text
alignleft :: Text
aligncenter :: Text
collapse :: Text
lpad :: Text
rpad :: Text
hpad :: Text
vpad :: Text


-- | Rendering a journal's items back to journal format, reproducing the
--   original journal file(s). Used by print --export.
module Hledger.Write.Journal

-- | How to render each kind of journal item in some output format.
data ItemRenderer
ItemRenderer :: (Transaction -> Text) -> (Text -> Maybe Text) -> (Text -> Text) -> (Text -> Text) -> ItemRenderer

-- | render a transaction, without a trailing blank line
[irTransaction] :: ItemRenderer -> Transaction -> Text

-- | render a directive given as source text, or drop it (Nothing)
[irDirective] :: ItemRenderer -> Text -> Maybe Text

-- | render a top-level comment line
[irComment] :: ItemRenderer -> Text -> Text

-- | render a comment ... end comment block
[irCommentBlock] :: ItemRenderer -> Text -> Text

-- | 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

-- | 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] -> Text


-- | Calculate the width of String and Text, being aware of wide
--   characters.
module Text.WideString

-- | Helper for constructing Builders while keeping track of text width.
data WideBuilder
WideBuilder :: Builder -> Int -> WideBuilder
[wbBuilder] :: WideBuilder -> Builder
[wbWidth] :: WideBuilder -> Int

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a strict Text to a WideBuilder.
wbFromText :: Text -> WideBuilder
instance GHC.Internal.Base.Monoid Text.WideString.WideBuilder
instance GHC.Internal.Base.Semigroup Text.WideString.WideBuilder
instance GHC.Internal.Show.Show Text.WideString.WideBuilder


-- | Text.Tabular.AsciiArt from tabular-0.2.2.7, modified to treat wide
--   characters as double width.
module Text.Tabular.AsciiWide
(+----+) :: Table rh ch a -> SemiTable rh a -> Table rh ch a
(+.+) :: Table rh ch a -> SemiTable rh a -> Table rh ch a
(+====+) :: Table rh ch a -> SemiTable rh a -> Table rh ch a
(^..^) :: Table rh ch a -> SemiTable ch a -> Table rh ch a
(^|^) :: Table rh ch a -> SemiTable ch a -> Table rh ch a
(^||^) :: Table rh ch a -> SemiTable ch a -> Table rh ch a
below :: Properties -> Table rh ch a -> SemiTable rh a -> Table rh ch a
beside :: Properties -> Table rh ch a -> SemiTable ch a -> Table rh ch a
col :: ch -> [a] -> SemiTable ch a
colH :: ch -> SemiTable ch a
empty :: Table rh ch a
flattenHeader :: Header h -> [Either Properties h]
headerContents :: Header h -> [h]
row :: rh -> [a] -> SemiTable rh a
rowH :: rh -> SemiTable rh a
squish :: (Properties -> b -> b) -> (h -> b) -> Header h -> [b]
zipHeader :: h -> [h] -> Header a -> Header (h, a)
data Header h
Header :: h -> Header h
Group :: Properties -> [Header h] -> Header h
data Properties
NoLine :: Properties
SingleLine :: Properties
DoubleLine :: Properties
data SemiTable h a
SemiTable :: Header h -> [a] -> SemiTable h a
data Table rh ch a
Table :: Header rh -> Header ch -> [[a]] -> Table rh ch a

-- | The options to use for rendering a table.
data TableOpts
TableOpts :: Bool -> Bool -> Bool -> TableOpts

-- | Pretty tables
[prettyTable] :: TableOpts -> Bool

-- | Whether to display the outer borders
[tableBorders] :: TableOpts -> Bool

-- | Whether to display spaces around bars
[borderSpaces] :: TableOpts -> Bool

-- | Render a table according to common options, for backwards
--   compatibility
render :: Show a => Bool -> (rh -> Text) -> (ch -> Text) -> (a -> Text) -> Table rh ch a -> Text

-- | Render a table according to various cell specifications&gt;
renderTable :: Show a => TableOpts -> (rh -> Cell) -> (ch -> Cell) -> (a -> Cell) -> Table rh ch a -> Text

-- | A version of renderTable which returns the underlying Builder.
renderTableB :: Show a => TableOpts -> (rh -> Cell) -> (ch -> Cell) -> (a -> Cell) -> Table rh ch a -> Builder

-- | A version of renderTable that operates on rows (including the
--   <a>row</a> of column headers) and returns the underlying Builder.
renderTableByRowsB :: Show a => TableOpts -> ([ch] -> [Cell]) -> ((rh, [a]) -> (Cell, [Cell])) -> Table rh ch a -> Builder

-- | Render a single row according to cell specifications.
renderRow :: TableOpts -> Header Cell -> Text

-- | A version of renderRow which returns the underlying Builder.
renderRowB :: TableOpts -> Header Cell -> Builder

-- | We stop rendering on the shortest list!
renderColumns :: TableOpts -> [Int] -> Header Cell -> Builder

-- | Cell contents along an alignment
data Cell
Cell :: Align -> [WideBuilder] -> Cell

-- | How to align text in a cell
data Align
TopRight :: Align
BottomRight :: Align
BottomLeft :: Align
TopLeft :: Align
emptyCell :: Cell

-- | Create a single-line cell from the given contents with its natural
--   width.
textCell :: Align -> Text -> Cell

-- | Create a multi-line cell from the given contents with its natural
--   width.
textsCell :: Align -> [Text] -> Cell

-- | Return the width of a Cell.
cellWidth :: Cell -> Int

-- | Add the second table below the first, discarding its column headings.
concatTables :: Properties -> Table rh ch a -> Table rh ch2 a -> Table rh ch a
instance Data.Default.Internal.Default Text.Tabular.AsciiWide.TableOpts
instance GHC.Internal.Show.Show Text.Tabular.AsciiWide.Align
instance GHC.Internal.Show.Show Text.Tabular.AsciiWide.TableOpts


-- | Text formatting helpers, ported from String as needed. There may be
--   better alternatives out there.
module Hledger.Utils.Text
textCapitalise :: Text -> Text

-- | Remove all matching pairs of square brackets and parentheses from the
--   text.
textUnbracket :: Text -> Text

-- | Wrap a Text with the surrounding Text.
wrap :: Text -> Text -> Text -> Text

-- | Remove trailing newlines/carriage returns.
textChomp :: Text -> Text

-- | 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 :: Text -> Text

-- | 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 :: Text -> Text
textQuoteIfNeeded :: Text -> Text
escapeDoubleQuotes :: Text -> Text
escapeBackslash :: Text -> Text

-- | Strip one matching pair of single or double quotes on the ends of a
--   string.
textStripQuotes :: Text -> Text
textElideRight :: Int -> Text -> Text

-- | Clip and pad a string to a minimum &amp; maximum width, and<i>or
--   left</i>right justify it. Works on multi-line strings too (but will
--   rewrite non-unix line endings).
formatText :: Bool -> Maybe Int -> Maybe Int -> Text -> Text

-- | Join several multi-line strings as side-by-side rectangular strings of
--   the same height, top-padded. Treats wide characters as double width.
textConcatTopPadded :: [Text] -> Text

-- | Join several multi-line strings as side-by-side rectangular strings of
--   the same height, bottom-padded. Treats wide characters as double
--   width.
textConcatBottomPadded :: [Text] -> Text

-- | General-purpose wide-char-aware single-line text layout function. It
--   can left- or right-pad a short string to a minimum width. It can left-
--   or right-clip a long string to a maximum width, optionally inserting
--   an ellipsis (the third argument). It clips and pads on the right when
--   the fourth argument is true, otherwise on the left. It treats wide
--   characters as double width.
fitText :: Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text

-- | Add a prefix to each line of a string.
linesPrepend :: Text -> Text -> Text

-- | Add a prefix to the first line of a string, and a different prefix to
--   the remaining lines.
linesPrepend2 :: Text -> Text -> Text -> Text

-- | Join a list of Text Builders with a newline after each item.
unlinesB :: [Builder] -> Builder

-- | Helper for constructing Builders while keeping track of text width.
data WideBuilder
WideBuilder :: Builder -> Int -> WideBuilder
[wbBuilder] :: WideBuilder -> Builder
[wbWidth] :: WideBuilder -> Int

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a strict Text to a WideBuilder.
wbFromText :: Text -> WideBuilder

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Double-width-character-aware string truncation. Take as many
--   characters as possible from a string without exceeding the specified
--   width. Eg textTakeWidth 3 "りんご" = "り".
textTakeWidth :: Int -> Text -> Text

-- | Read a decimal number from a Text. Assumes the input consists only of
--   digit characters.
readDecimal :: Text -> Integer
tests_Text :: TestTree


-- | General and hledger-specific input/output-related helpers for
--   pretty-printing haskell values, error reporting, time, files, command
--   line parsing, terminals, pager output, ANSI colour/styles, etc.
module Hledger.Utils.IO

-- | Pretty show. An easier alias for pretty-simple's pShow. This will
--   probably show in colour if useColorOnStderrUnsafe is true.
pshow :: Show a => a -> String

-- | Monochrome version of pshow. This will never show in colour.
pshow' :: Show a => a -> String

-- | Pretty print a showable value. An easier alias for pretty-simple's
--   pPrint. This will print in colour if useColorOnStderrUnsafe is true.
pprint :: Show a => a -> IO ()

-- | Monochrome version of pprint. This will never print in colour.
pprint' :: Show a => a -> IO ()

-- | Call errorWithoutStackTrace, prepending a "Error:" label.
error' :: String -> a

-- | Like error', but add a hint about using -h (on its own line, if the
--   message has several lines).
usageError :: String -> a

-- | Show a warning message on stderr before returning the given value.
--   Like trace, but prepends a "Warning:" label, and does some ANSI
--   styling of the first line when allowed (using unsafe IO). Currently we
--   use this very sparingly in hledger; we prefer to either quietly work,
--   or loudly raise an error. Varying output can make scripting harder.
--   But on stderr, it shouldn't cause much hassle.
warn :: String -> a -> a

-- | 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 ()

-- | 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 ()

-- | Apply standard ANSI SGR formatting (red, bold) suitable for console
--   error text.
ansiFormatError :: String -> String

-- | Apply standard ANSI SGR formatting (yellow, bold) suitable for console
--   warning text.
ansiFormatWarning :: String -> String

-- | Print an error message to stderr, with a consistent "programname: "
--   prefix, and applying ANSI styling (bold bright red) to the first line
--   if that is supported and allowed.
printError :: String -> IO ()

-- | Print an error message with printError, then exit the program with a
--   non-zero exit code.
exitWithErrorMessage :: String -> IO ()

-- | This wraps a program's main routine so as to display more consistent,
--   useful, and GHC-version-independent error output when the program
--   exits because of certain common exceptions. It
--   
--   <ol>
--   <li>disables SIGPIPE errors, which are usually harmless, caused when
--   our output is truncated in a piped command.</li>
--   <li>catches these common exceptions:</li>
--   </ol>
--   
--   <ul>
--   <li>UnicodeException, caused eg by text decoding errors in pure
--   code</li>
--   <li>IOException, caused by I<i>O errors, including text decoding
--   errors during I</i>O</li>
--   <li>ErrorCall - <tt>error</tt> / <tt>errorWithoutStackTrace</tt>
--   calls</li>
--   </ul>
--   
--   <ol>
--   <li>compensates for GHC output bugs:</li>
--   </ol>
--   
--   <ul>
--   <li>removes the trailing newlines added by some GHC 9.10.*
--   versions</li>
--   <li>removes "uncaught exception" output added by some GHC 9.12.*
--   versions</li>
--   <li>ensures a consistent "PROGNAME: " prefix</li>
--   </ul>
--   
--   <ol>
--   <li>applies bold bright red ANSI styling to the first line of error
--   output, if that is supported and allowed</li>
--   <li>for unicode exceptions and I/O exceptions which look like they
--   were unicode-related, it adds a message (in english) explaining the
--   problem and what to do.</li>
--   </ol>
--   
--   Some exceptions this does not catch are ExitCode
--   (exitSuccess<i>exitFailure</i>exitWith) and UserInterrupt (control-C).
handleExit :: IO () -> IO ()
getCurrentLocalTime :: IO LocalTime
getCurrentZonedTime :: IO ZonedTime

-- | 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

-- | 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

-- | Like getHomeDirectory, but in case of IO error (home directory not
--   found, not understood, etc.), returns "".
getHomeSafe :: IO (Maybe FilePath)

-- | Like embedFile, but takes a path relative to the package directory.
embedFileRelative :: FilePath -> Q Exp

-- | 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

-- | Expand a single tilde (representing home directory) at the start of a
--   file path. ~username is not supported. This can raise an IO error.
expandHomePath :: FilePath -> IO FilePath

-- | Given a current directory, convert a possibly relative, possibly
--   tilde-prefixed file path to an absolute one. ~username is not
--   supported. If the file path is "-", it is left as-is. This can an
--   raise an IO error.
expandPath :: FilePath -> FilePath -> IO FilePath

-- | Like <tt>expandPath</tt>, but treats the expanded path as a glob, and
--   returns zero or more matched absolute file paths, alphabetically
--   sorted. Can raise an error. For a more elaborate glob expander, see
--   <tt>findMatchedFiles</tt> (used by the include directive).
expandGlob :: FilePath -> FilePath -> IO [FilePath]

-- | Like expandPath, but if the path contains glob metacharacters (* ? [
--   {), treats it as a glob pattern and expands it, returning the first
--   match. Raises an error if the glob pattern matches no files. If the
--   path contains no glob metacharacters, just expands ~ and returns the
--   path, even if the file doesn't exist yet. This is useful for options
--   like -f and LEDGER_FILE that should: - accept non-existent files (for
--   commands like add/import that create them) - expand glob patterns and
--   error if they don't match anything
expandPathOrGlob :: FilePath -> FilePath -> IO FilePath

-- | Given a list of existing file paths, sort them by modification time
--   (from oldest to newest).
sortByModTime :: [FilePath] -> IO [FilePath]

-- | Open a file for reading, using the standard System.IO.openFile. This
--   opens the handle in text mode, using the initial system locale's text
--   encoding.
openFileOrStdin :: String -> IO Handle

-- | Run an action with a handle for writing, opening the given file path
--   in the given mode, or returning <a>stdout</a> if the path is "-". When
--   opening a real file, the handle is closed at the end (like
--   <a>withFile</a>); when using stdout, it is left open for the rest of
--   the program.
withFileOrStdout :: FilePath -> IOMode -> (Handle -> IO r) -> IO r

-- | Verify that the filesystem at <tt>dir</tt> honors O_APPEND, by doing a
--   quick test with a dummy file there (.hledger-append-test*). Returns
--   True if writes opened in <a>AppendMode</a> 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 <a>appendFile</a> actually overwrites the
--   file, potentially causing severe data loss (#2577).
ensureFilesystemCanAppend :: FilePath -> IO Bool

-- | Like readFilePortably, but read from standard input if the path is
--   "-".
readFileOrStdinPortably :: String -> IO Text

-- | Like readFileOrStdinPortably, but take an optional converter.
readFileOrStdinPortably' :: Maybe DynEncoding -> String -> IO Text

-- | Like readFilePortably, but read all of the file before proceeding.
readFileStrictly :: FilePath -> IO Text

-- | Read text from a file, converting any rn line endings to n,, using the
--   system locale's text encoding, ignoring any utf8 BOM prefix (as seen
--   in paypal's 2018 CSV, eg) if that encoding is utf8.
readFilePortably :: FilePath -> IO Text

-- | Read text from a handle, perhaps using a specified encoding from the
--   encoding package. Or if no encoding is specified, using the handle's
--   current encoding, changing it to UTF-8BOM if it was UTF-8, to ignore
--   any Byte Order Mark at the start. Also it converts Windows line
--   endings to newlines. If decoding fails, this throws an IOException (or
--   possibly a UnicodeException or something else from the encoding
--   package).
hGetContentsPortably :: Maybe DynEncoding -> Handle -> IO Text

-- | Create a handle from which the given text can be read. Its encoding
--   will be UTF-8.
textToHandle :: Text -> IO Handle

-- | The program's command line arguments. Uses unsafePerformIO; tends to
--   stick in GHCI until reloaded, and may or may not detect args provided
--   by a hledger config file.
progArgs :: [String]

-- | Given one or more long or short flag names, report whether this flag
--   is present in the command line. Concatenated short flags (-a -b
--   written as -ab) are not supported.
getFlag :: [String] -> IO Bool

-- | Given one or more long or short option names, read the rightmost value
--   of this option from the command line arguments. If the value is
--   missing raise an error. Concatenated short flags (-a -b written as
--   -ab) are not supported.
getOpt :: [String] -> IO (Maybe String)

-- | Parse y<i>yes</i>always or n<i>no</i>never to true or false, or return
--   an error message.
parseYN :: String -> Either String Bool

-- | Parse y<i>yes</i>always or n<i>no</i>never or a/auto to a YNA choice,
--   or return an error message.
parseYNA :: String -> Either String YNA
data YNA
Yes :: YNA
No :: YNA
Auto :: YNA

-- | An alternative to ansi-terminal's getTerminalSize, based on the more
--   robust-looking terminal-size package.
--   
--   Tries to get stdout's terminal's current height and width.
getTerminalHeightWidth :: IO (Maybe (Int, Int))
getTerminalHeight :: IO (Maybe Int)
getTerminalWidth :: IO (Maybe Int)

-- | 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

-- | Try to find a pager executable robustly, safely handling various error
--   conditions like an unset PATH var or the specified pager not being
--   found as an executable. The pager can be specified by a path or
--   program name in the PAGER environment variable. If that is unset or
--   has a problem, "less" is tried, then "more". If successful, the
--   pager's path or program name is returned.
findPager :: IO (Maybe String)

-- | Display the given text on the terminal, trying to use a pager ($PAGER,
--   less, or more) when appropriate (see maybePagerFor), otherwise
--   printing to standard output. Also, if the pager is less, we modify the
--   LESS environment variable (see lessVarValue) and check for problems
--   which could cause confusing output (see lessIsWorking).
runPager :: String -> IO ()

-- | Compute the LESS environment variable value that hledger will use for
--   the less pager. This used in runPager when invoking less, and also in
--   the setup command for display. It takes the current HLEDGER_LESS and
--   LESS env var values, and whether we are showing colour on stdout, and
--   returns the adjusted LESS value that should be used. Specifically:
--   
--   <ul>
--   <li>If HLEDGER_LESS is defined, we use it in place of the LESS
--   environment variable.</li>
--   <li>Otherwise, if LESS is defined, append some preferred options
--   (lessOptions and maybe lessColourOptions) to it.</li>
--   <li>Otherwise, we set LESS to just use those preferred options.</li>
--   </ul>
lessVarValue :: Maybe String -> Maybe String -> Bool -> String

-- | Test <tt>less</tt>, by running less --version and looking for a
--   nonzero exit, timeout, or stderr output. Uses the provided
--   environment, containing a LESS variable, if any. We do this because
--   various LESS settings can cause some less versions to fail or cause
--   confusing output without failing.
lessIsWorking :: Maybe [(String, String)] -> IO Bool

-- | Get the value of the rightmost --color or --colour option from the
--   program's command line arguments. Throws an error if the option's
--   value could not be parsed.
colorOption :: IO YNA

-- | Should ANSI color and styles be used for standard output ? Considers
--   useColorOnHandle stdout and hasOutputFile.
useColorOnStdout :: IO Bool

-- | Should ANSI color and styles be used for standard error output ?
--   Considers useColorOnHandle stderr; is not affected by an --output-file
--   option.
useColorOnStderr :: IO Bool

-- | Like useColorOnStdout, but using unsafePerformIO. Useful eg for
--   low-level debug code. Sticky in GHCI until reloaded, may not always be
--   affected by --color in a hledger config file, etc.
useColorOnStdoutUnsafe :: Bool

-- | Like useColorOnStdoutUnsafe, but for stderr.
useColorOnStderrUnsafe :: Bool

-- | 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<i>tmux</i>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,
--   <a>rgb'</a> downgrades to the nearest xterm 256-colour.
supportsTrueColor :: IO Bool

-- | Like <a>supportsTrueColor</a>, but using unsafePerformIO.
supportsTrueColorUnsafe :: Bool

-- | Set various ANSI styles/colours in a string, only if
--   useColorOnStdoutUnsafe says we should.
bold' :: String -> String
faint' :: String -> String
black' :: String -> String
red' :: String -> String
green' :: String -> String
yellow' :: String -> String
blue' :: String -> String
magenta' :: String -> String
cyan' :: String -> String
white' :: String -> String
brightBlack' :: String -> String
brightRed' :: String -> String
brightGreen' :: String -> String
brightYellow' :: String -> String
brightBlue' :: String -> String
brightMagenta' :: String -> String
brightCyan' :: String -> String
brightWhite' :: String -> String
rgb' :: Float -> Float -> Float -> String -> String
sgrresetall :: String

-- | 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

-- | Colour a string with hledger's diagonal blue-to-green gradient: each
--   character's colour depends on its position (<tt>row</tt>, and column
--   counting from <tt>col0</tt>) within a grid <tt>h</tt> rows tall and
--   <tt>w</tt> 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 <a>bold'</a> or <a>faint'</a>); 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

-- | Render a title heading coloured with hledger's blue-to-green bold
--   gradient, when colour is enabled.
titleLine :: String -> String

-- | 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

-- | Wrap a string in ANSI codes to set and reset foreground colour.
--   ColorIntensity is <tt>Dull</tt> or <tt>Vivid</tt> (ie normal and
--   bold). Color is one of <tt>Black</tt>, <tt>Red</tt>, <tt>Green</tt>,
--   <tt>Yellow</tt>, <tt>Blue</tt>, <tt>Magenta</tt>, <tt>Cyan</tt>,
--   <tt>White</tt>. Eg: <tt>color Dull Red "text"</tt>.
color :: ColorIntensity -> Color -> String -> String

-- | Wrap a string in ANSI codes to set and reset background colour.
bgColor :: ColorIntensity -> Color -> String -> String

-- | Wrap a WideBuilder in ANSI codes to set and reset foreground colour.
colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder

-- | Wrap a WideBuilder in ANSI codes to set and reset background colour.
bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder

-- | Detect whether the terminal currently has a light background colour,
--   if possible, using unsafePerformIO. If the terminal is transparent,
--   its apparent light/darkness may be different.
terminalIsLight :: Maybe Bool

-- | Detect the terminal's current background lightness (0..1), if
--   possible, using unsafePerformIO. If the terminal is transparent, its
--   apparent lightness may be different.
terminalLightness :: Maybe Float

-- | Detect the terminal's current foreground colour, if possible, using
--   unsafePerformIO.
terminalFgColor :: Maybe (RGB Float)

-- | Detect the terminal's current background colour, if possible, using
--   unsafePerformIO.
terminalBgColor :: Maybe (RGB Float)
instance GHC.Internal.Classes.Eq Hledger.Utils.IO.YNA
instance GHC.Internal.Show.Show Hledger.Utils.IO.YNA


-- | Here are debug tracing/logging helpers built on Debug.Trace, extracted
--   from the hledger project. Features:
--   
--   <ul>
--   <li>they can be built in to your program permanently, and activated by
--   a --debug [LEVEL] option</li>
--   <li>they can optionally log to a file instead of stderr (for TUI
--   apps)</li>
--   <li>they can be used in IO, pure, or startup code</li>
--   <li>values are printed with a label, and pretty-printed (using
--   pretty-simple)</li>
--   <li>ANSI colour is used when appropriate.</li>
--   </ul>
--   
--   Insert these <tt>dbg*</tt> helpers at points of interest in your code,
--   either temporarily while debugging, or permanently in production code,
--   and activate them with <tt>--debug [1-9]</tt> on the command line
--   (<tt>--debug</tt> with no value means level 1). For example, this
--   expression:
--   
--   <pre>
--   dbg4 "foo" foo
--   </pre>
--   
--   will pretty-print foo with a "foo:" label when it is evaluated, but
--   only if --debug's value is 4 or greater. In other words: use dbg1 for
--   the most useful debug output, dbg9 for the most specialised/verbose.
--   
--   They are intended to be easy to use and to find in your code, with a
--   consistent naming scheme:
--   
--   <pre>
--   dbg&lt;LEVEL&gt;Msg   STR    VAL  -- trace/log a string in pure code
--   dbg&lt;LEVEL&gt;MsgIO STR         -- trace/log a string in IO
--   
--   dbg&lt;LEVEL&gt;      STR    VAL  -- trace/log a showable value in pure code
--   dbg&lt;LEVEL&gt;IO    STR    VAL  -- trace/log a showable value in IO
--   
--   dbg&lt;LEVEL&gt;With  SHOWFN VAL  -- trace/log any value
--   </pre>
--   
--   Or if you prefer you can ignore the numbered variants and write an
--   extra argument:
--   
--   <pre>
--   dbgMsg   LEVEL  STR    VAL
--   dbgMsgIO LEVEL  STR
--   
--   dbg      LEVEL  STR    VAL
--   dbgIO    LEVEL  STR    VAL
--   
--   dbgWith  LEVEL  SHOWFN VAL
--   
--   dbgTime   LEVEL  STR    VAL  -- trace/log a phase timing: STR, and the time and memory allocated since the previous one, after deep-forcing VAL
--   dbgTimeIO LEVEL  STR    VAL  -- the same, in IO
--   </pre>
--   
--   Haskell values will be pretty-printed by default, using pretty-simple.
--   
--   ANSI color will also be used if appropriate, respecting output
--   capabilities, <tt>NO_COLOR</tt>, and/or a <tt>--color [YNA]</tt> (or
--   <tt>--colour</tt>) command line option.
--   
--   These helpers normally print output on stderr, but can automatically
--   log to a file instead, which can be useful for TUI apps which are
--   redrawing the screen. To enable this logging mode, use
--   <tt>withProgName</tt> to add a ".log" suffix to the program name:
--   
--   <pre>
--   main = withProgName "PROGRAM.log" $ do ...
--   </pre>
--   
--   Now all dbg calls will log to <tt>PROGRAM.log</tt> in the current
--   directory.
--   
--   Logging, and reading the command line/program name/output context use
--   unsafePerformIO, so that these can be used anywhere, including early
--   in your program before command line parsing is complete. As a
--   consequence, if you are testing in GHCI and want to change the debug
--   level, you'll need to reload this module.
--   
--   The <tt>dbg</tt> function name clashes with the one in
--   Text.Megaparsec.Debug, unfortunately; sorry about that. If you are
--   also using that, use qualified imports, or our <tt>dbg_</tt> alias, to
--   avoid the clash.
--   
--   The meaning of debug levels is up to you. Eg hledger uses them as
--   follows:
--   
--   <pre>
--   Debug level:  What to show:
--   ------------  ---------------------------------------------------------
--   0             normal program output only
--   1             useful warnings, most common troubleshooting info, phase timings
--   2             common troubleshooting info, more detail
--   3             report options selection
--   4             report generation
--   5             report generation, more detail
--   6             input file reading
--   7             input file reading, more detail
--   8             command line parsing
--   9             any other rarely needed / more in-depth info
--   </pre>
--   
--   It's not yet possible to select debug output by topic; that would be
--   useful.
module Hledger.Utils.Debug

-- | The program's debug output verbosity, from 0 to 9. The default is 0
--   meaning no debug output. This can be overridden by running the program
--   with a --debug [1-9] command line option; a --debug flag with no value
--   means 1. Uses unsafePerformIO to read the command line. When running
--   in GHCI, changing this requires reloading this module.
debugLevel :: Int

-- | Trace or log a string if the program debug level is at or above the
--   specified level, then return the second argument.
dbgMsg :: Int -> String -> a -> a
dbg0Msg :: String -> a -> a
dbg1Msg :: String -> a -> a
dbg2Msg :: String -> a -> a
dbg3Msg :: String -> a -> a
dbg4Msg :: String -> a -> a
dbg5Msg :: String -> a -> a
dbg6Msg :: String -> a -> a
dbg7Msg :: String -> a -> a
dbg8Msg :: String -> a -> a
dbg9Msg :: String -> a -> a

-- | Like dbgMsg, but sequences properly in IO.
dbgMsgIO :: MonadIO m => Int -> String -> m ()
dbg0MsgIO :: MonadIO m => String -> m ()
dbg1MsgIO :: MonadIO m => String -> m ()
dbg2MsgIO :: MonadIO m => String -> m ()
dbg3MsgIO :: MonadIO m => String -> m ()
dbg4MsgIO :: MonadIO m => String -> m ()
dbg5MsgIO :: MonadIO m => String -> m ()
dbg6MsgIO :: MonadIO m => String -> m ()
dbg7MsgIO :: MonadIO m => String -> m ()
dbg8MsgIO :: MonadIO m => String -> m ()
dbg9MsgIO :: MonadIO m => String -> m ()

-- | Trace or log a label and showable value, pretty-printed, if the
--   program debug level is at or above the specified level; then return
--   the value.
dbg :: Show a => Int -> String -> a -> a

-- | Alias for dbg, can be used to avoid namespace clashes.
dbg_ :: Show a => Int -> String -> a -> a
dbg0 :: Show a => String -> a -> a
dbg1 :: Show a => String -> a -> a
dbg2 :: Show a => String -> a -> a
dbg3 :: Show a => String -> a -> a
dbg4 :: Show a => String -> a -> a
dbg5 :: Show a => String -> a -> a
dbg6 :: Show a => String -> a -> a
dbg7 :: Show a => String -> a -> a
dbg8 :: Show a => String -> a -> a
dbg9 :: Show a => String -> a -> a

-- | Like dbg, but sequences properly in IO.
dbgIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
dbg0IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg1IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg2IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg3IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg4IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg5IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg6IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg7IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg8IO :: (MonadIO m, Show a) => String -> a -> m ()
dbg9IO :: (MonadIO m, Show a) => String -> a -> m ()

-- | Like dbg, but with a custom show function.
dbgWith :: Int -> (a -> String) -> a -> a
dbg0With :: (a -> String) -> a -> a
dbg1With :: (a -> String) -> a -> a
dbg2With :: (a -> String) -> a -> a
dbg3With :: (a -> String) -> a -> a
dbg4With :: (a -> String) -> a -> a
dbg5With :: (a -> String) -> a -> a
dbg6With :: (a -> String) -> a -> a
dbg7With :: (a -> String) -> a -> a
dbg8With :: (a -> String) -> a -> a
dbg9With :: (a -> String) -> a -> a

-- | 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

-- | Like dbgTime, but sequences properly in IO.
dbgTimeIO :: (MonadIO m, NFData a) => Int -> String -> a -> m a

-- | 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 ()

-- | Helper for producing debug messages: concatenates a name (eg a
--   function name), short description of the value being logged, and
--   string representation of the value.
--   
--   Eg: <tt>let lbl = lbl_ "print"</tt>, <tt>dbg1With (lbl "part 1".show)
--   ...</tt>.
lbl_ :: String -> String -> String -> String

-- | The progam name, with any ".log" suffix removed.
progName :: String

-- | Is the hledger-lib package built with ghc-debug support ?
ghcDebugSupportedInLib :: Bool

-- | Whether ghc-debug support is included in this build, and if so, how it
--   will behave. When hledger is built with the <tt>ghcdebug</tt> cabal
--   flag (off by default, because of extra deps), it can listen (on unix
--   ?) for connections from ghc-debug clients like ghc-debug-brick, for
--   pausing/resuming the program and inspecting memory usage and profile
--   information.
--   
--   With a ghc-debug-supporting build, ghc-debug can be enabled by running
--   hledger with a negative --debug level. There are three different
--   modes: --debug=-1 - run normally (can be paused/resumed by a ghc-debug
--   client), --debug=-2 - pause and await client commands at program start
--   (not useful currently), --debug=-3 - pause and await client commands
--   at program end.
data GhcDebugMode
GDNotSupported :: GhcDebugMode
GDDisabled :: GhcDebugMode
GDNoPause :: GhcDebugMode
GDPauseAtStart :: GhcDebugMode
GDPauseAtEnd :: GhcDebugMode

-- | Should the program open a socket allowing control by ghc-debug-brick
--   or similar ghc-debug client ? See GhcDebugMode.
ghcDebugMode :: GhcDebugMode

-- | When ghc-debug support has been built into the program and enabled at
--   runtime with --debug=-N, this calls ghc-debug's withGhcDebug;
--   otherwise it's a no-op.
withGhcDebug' :: a -> a

-- | When ghc-debug support has been built into the program, this calls
--   ghc-debug's pause, otherwise it's a no-op.
ghcDebugPause' :: IO ()
trace :: String -> a -> a
traceIO :: String -> IO ()
traceShowId :: Show a => a -> a
instance GHC.Internal.Classes.Eq Hledger.Utils.Debug.GhcDebugMode
instance GHC.Internal.Classes.Ord Hledger.Utils.Debug.GhcDebugMode
instance GHC.Internal.Show.Show Hledger.Utils.Debug.GhcDebugMode

module Hledger.Utils.Parse

-- | A parser of string to some type.
type SimpleStringParser a = Parsec HledgerParseErrorData String a

-- | A parser of strict text to some type.
type SimpleTextParser = Parsec HledgerParseErrorData Text

-- | A parser of text that runs in some monad.
type TextParser (m :: Type -> Type) a = ParsecT HledgerParseErrorData Text m a
data SourcePos
SourcePos :: FilePath -> Pos -> Pos -> SourcePos
[sourceName] :: SourcePos -> FilePath
[sourceLine] :: SourcePos -> Pos
[sourceColumn] :: SourcePos -> Pos
mkPos :: Int -> Pos
unPos :: Pos -> Int
initialPos :: FilePath -> SourcePos
sourcePosPretty :: SourcePos -> String

-- | 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

-- | Render a source position as FILE:LINE, without its column.
sourcePosFileLine :: SourcePos -> String

-- | Backtracking choice, use this when alternatives share a prefix.
--   Consumes no input if all choices fail.
choice' :: forall (m :: Type -> Type) a. [TextParser m a] -> TextParser m a

-- | Backtracking choice, use this when alternatives share a prefix.
--   Consumes no input if all choices fail.
choiceInState :: forall s (m :: Type -> Type) a. [StateT s (ParsecT HledgerParseErrorData Text m) a] -> StateT s (ParsecT HledgerParseErrorData Text m) a
surroundedBy :: Applicative m => m openclose -> m a -> m a
parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a

-- | Run a text parser in the identity monad. See also: parseWithState.
runTextParser :: TextParser Identity a -> Text -> Either HledgerParseErrors a

-- | Run a text parser in the identity monad. See also: parseWithState.
rtp :: TextParser Identity a -> Text -> Either HledgerParseErrors a
parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a

-- | Run a stateful parser with some initial state on a text. See also:
--   runTextParser, runJournalParser.
parseWithState :: Monad m => st -> StateT st (ParsecT HledgerParseErrorData Text m) a -> Text -> m (Either HledgerParseErrors a)
parseWithState' :: Stream s => st -> StateT st (ParsecT e s Identity) a -> s -> Either (ParseErrorBundle s e) a
fromparse :: (Show t, Show (Token t), Show e) => Either (ParseErrorBundle t e) a -> a
parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a
nonspace :: forall (m :: Type -> Type). TextParser m Char
isNewline :: Char -> Bool
isNonNewlineSpace :: Char -> Bool
restofline :: forall (m :: Type -> Type). TextParser m String
eolof :: forall (m :: Type -> Type). TextParser m ()
spacenonewline :: forall s (m :: Type -> Type). (Stream s, Char ~ Token s) => ParsecT HledgerParseErrorData s m Char
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()

-- | Skip any non-newline whitespace, and return whether there was any.
skipNonNewlineSpaces' :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool

-- | 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 :: forall (m :: Type -> Type). TextParser m (Maybe Char)

-- | Like peekChar, but returning the next two characters, if any.
peekChars2 :: forall (m :: Type -> Type). TextParser m (Maybe Char, Maybe Char)

-- | 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 :: forall (m :: Type -> Type). TextParser m (Bool, Maybe Char)

-- | 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]

-- | Trace to stderr or log to debug log the provided label (if non-null)
--   and current parser state (position and next input), if the global
--   debug level is at or above the specified level. See also:
--   Hledger.Utils.Debug, megaparsec's dbg. Uses unsafePerformIO. XXX Can
--   be hard to make this evaluate.
dbgparse :: forall (m :: Type -> Type). Int -> String -> TextParser m ()

-- | Custom error data for hledger parsers. Specialised for a <a>Text</a>
--   parse stream. ReparseableTextParseErrorData ?
data HledgerParseErrorData

-- | A specialised version of ParseErrorBundle: a non-empty collection of
--   hledger parse errors, equipped with PosState to help pretty-print
--   them. Specialised for a <a>Text</a> parse stream.
type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData

-- | Fail at a specific source position, given by the raw offset from the
--   start of the input stream (the number of tokens processed at that
--   point).
parseErrorAt :: Int -> String -> HledgerParseErrorData

-- | Fail at a specific source interval, given by the raw offsets of its
--   endpoints from the start of the input stream (the numbers of tokens
--   processed at those points).
--   
--   Note that care must be taken to ensure that the specified interval
--   does not span multiple lines of the input source. This will not be
--   checked.
parseErrorAtRegion :: Int -> Int -> String -> HledgerParseErrorData

-- | A fragment of source suitable for "re-parsing". The purpose of this
--   data type is to preserve the content and source position of the
--   excerpt so that parse errors raised during "re-parsing" may properly
--   reference the original source.
data SourceExcerpt

-- | Get the raw text of a source excerpt.
getExcerptText :: SourceExcerpt -> Text

-- | 'excerpt_ p' applies the given parser <tt>p</tt> and extracts the
--   portion of the source consumed by <tt>p</tt>, along with the source
--   position of this portion. This is the only way to create a source
--   excerpt suitable for "re-parsing" by <a>reparseExcerpt</a>.
excerpt_ :: MonadParsec HledgerParseErrorData Text m => m a -> m SourceExcerpt

-- | 'reparseExcerpt s p' "re-parses" the source excerpt <tt>s</tt> using
--   the parser <tt>p</tt>. Parse errors raised by <tt>p</tt> will be
--   re-thrown at the source position of the source excerpt.
--   
--   In order for the correct source file to be displayed when re-throwing
--   parse errors, we must ensure that the source file during the use of
--   'reparseExcerpt s p' is the same as that during the use of
--   <a>excerpt_</a> that generated the source excerpt <tt>s</tt>. However,
--   we can usually expect this condition to be satisfied because, at the
--   time of writing, the only changes of source file in the codebase take
--   place through include files, and the parser for include files neither
--   accepts nor returns <a>SourceExcerpt</a>s.
reparseExcerpt :: forall (m :: Type -> Type) a. Monad m => SourceExcerpt -> ParsecT HledgerParseErrorData Text m a -> ParsecT HledgerParseErrorData Text m a

-- | Pretty-print our custom parse errors. It is necessary to use this
--   instead of <a>errorBundlePretty</a> when custom parse errors are
--   thrown.
--   
--   This function intercepts our custom parse errors and applies final
--   adjustments (<tt>finalizeCustomError</tt>) before passing them to
--   <a>errorBundlePretty</a>. These adjustments are part of the
--   implementation of the behaviour of our custom parse errors.
--   
--   Note: We must ensure that the offset of the <a>PosState</a> of the
--   provided <a>ParseErrorBundle</a> is no larger than the offset
--   specified by a <a>ErrorFailAt</a> constructor. This is guaranteed if
--   this offset is set to 0 (that is, the beginning of the source file),
--   which is the case for <a>ParseErrorBundle</a>s returned from
--   <a>runParserT</a>.
customErrorBundlePretty :: HledgerParseErrors -> String

-- | Apply the final adjustments to the custom parse errors in this error
--   bundle (see <a>customErrorBundlePretty</a>), leaving errors which
--   megaparsec's standard <a>errorBundlePretty</a> can render correctly.
--   Exposed for callers which need to adjust the bundle further before
--   rendering it.
finalizeCustomErrorBundle :: HledgerParseErrors -> HledgerParseErrors
type FinalParseError = FinalParseError' HledgerParseErrorData

-- | A type representing "final" parse errors that cannot be backtracked
--   from and are guaranteed to halt parsing. The anti-backtracking
--   behaviour is implemented by an <a>ExceptT</a> layer in the parser's
--   monad stack, using this type as the <a>ExceptT</a> error type.
--   
--   We have three goals for this type: (1) it should be possible to
--   convert any parse error into a "final" parse error, (2) it should be
--   possible to take a parse error thrown from an include file and
--   re-throw it in the context of the parent file, and (3) the
--   pretty-printing of "final" parse errors should be consistent with that
--   of ordinary parse errors, but should also report the stack of parent
--   files when errors are thrown from included files, and (4) readers of
--   non-journal formats (like CSV), which produce complete error messages
--   rather than parse errors, should be able to throw those as "final"
--   parse errors too, so they get the same include file stack.
--   
--   In order to pretty-print a "final" parse error (goal 3), it must be
--   bundled with include filepaths and its full source text. When a
--   "final" parse error is thrown from within a parser, we do not have
--   access to the full source, so we must hold the parse error
--   (<a>FinalParseError</a>) until it can be combined with the full source
--   (and any parent file paths) by the parser's caller
--   (<a>FinalParseErrorBundle</a>).
data FinalParseError' e
type FinalParseErrorBundle = FinalParseErrorBundle' HledgerParseErrorData

-- | A type bundling a <a>ParseError</a> with its full source text,
--   filepath, and stack of include files. Suitable for pretty-printing.
--   
--   Megaparsec's <a>ParseErrorBundle</a> type already bundles a parse
--   error with its full source text and filepath, so we just add a stack
--   of include files. Or, it can hold a complete error message instead
--   (see <a>FinalMessage</a>).
data FinalParseErrorBundle' e

-- | Convert a "regular" parse error into a "final" parse error.
finalError :: ParseError Text e -> FinalParseError' e

-- | Like megaparsec's <a>fancyFailure</a>, but as a "final" parse error.
finalFancyFailure :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => Set (ErrorFancy e) -> m a

-- | Like <a>fail</a>, but as a "final" parse error.
finalFail :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => String -> m a

-- | Like megaparsec's <a>customFailure</a>, but as a "final" parse error.
finalCustomFailure :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => e -> m a

-- | 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

-- | Pretty-print a "final" parse error: print the stack of include files,
--   then apply the pretty-printer for parse error bundles. Note that
--   <a>attachSource</a> must be used on a "final" parse error before it
--   can be pretty-printed.
finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String

-- | Attach a filepath and source text to a "final" parse error so that it
--   can be pretty-printed. You must ensure that you provide the
--   appropriate source text and filepath.
attachSource :: FilePath -> Text -> FinalParseError' e -> FinalParseErrorBundle' e

-- | Parse an include file with the given parser and initial state,
--   discarding the resulting state, and re-throwing any parse errors as
--   final parse errors with the file's info attached.
parseIncludeFile :: forall (m :: Type -> Type) st a. Monad m => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a -> st -> FilePath -> Text -> StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a
instance GHC.Internal.Classes.Eq Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Internal.Base.Monoid (Hledger.Utils.Parse.FinalParseError' e)
instance GHC.Internal.Classes.Ord Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Internal.Classes.Ord (Text.Megaparsec.Error.ParseError Data.Text.Internal.Text Hledger.Utils.Parse.HledgerParseErrorData)
instance GHC.Internal.Base.Semigroup (Hledger.Utils.Parse.FinalParseError' e)
instance Text.Megaparsec.Error.ShowErrorComponent Hledger.Utils.Parse.HledgerParseErrorData
instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (Hledger.Utils.Parse.FinalParseError' e)
instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (Hledger.Utils.Parse.FinalParseErrorBundle' e)
instance GHC.Internal.Show.Show Hledger.Utils.Parse.HledgerParseErrorData

module Hledger.Utils.Test
adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree
askOption :: IsOption v => (v -> TestTree) -> TestTree
defaultIngredients :: [Ingredient]
localOption :: IsOption v => v -> TestTree -> TestTree
withResource :: IO a -> (a -> IO ()) -> (IO a -> TestTree) -> TestTree
defaultMainWithIngredients :: [Ingredient] -> TestTree -> IO ()
after :: DependencyType -> String -> TestTree -> TestTree
after_ :: DependencyType -> Expr -> TestTree -> TestTree
dependentTestGroup :: TestName -> DependencyType -> [TestTree] -> TestTree
inOrderTestGroup :: TestName -> [TestTree] -> TestTree
sequentialTestGroup :: TestName -> DependencyType -> [TestTree] -> TestTree
testGroup :: TestName -> [TestTree] -> TestTree
includingOptions :: [OptionDescription] -> Ingredient
mkTimeout :: Integer -> Timeout
data DependencyType
AllSucceed :: DependencyType
AllFinish :: DependencyType
type TestName = String
data TestTree
data Timeout
Timeout :: Integer -> String -> Timeout
NoTimeout :: Timeout
testCase :: TestName -> Assertion -> TestTree
testCaseInfo :: TestName -> IO String -> TestTree
(@=?) :: (Eq a, Show a, HasCallStack) => a -> a -> Assertion
(@?) :: (AssertionPredicable t, HasCallStack) => t -> String -> Assertion
(@?=) :: (Eq a, Show a, HasCallStack) => a -> a -> Assertion
assertBool :: HasCallStack => String -> Bool -> Assertion
assertEqual :: (Eq a, Show a, HasCallStack) => String -> a -> a -> Assertion
assertFailure :: HasCallStack => String -> IO a
assertString :: HasCallStack => String -> Assertion
testCaseSteps :: TestName -> ((String -> IO ()) -> Assertion) -> TestTree
type HasCallStack = ?callStack :: CallStack
class Assertable t
assert :: Assertable t => t -> Assertion
type Assertion = IO ()
class AssertionPredicable t
assertionPredicate :: AssertionPredicable t => t -> IO Bool
type AssertionPredicate = IO Bool
data HUnitFailure
HUnitFailure :: Maybe SrcLoc -> String -> HUnitFailure

-- | Assert any Left value.
assertLeft :: (HasCallStack, Eq b, Show b) => Either a b -> Assertion

-- | Assert any Right value.
assertRight :: (HasCallStack, Eq a, Show a) => Either a b -> Assertion

-- | Assert that this stateful parser runnable in IO successfully parses
--   all of the given input text, showing the parse error if it fails.
--   Suitable for hledger's JournalParser parsers.
assertParse :: (HasCallStack, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> Assertion

-- | Assert a parser produces an expected value.
assertParseEq :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> a -> Assertion

-- | Like assertParseEq, but transform the parse result with the given
--   function before comparing it.
assertParseEqOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (a -> b) -> b -> Assertion

-- | Assert that this stateful parser runnable in IO fails to parse the
--   given input text, with a parse error containing the given string.
assertParseError :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> String -> Assertion
assertParseE :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> Assertion
assertParseEqE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> a -> Assertion
assertParseErrorE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> String -> Assertion

-- | Run a stateful parser in IO like assertParse, then assert that the
--   final state (the wrapped state, not megaparsec's internal state),
--   transformed by the given function, matches the given expected value.
assertParseStateOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (st -> b) -> b -> Assertion


-- | String formatting helpers, starting to get a bit out of control.
module Hledger.Utils.String

-- | Take elements from the end of a list.
takeEnd :: Int -> [a] -> [a]
capitalise :: String -> String
lowercase :: String -> String
uppercase :: String -> String
underline :: String -> String
stripbrackets :: String -> String

-- | Double-quote this string if it contains whitespace, single quotes or
--   double-quotes, escaping the quotes as needed.
quoteIfNeeded :: String -> String

-- | Single-quote this string if it contains whitespace or double-quotes.
--   Does not work for strings containing single quotes.
singleQuoteIfNeeded :: String -> String

-- | 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 <a>runCommand</a>, <a>callCommand</a>, or
--   <a>shell</a>.
shellQuoteIfNeeded :: String -> String

-- | 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.
--   
--   <pre>
--   &gt;&gt;&gt; quoteForCommandLine "a"
--   "a"
--   
--   &gt;&gt;&gt; quoteForCommandLine "\""
--   "'\"'"
--   
--   &gt;&gt;&gt; quoteForCommandLine "$"
--   "'$'"
--   
--   &gt;&gt;&gt; quoteForCommandLine "it's"
--   "'it'\\''s'"
--   </pre>
quoteForCommandLine :: String -> String

-- | 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.
--   
--   <pre>
--   &gt;&gt;&gt; words' "a b"
--   ["a","b"]
--   
--   &gt;&gt;&gt; words' "'a b' c"
--   ["a b","c"]
--   
--   &gt;&gt;&gt; words' "date:'1 to 15' x"
--   ["date:1 to 15","x"]
--   
--   &gt;&gt;&gt; words' "\"it's\""
--   ["it's"]
--   
--   &gt;&gt;&gt; words' "a '' b"
--   ["a","","b"]
--   
--   &gt;&gt;&gt; wordsmay "an unclosed 'quote"
--   Nothing
--   </pre>
words' :: String -> [String]

-- | Like words', but return Nothing if parsing fails (eg because of an
--   unclosed quote), rather than raising an error.
wordsmay :: String -> Maybe [String]

-- | 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]

-- | Strip one matching pair of single or double quotes on the ends of a
--   string.
stripQuotes :: String -> String
isSingleQuoted :: String -> Bool
isDoubleQuoted :: String -> Bool

-- | Strip ANSI escape sequences from a string.
--   
--   <pre>
--   &gt;&gt;&gt; stripAnsi "\ESC[31m-1\ESC[m"
--   "-1"
--   </pre>
stripAnsi :: String -> String

-- | Remove leading and trailing whitespace.
strip :: String -> String

-- | Remove leading whitespace.
lstrip :: String -> String

-- | Remove trailing whitespace.
rstrip :: String -> String

-- | Strip the given starting and ending character from the start and end
--   of a string if both are present.
strip1Char :: Char -> Char -> String -> String

-- | Strip a run of zero or more characters matching the predicate from the
--   start and end of a string.
stripBy :: (Char -> Bool) -> String -> String

-- | Strip a single balanced enclosing pair of a character matching the
--   predicate from the start and end of a string.
strip1By :: (Char -> Bool) -> String -> String

-- | Remove all trailing newlines/carriage returns.
chomp :: String -> String

-- | Remove all trailing newline/carriage returns, leaving just one
--   trailing newline.
chomp1 :: String -> String

-- | Remove consecutive line breaks, replacing them with single space
singleline :: String -> String
elideLeft :: Int -> String -> String
elideRight :: Int -> String -> String

-- | Clip and pad a string to a minimum &amp; maximum width, and<i>or
--   left</i>right justify it. Works on multi-line strings too (but will
--   rewrite non-unix line endings).
formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String
charWidth :: Char -> Int

-- | Alias for <a>realLength</a>.
strWidth :: String -> Int

-- | Like strWidth, but also strips ANSI escape sequences before
--   calculating the width.
--   
--   This is no longer used in code, as widths are calculated before adding
--   ANSI escape sequences, but is being kept around for now.
strWidthAnsi :: String -> Int

-- | Double-width-character-aware string truncation. Take as many
--   characters as possible from a string without exceeding the specified
--   width. Eg takeWidth 3 "りんご" = "り".
takeWidth :: Int -> String -> String


-- | 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 <a>translationsOverrideDir</a>). Lookups are pure functions of a
--   <a>Translations</a> value, so there is no process-global locale state,
--   and hledger-web can serve a different language to each request.
--   
--   Conventions:
--   
--   <ul>
--   <li>The msgid is the English text. A missing or empty translation
--   falls back to it, and <a>noTranslations</a> is the identity, so
--   English output is unaffected by this machinery.</li>
--   <li>Parameters are <tt>{name}</tt> placeholders substituted after
--   lookup (<a>trf</a>), never printf formats: a translation can not crash
--   the program.</li>
--   <li>Short words used in more than one sense carry a context
--   (<a>trc</a>).</li>
--   <li>Use <a>tr</a> (or <a>trc</a>, <a>trf</a>) where text is displayed
--   and a <a>Translations</a> value is at hand, usually from the report
--   options. Use <a>i18n</a> (or <a>i18nc</a>) 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 <a>tr</a>
--   at display time. Both forms are what the catalog extraction tool looks
--   for.</li>
--   <li>A malformed catalog is reported as a warning and ignored.</li>
--   </ul>
--   
--   This module is experimental and its API may change.
module Hledger.Utils.I18n

-- | A set of translations for one language, looked up by English text
--   (optionally qualified by a context, see <a>trc</a>).
data Translations
Translations :: Text -> Map Text Text -> Map Text [Text] -> Maybe PluralForms -> Translations

-- | language tag, eg "de", "pt-BR", "zh-Hans"
[trLang] :: Translations -> Text

-- | msgid (or "contextx04msgid") -&gt; translation
[trMessages] :: Translations -> Map Text Text

-- | singular msgid -&gt; one translation per plural form
[trPlurals] :: Translations -> Map Text [Text]

-- | this language's plural rule, from the catalog header
[trPluralForms] :: Translations -> Maybe PluralForms

-- | A language's plural rule: how many forms it has, and which form a
--   count selects.
data PluralForms
PluralForms :: Int -> (Int -> Int) -> PluralForms
[pfCount] :: PluralForms -> Int
[pfRule] :: PluralForms -> Int -> Int

-- | English: every lookup returns its argument.
noTranslations :: Translations

-- | Translate this English text, or return it unchanged if there is no
--   translation.
tr :: Translations -> Text -> Text

-- | Like <a>tr</a>, 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

-- | Translate this English template, then fill in its <tt>{name}</tt>
--   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

-- | Translate a count phrase, choosing the plural form this language uses
--   for the count, then fill in the <tt>{n}</tt> 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

-- | Mark an English literal that is stored now, in data such as a report
--   spec or a menu item, and translated later by <a>tr</a> 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 <a>Translations</a> value is already at hand, use <a>tr</a>
--   directly instead.
i18n :: Text -> Text

-- | Like <a>i18n</a>, for a literal that will be translated with a context
--   by <a>trc</a>.
i18nc :: Text -> Text -> Text

-- | 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

-- | 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
--   <a>langPrefsFromEnv</a>), falling back to English. Anything else is a
--   language tag, which must have a catalog, built-in or in
--   <a>translationsOverrideDir</a>; otherwise a usage error is raised.
translationsForLangOption :: Maybe String -> IO Translations

-- | Replace each <tt>{name}</tt> 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

-- | The placeholder names in a template.
placeholders :: Text -> Set 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

-- | Merge two catalogs; entries in the second take precedence.
mergeTranslations :: Translations -> Translations -> Translations

-- | 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

-- | The languages with a built-in catalog, plus English.
builtinLanguages :: [Text]

-- | 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]

-- | Load the translations for this language tag (which should be one
--   returned by <a>availableLanguages</a>): 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

-- | Load the translations for every available language.
loadAllTranslations :: IO (Map Text Translations)

-- | 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
--   (~<i>.config</i>hledger/locale on unix, %APPDATA%\hledger\locale on
--   windows).
translationsOverrideDir :: IO FilePath

-- | 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)

-- | Write the catalog to start translating a language from (see
--   <a>startingCatalog</a>) into <a>translationsOverrideDir</a>, 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))

-- | 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

-- | 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

-- | The tags to try for a language tag, most specific first: the tag
--   itself, then with subtags dropped from the right.
langTagCandidates :: Text -> [Text]

-- | 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

-- | 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

-- | 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]

-- | 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, &amp;&amp;, ||, and ?:.
parsePluralForms :: Text -> Maybe PluralForms
tests_I18n :: TestTree
instance GHC.Internal.Show.Show Hledger.Utils.I18n.Translations


-- | Utilities used throughout hledger, or needed low in the module
--   hierarchy. These are the bottom of hledger's module graph.
module Hledger.Utils

-- | Apply a function the specified number of times, which should be &gt; 0
--   (otherwise does nothing). Possibly uses O(n) stack ?
applyN :: Int -> (a -> a) -> a -> a

-- | Like mapM but uses sequence'.
mapM' :: Monad f => (a -> f b) -> [a] -> f [b]

-- | This is a version of sequence based on difference lists. It is
--   slightly faster but we mostly use it because it uses the heap instead
--   of the stack. This has the advantage that Neil Mitchell’s trick of
--   limiting the stack size to discover space leaks doesn’t show this as a
--   false positive.
sequence' :: Monad f => [f a] -> f [a]
curry2 :: ((a, b) -> c) -> a -> b -> c
uncurry2 :: (a -> b -> c) -> (a, b) -> c
curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e

-- | Division, returning 0 when the denominator is 0.
divideSafe :: (Eq a, Fractional a) => a -> a -> a

-- | Total version of maximum, for integral types, giving 0 for an empty
--   list.
maximum' :: Integral a => [a] -> a

-- | Strict version of maximum that doesn’t leak space
maximumStrict :: Ord a => [a] -> a

-- | Strict version of minimum that doesn’t leak space
minimumStrict :: Ord a => [a] -> a
splitAtElement :: Eq a => a -> [a] -> [[a]]

-- | Strict version of sum that doesn’t leak space
sumStrict :: Num a => [a] -> a

-- | Version of all that fails on an empty list.
all1 :: (a -> Bool) -> [a] -> Bool

-- | Take elements from a list until a predicate fails, and then keep the
--   first failing element as well.
takeUntilFails :: (a -> Bool) -> [a] -> [a]

-- | Take elements from a non-empty list until a predicate fails, and then
--   keep the first failing element as well.
takeUntilFailsNE :: (a -> Bool) -> NonEmpty a -> NonEmpty a

-- | Get the leaves of this tree as a list. The topmost node ("root" in
--   hledger account trees) is not counted as a leaf.
treeLeaves :: Tree a -> [a]
first3 :: (a, b, c) -> a
second3 :: (a, b, c) -> b
third3 :: (a, b, c) -> c
first4 :: (a, b, c, d) -> a
second4 :: (a, b, c, d) -> b
third4 :: (a, b, c, d) -> c
fourth4 :: (a, b, c, d) -> d
first5 :: (a, b, c, d, e) -> a
second5 :: (a, b, c, d, e) -> b
third5 :: (a, b, c, d, e) -> c
fourth5 :: (a, b, c, d, e) -> d
fifth5 :: (a, b, c, d, e) -> e
first6 :: (a, b, c, d, e, f) -> a
second6 :: (a, b, c, d, e, f) -> b
third6 :: (a, b, c, d, e, f) -> c
fourth6 :: (a, b, c, d, e, f) -> d
fifth6 :: (a, b, c, d, e, f) -> e
sixth6 :: (a, b, c, d, e, f) -> f

-- | Convert a list of strings to a multi-line multi-column list fitting
--   within the given width. Not wide character aware.
multicol :: Int -> [String] -> String

-- | Find the number of digits of an <a>Int</a>.
numDigitsInt :: Integral a => Int -> a

-- | Find the number of digits of an Integer. The integer should not have
--   more digits than an Int can count. This is probably inefficient.
numDigitsInteger :: Integer -> Int

-- | Make classy lenses for Hledger options fields. This is intended to be
--   used with BalancingOpts, InputOpt, ReportOpts, ReportSpec, and
--   CliOpts. When run on X, it will create a typeclass named HasX (except
--   for ReportOpts, which will be named HasReportOptsNoUpdate) containing
--   all the lenses for that type. If the field name starts with an
--   underscore, the lens name will be created by stripping the underscore
--   from the front on the name. If the field name ends with an underscore,
--   the field name ends with an underscore, the lens name will be mostly
--   created by stripping the underscore, but a few names for which this
--   would create too many conflicts instead have a second underscore
--   appended. ReportOpts fields for which updating them requires updating
--   the query in ReportSpec are instead names by dropping the trailing
--   underscore and appending NoUpdate to the name, e.g. querystring_ -&gt;
--   querystringNoUpdate.
--   
--   There are a few reasons for the complicated rules. - We have some
--   legacy field names ending in an underscore (e.g. value_) which we want
--   to temporarily accommodate, before eventually switching to a more
--   modern style (e.g. _rsReportOpts) - Certain fields in ReportOpts need
--   to update the enclosing ReportSpec when they are updated, and it is a
--   common programming error to forget to do this. We append NoUpdate to
--   those lenses which will not update the enclosing field, and reserve
--   the shorter name for manually define lenses (or at least something
--   lens-like) which will update the ReportSpec. cf. the lengthy
--   discussion here and in surrounding comments:
--   <a>https://github.com/hledgerorg/hledger/pull/1545#issuecomment-881974554</a>
makeHledgerClassyLenses :: Name -> DecsQ
tests_Utils :: TestTree


-- | CSV utilities.
module Hledger.Write.Csv
type CSV = [CsvRecord]
type CsvRecord = [CsvValue]
type CsvValue = Text
printCSV :: CSV -> Text
printTSV :: CSV -> Text
tests_CsvUtils :: TestTree


-- | hledger's cmdargs modes parse command-line arguments to an
--   intermediate format, RawOpts (an association list), rather than a
--   fixed ADT like CliOpts. This allows the modes and flags to be reused
--   more easily by hledger commands/scripts in this and other packages.
module Hledger.Data.RawOptions

-- | The result of running cmdargs: an association list of option names to
--   string values.
data RawOpts
mkRawOpts :: [(String, String)] -> RawOpts
overRawOpts :: ([(String, String)] -> [(String, String)]) -> RawOpts -> RawOpts
dropRawOpt :: String -> RawOpts -> RawOpts
setopt :: String -> String -> RawOpts -> RawOpts
setboolopt :: String -> RawOpts -> RawOpts
unsetboolopt :: String -> RawOpts -> RawOpts
appendopts :: [(String, String)] -> RawOpts -> RawOpts

-- | Is the named flag present ?
boolopt :: String -> RawOpts -> Bool

-- | Like boolopt, except if the flag is repeated on the command line it
--   toggles the value. An even number of repetitions is equivalent to
--   none.
toggleopt :: String -> RawOpts -> Bool

-- | From a list of RawOpts, get the last one (ie the right-most on the
--   command line) for which the given predicate returns a Just value.
--   Useful for exclusive choice flags like --daily|--weekly|--quarterly...
--   
--   <pre>
--   &gt;&gt;&gt; import Safe (readMay)
--   
--   &gt;&gt;&gt; choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])
--   Just "c"
--   
--   &gt;&gt;&gt; choiceopt (const Nothing) (RawOpts [("a","")])
--   Nothing
--   
--   &gt;&gt;&gt; choiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe Ordering
--   Just EQ
--   </pre>
choiceopt :: (String -> Maybe a) -> RawOpts -> Maybe a

-- | Collects processed and filtered list of options preserving their order
--   
--   <pre>
--   &gt;&gt;&gt; collectopts (const Nothing) (RawOpts [("x","")])
--   []
--   
--   &gt;&gt;&gt; collectopts Just (RawOpts [("a",""),("b","")])
--   [("a",""),("b","")]
--   </pre>
collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]
stringopt :: String -> RawOpts -> String
maybestringopt :: String -> RawOpts -> Maybe String
listofstringopt :: String -> RawOpts -> [String]

-- | Reads the named option's Int argument. If not present it will return
--   0. An argument that is too small or too large will raise an error.
intopt :: String -> RawOpts -> Int

-- | Reads the named option's natural-number argument. If not present it
--   will return 0. An argument that is negative or too large will raise an
--   error.
posintopt :: String -> RawOpts -> Int

-- | Reads the named option's Int argument, if it is present. An argument
--   that is too small or too large will raise an error.
maybeintopt :: String -> RawOpts -> Maybe Int

-- | Reads the named option's natural-number argument, if it is present. An
--   argument that is negative or too large will raise an error.
maybeposintopt :: String -> RawOpts -> Maybe Int
maybecharopt :: String -> RawOpts -> Maybe Char
maybeynopt :: String -> RawOpts -> Maybe Bool
maybeynaopt :: String -> RawOpts -> Maybe YNA
instance Data.Default.Internal.Default Hledger.Data.RawOptions.RawOpts
instance GHC.Internal.Show.Show Hledger.Data.RawOptions.RawOpts


-- | Date parsing and utilities for hledger.
--   
--   For date and time values, we use the standard Day and UTCTime types.
--   
--   A <a>SmartDate</a> is a date which may be partially-specified or
--   relative. Eg 2008/12/31, but also 2008/12, 12/31, tomorrow, last week,
--   next year, in 5 days, in -3 quarters. We represent these as a triple
--   of strings like ("2008","12",""), ("","","tomorrow"),
--   ("","last","week").
--   
--   A <a>DateSpan</a> is the span of time between two specific calendar
--   dates, or an open-ended span where one or both dates are unspecified.
--   (A date span with both ends unspecified matches all dates.)
--   
--   An <a>Interval</a> is ledger's "reporting interval" - weekly, monthly,
--   quarterly, etc.
--   
--   <a>Period</a> will probably replace DateSpan in due course.
module Hledger.Data.Dates
fromEFDay :: EFDay -> Day
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay

-- | Get the current local date.
getCurrentDay :: IO Day

-- | Get the current local month number.
getCurrentMonth :: IO Int

-- | Get the current local year.
getCurrentYear :: IO Integer
nulldate :: Day

-- | Does the span include the given date ?
spanContainsDate :: DateSpan -> Day -> Bool

-- | Does the period include the given date ? (Here to avoid import cycle).
periodContainsDate :: Period -> Day -> Bool

-- | A simple date parsing helper: parses these YMD date string formats:
--   `YYYY-MM-DD`, `YYYY<i>MM</i>DD`, <a>DD</a> or <tt>YYYYMMDD</tt>, where
--   the month and day each have two digits and the year has one or more.
--   
--   This is different from the Smart Dates of the CLI and period
--   expressions ("smartdate", below) and not quite the same as the Simple
--   Dates of the journal ("datep", in Hledger.Read.Common). It's mainly
--   for internal or interactive use, eg when debugging - but currently is
--   also used in a few user-facing places, such as: parsing --value's
--   argument, parsing .latest files, and parsing hledger's --version
--   output (which uses unseparated dates).
--   
--   Unseparated dates were added in 2025 for convenience. Note it means
--   many integers will now parse successfully.
--   
--   <pre>
--   &gt;&gt;&gt; parsedate "2008/02/03"
--   Just 2008-02-03
--   
--   &gt;&gt;&gt; parsedate "2008/02/03/"
--   Nothing
--   
--   &gt;&gt;&gt; parsedate "2008/02/30"
--   Nothing
--   
--   &gt;&gt;&gt; parsedate "2025-01-01"
--   Just 2025-01-01
--   
--   &gt;&gt;&gt; parsedate "2025.01.01"
--   Just 2025-01-01
--   
--   &gt;&gt;&gt; parsedate "20250101"
--   Just 2025-01-01
--   
--   &gt;&gt;&gt; parsedate "00101"
--   Just 0000-01-01
--   </pre>
parsedate :: String -> Maybe Day
showDate :: Day -> Text
showEFDate :: EFDay -> Text

-- | Render a datespan as a display string, abbreviating into a compact
--   form if possible. Warning, hides whether dates are Exact or Flex.
showDateSpan :: DateSpan -> Text

-- | Show a DateSpan with its begin/end dates, exact or flex.
showDateSpanDebug :: DateSpan -> String

-- | Like showDateSpan, but show month spans as just the abbreviated month
--   name in the current locale.
showDateSpanAbbrev :: DateSpan -> Text

-- | Like showDateSpanAbbrev, but take the month names from this time
--   locale.
showDateSpanAbbrevWith :: TimeLocale -> DateSpan -> Text

-- | 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

-- | 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 "".
--   
--   <a>showDateSpan</a> 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.
--   
--   <pre>
--   &gt;&gt;&gt; showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) (Just $ Exact $ fromGregorian 2026 1 1)
--   "2025"
--   
--   &gt;&gt;&gt; showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 13) (Just $ Exact $ fromGregorian 2025 1 20)
--   "2025-01-13..2025-01-20"
--   
--   &gt;&gt;&gt; showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 15) (Just $ Exact $ fromGregorian 2025 2 15)
--   "2025-01-15..2025-02-15"
--   
--   &gt;&gt;&gt; showDateSpanForQuery $ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
--   "2025-01-01.."
--   
--   &gt;&gt;&gt; showDateSpanForQuery $ DateSpan Nothing (Just $ Exact $ fromGregorian 2025 2 1)
--   "..2025-02-01"
--   
--   &gt;&gt;&gt; showDateSpanForQuery nulldatespan
--   ""
--   </pre>
showDateSpanForQuery :: DateSpan -> Text
elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a
prevday :: Day -> Day

-- | Parse a period expression, specifying a date span and optionally a
--   reporting interval. Requires a reference "today" date for resolving
--   any relative start/end dates (only; it is not needed for parsing the
--   reporting interval).
--   
--   <pre>
--   &gt;&gt;&gt; let p = parsePeriodExpr (fromGregorian 2008 11 26)
--   
--   &gt;&gt;&gt; p "from Aug to Oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   &gt;&gt;&gt; p "aug to oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   &gt;&gt;&gt; p "2009q2"
--   Right (NoInterval,DateSpan 2009Q2)
--   
--   &gt;&gt;&gt; p "Q3"
--   Right (NoInterval,DateSpan 2008Q3)
--   
--   &gt;&gt;&gt; p "every 3 days in Aug"
--   Right (Days 3,DateSpan 2008-08)
--   
--   &gt;&gt;&gt; p "daily from aug"
--   Right (Days 1,DateSpan 2008-08-01..)
--   
--   &gt;&gt;&gt; p "every week to 2009"
--   Right (Weeks 1,DateSpan ..2008-12-31)
--   
--   &gt;&gt;&gt; p "every 2nd day of month"
--   Right (MonthDay 2,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day"
--   Right (MonthDay 2,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 2nd day 2009-"
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 29th Nov"
--   Right (MonthAndDay 11 29,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 29th nov ..2009"
--   Right (MonthAndDay 11 29,DateSpan ..2008-12-31)
--   
--   &gt;&gt;&gt; p "every nov 29th"
--   Right (MonthAndDay 11 29,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every Nov 29th 2009.."
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 11/29 from 2009"
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 11/29 since 2009"
--   Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 2nd Thursday of month to 2009"
--   Right (NthWeekdayOfMonth 2 4,DateSpan ..2008-12-31)
--   
--   &gt;&gt;&gt; p "every 1st monday of month to 2009"
--   Right (NthWeekdayOfMonth 1 1,DateSpan ..2008-12-31)
--   
--   &gt;&gt;&gt; p "every tue"
--   Right (DaysOfWeek [2],DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day of week"
--   Right (DaysOfWeek [2],DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day of month"
--   Right (MonthDay 2,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day"
--   Right (MonthDay 2,DateSpan ..)
--   
--   &gt;&gt;&gt; p "every 2nd day 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   
--   &gt;&gt;&gt; p "every 2nd day of month 2009.."
--   Right (MonthDay 2,DateSpan 2009-01-01..)
--   </pre>
periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan)
reportingintervalp :: forall (m :: Type -> Type). TextParser m Interval

-- | Parse a period expression to an Interval and overall DateSpan using
--   the provided reference date, or return a parse error.
parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan)

-- | Like parsePeriodExpr, but call error' on failure.
parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan)
nulldatespan :: DateSpan

-- | An exact datespan of zero length, that matches no date.
emptydatespan :: DateSpan
datesepchar :: forall (m :: Type -> Type). TextParser m Char
datesepchars :: String
isDateSepChar :: Char -> Bool
spanStart :: DateSpan -> Maybe Day
spanEnd :: DateSpan -> Maybe Day
spanStartYear :: DateSpan -> Maybe Year
spanEndYear :: DateSpan -> Maybe Year

-- | Get the 0-2 years mentioned explicitly in a DateSpan.
spanYears :: DateSpan -> [Year]

-- | Get overall span enclosing multiple sequentially ordered spans. The
--   start and end date will be exact or flexible depending on the first
--   span's start date and last span's end date.
spansSpan :: [DateSpan] -> DateSpan

-- | Calculate the intersection of two datespans.
--   
--   For non-intersecting spans, gives an empty span beginning on the
--   second's start date: &gt;&gt;&gt; DateSpan (Just $ Flex $
--   fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03)
--   <a>spanIntersect</a> DateSpan (Just $ Flex $ fromGregorian 2018 01 03)
--   (Just $ Flex $ fromGregorian 2018 01 05) DateSpan
--   2018-01-03..2018-01-02
spanIntersect :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the intersection of a number of datespans.
spansIntersect :: [DateSpan] -> DateSpan

-- | Fill any unspecified dates in the first span with the dates from the
--   second one (if specified there). Sort of a one-way spanIntersect. This
--   one can create an invalid span that'll always be empty.
--   
--   <pre>
--   &gt;&gt;&gt; :{
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) Nothing
--    `spanDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2024-01-01
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; :{
--    DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
--    `spanDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2025-01-01..2024-01-01
--   </pre>
spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan

-- | A smarter version of spanDefaultsFrom that avoids creating invalid
--   spans ending before they begin. Kept separate for now to reduce risk.
--   
--   <pre>
--   &gt;&gt;&gt; :{
--    DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
--    `spanValidDefaultsFrom`
--    DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
--   :}
--   DateSpan 2025-01-01..
--   </pre>
spanValidDefaultsFrom :: DateSpan -> DateSpan -> DateSpan

-- | Extend the definite start/end dates of the first span, if needed, to
--   include the definite start/end dates of the second span. And<i>or,
--   replace open start</i>end dates in the first span with definite
--   start/end dates from the second. Unlike spanUnion, open start/end
--   dates in the second are ignored.
--   
--   <pre>
--   &gt;&gt;&gt; ys2024 = fromGregorian 2024 01 01
--   
--   &gt;&gt;&gt; ys2025 = fromGregorian 2025 01 01
--   
--   &gt;&gt;&gt; to2024 = DateSpan Nothing               (Just $ Exact ys2024)
--   
--   &gt;&gt;&gt; all2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
--   
--   &gt;&gt;&gt; partof2024 = DateSpan (Just $ Exact $ fromGregorian 2024 03 01) (Just $ Exact $ fromGregorian 2024 09 01)
--   
--   &gt;&gt;&gt; spanExtend to2024 all2024
--   DateSpan 2024
--   
--   &gt;&gt;&gt; spanExtend all2024 to2024
--   DateSpan 2024
--   
--   &gt;&gt;&gt; spanExtend partof2024 all2024
--   DateSpan 2024
--   
--   &gt;&gt;&gt; spanExtend all2024 partof2024
--   DateSpan 2024
--   </pre>
spanExtend :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the union of two datespans. If either span is open-ended,
--   the union will be too.
--   
--   <pre>
--   &gt;&gt;&gt; ys2024 = fromGregorian 2024 01 01
--   
--   &gt;&gt;&gt; ys2025 = fromGregorian 2025 01 01
--   
--   &gt;&gt;&gt; to2024 = DateSpan Nothing               (Just $ Exact ys2024)
--   
--   &gt;&gt;&gt; in2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
--   
--   &gt;&gt;&gt; spanUnion to2024 in2024
--   DateSpan ..2024-12-31
--   
--   &gt;&gt;&gt; spanUnion in2024 to2024
--   DateSpan ..2024-12-31
--   </pre>
spanUnion :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the union of a number of datespans.
spansUnion :: [DateSpan] -> DateSpan

-- | Calculate the minimal DateSpan containing all of the given Days (in
--   the usual exclusive-end-date sense: beginning on the earliest, and
--   ending on the day after the latest).
daysSpan :: [Day] -> DateSpan

-- | Select the DateSpan containing a given Day, if any, from a given list
--   of DateSpans.
--   
--   If the DateSpans are non-overlapping, this returns the unique
--   containing DateSpan, if it exists. If the DateSpans are overlapping,
--   it will return the containing DateSpan with the latest start date, and
--   then latest end date.
latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan

-- | Parse a date in any of the formats allowed in Ledger's period
--   expressions, and some others. Assumes any text in the parse stream has
--   been lowercased. Returns a SmartDate, to be converted to a full date
--   later (see fixSmartDate).
--   
--   Examples:
--   
--   <pre>
--   2004                                        (start of year, which must have 4+ digits)
--   2004/10                                     (start of month, which must be 1-12)
--   2004/10/1                                   (exact date, day must be 1-31)
--   10/1                                        (month and day in current year)
--   21                                          (day in current month)
--   october, oct                                (start of month in current year)
--   yesterday, today, tomorrow                  (-1, 0, 1 days from today)
--   last/this/next day/week/month/quarter/year  (-1, 0, 1 periods from the current period)
--   last/this/next monday/mon                   (the previous or next named weekday; this=next)
--   last/next january/jan                       (previous or next start of named month; this disallowed to avoid confusion)
--   in n days/weeks/months/quarters/years       (n periods from the current period)
--   n days/weeks/months/quarters/years ago      (-n periods from the current period)
--   20181201                                    (8 digit YYYYMMDD with valid year month and day)
--   201812                                      (6 digit YYYYMM with valid year and month)
--   </pre>
--   
--   Note malformed digit sequences might give surprising results:
--   
--   <pre>
--   201813                                      (6 digits with an invalid month is parsed as start of 6-digit year)
--   20181301                                    (8 digits with an invalid month is parsed as start of 8-digit year)
--   20181232                                    (8 digits with an invalid day gives an error)
--   201801012                                   (9+ digits beginning with a valid YYYYMMDD gives an error)
--   </pre>
--   
--   Eg:
--   
--   YYYYMMDD is parsed as year-month-date if those parts are valid (&gt;=4
--   digits, 1-12, and 1-31 respectively): &gt;&gt;&gt; parsewith
--   (smartdate &lt;* eof) "20181201" Right (SmartCompleteDate 2018-12-01)
--   
--   YYYYMM is parsed as year-month-01 if year and month are valid:
--   &gt;&gt;&gt; parsewith (smartdate &lt;* eof) "201804" Right
--   (SmartAssumeStart 2018 (Just 4))
--   
--   With an invalid month, it's parsed as a year: &gt;&gt;&gt; parsewith
--   (smartdate &lt;* eof) "201813" Right (SmartAssumeStart 201813 Nothing)
--   
--   A 9+ digit number beginning with valid YYYYMMDD gives an error:
--   &gt;&gt;&gt; parsewith (smartdate &lt;* eof) "201801012" Left (...)
--   
--   Big numbers not beginning with a valid YYYYMMDD are parsed as a year:
--   &gt;&gt;&gt; parsewith (smartdate &lt;* eof) "201813012" Right
--   (SmartAssumeStart 201813012 Nothing)
smartdate :: forall (m :: Type -> Type). TextParser m SmartDate

-- | Group elements based on where they fall in a list of <a>DateSpan</a>s
--   without gaps. The precondition is not checked.
groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])]

-- | Convert a SmartDate to a specific date using the provided reference
--   date. This date will be exact or flexible depending on whether the day
--   was specified exactly. (Missing least-significant parts produces a
--   flex date.)
--   
--   <h4>Examples:</h4>
--   
--   <pre>
--   &gt;&gt;&gt; :set -XOverloadedStrings
--   
--   &gt;&gt;&gt; let t = fixSmartDateStr (fromGregorian 2008 11 26)
--   
--   &gt;&gt;&gt; t "0000-01-01"
--   "0000-01-01"
--   
--   &gt;&gt;&gt; t "1999-12-02"
--   "1999-12-02"
--   
--   &gt;&gt;&gt; t "1999.12.02"
--   "1999-12-02"
--   
--   &gt;&gt;&gt; t "1999/3/2"
--   "1999-03-02"
--   
--   &gt;&gt;&gt; t "19990302"
--   "1999-03-02"
--   
--   &gt;&gt;&gt; t "2008/2"
--   "2008-02-01"
--   
--   &gt;&gt;&gt; t "0020/2"
--   "0020-02-01"
--   
--   &gt;&gt;&gt; t "1000"
--   "1000-01-01"
--   
--   &gt;&gt;&gt; t "4/2"
--   "2008-04-02"
--   
--   &gt;&gt;&gt; t "2"
--   "2008-11-02"
--   
--   &gt;&gt;&gt; t "January"
--   "2008-01-01"
--   
--   &gt;&gt;&gt; t "feb"
--   "2008-02-01"
--   
--   &gt;&gt;&gt; t "today"
--   "2008-11-26"
--   
--   &gt;&gt;&gt; t "yesterday"
--   "2008-11-25"
--   
--   &gt;&gt;&gt; t "tomorrow"
--   "2008-11-27"
--   
--   &gt;&gt;&gt; t "this day"
--   "2008-11-26"
--   
--   &gt;&gt;&gt; t "last day"
--   "2008-11-25"
--   
--   &gt;&gt;&gt; t "next day"
--   "2008-11-27"
--   
--   &gt;&gt;&gt; t "this week"  -- last monday
--   "2008-11-24"
--   
--   &gt;&gt;&gt; t "last week"  -- previous monday
--   "2008-11-17"
--   
--   &gt;&gt;&gt; t "next week"  -- next monday
--   "2008-12-01"
--   
--   &gt;&gt;&gt; t "this month"
--   "2008-11-01"
--   
--   &gt;&gt;&gt; t "last month"
--   "2008-10-01"
--   
--   &gt;&gt;&gt; t "next month"
--   "2008-12-01"
--   
--   &gt;&gt;&gt; t "this quarter"
--   "2008-10-01"
--   
--   &gt;&gt;&gt; t "last quarter"
--   "2008-07-01"
--   
--   &gt;&gt;&gt; t "next quarter"
--   "2009-01-01"
--   
--   &gt;&gt;&gt; t "this year"
--   "2008-01-01"
--   
--   &gt;&gt;&gt; t "last year"
--   "2007-01-01"
--   
--   &gt;&gt;&gt; t "next year"
--   "2009-01-01"
--   </pre>
--   
--   refdate is Wednesday, 2008-11-26 &gt;&gt;&gt; t "last wednesday"
--   "2008-11-19" &gt;&gt;&gt; t "this wednesday" "2008-12-03" &gt;&gt;&gt;
--   t "next wednesday" "2008-12-03" &gt;&gt;&gt; t "last january"
--   "2008-01-01" &gt;&gt;&gt; t "this january" "2009-01-01" &gt;&gt;&gt; t
--   "next january" "2009-01-01" &gt;&gt;&gt; t "last november"
--   "2007-11-01" &gt;&gt;&gt; t "this november" "2009-11-01" &gt;&gt;&gt;
--   t "next november" "2009-11-01"
--   
--   <pre>
--   &gt;&gt;&gt; t "in 5 days"
--   "2008-12-01"
--   
--   &gt;&gt;&gt; t "in 7 months"
--   "2009-06-01"
--   
--   &gt;&gt;&gt; t "in -2 weeks"
--   "2008-11-10"
--   
--   &gt;&gt;&gt; t "1 quarter ago"
--   "2008-07-01"
--   
--   &gt;&gt;&gt; t "1 week ahead"
--   "2008-12-01"
--   </pre>
fixSmartDate :: Day -> SmartDate -> EFDay

-- | Convert a smart date string to an explicit yyyy/mm/dd string using the
--   provided reference date, or raise an error.
fixSmartDateStr :: Day -> Text -> Text

-- | A safe version of fixSmartDateStr.
fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text
fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay

-- | Parse a year number from a Text, making sure that at least four digits
--   are used.
yearp :: forall (m :: Type -> Type). TextParser m Integer

-- | Count the days in a DateSpan, or if it is open-ended return Nothing.
daysInSpan :: DateSpan -> Maybe Integer
startofyear :: Day -> Day
startofquarter :: Day -> Day
startofmonth :: Day -> Day
startofweek :: Day -> Day
nextday :: Day -> Day
nextweek :: Day -> Day

-- | Find the next occurrence of the specified month and day of month, on
--   or after the given date. The month should be 1-12 and the day of month
--   should be 1-31, or an error will be raised.
--   
--   <pre>
--   &gt;&gt;&gt; let wed22nd = fromGregorian 2017 11 22
--   
--   &gt;&gt;&gt; nextmonthandday 11 21 wed22nd
--   2018-11-21
--   
--   &gt;&gt;&gt; nextmonthandday 11 22 wed22nd
--   2017-11-22
--   
--   &gt;&gt;&gt; nextmonthandday 11 23 wed22nd
--   2017-11-23
--   </pre>
nextmonthandday :: Month -> MonthDay -> Day -> Day

-- | Find the next occurrence of the specified day of month, on or after
--   the given date. The day of month should be 1-31, or an error will be
--   raised.
--   
--   <pre>
--   &gt;&gt;&gt; let wed22nd = fromGregorian 2017 11 22
--   
--   &gt;&gt;&gt; nextnthdayofmonth 21 wed22nd
--   2017-12-21
--   
--   &gt;&gt;&gt; nextnthdayofmonth 22 wed22nd
--   2017-11-22
--   
--   &gt;&gt;&gt; nextnthdayofmonth 23 wed22nd
--   2017-11-23
--   </pre>
nextnthdayofmonth :: MonthDay -> Day -> Day

-- | Find the previous occurrence of some nth weekday of a month, on or
--   before the given date d.
--   
--   <pre>
--   &gt;&gt;&gt; let wed22nd = fromGregorian 2017 11 22
--   
--   &gt;&gt;&gt; prevNthWeekdayOfMonth 4 3 wed22nd
--   2017-11-22
--   
--   &gt;&gt;&gt; prevNthWeekdayOfMonth 5 2 wed22nd
--   2017-10-31
--   </pre>
prevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day

-- | For given date d find week-long interval that starts on nth day of
--   week and covers it.
--   
--   Examples: 2017-11-22 is Wed. Week-long intervals that cover it and
--   start on Mon, Tue or Wed will start in the same week. However
--   intervals that start on Thu or Fri should start in prev week:
--   &gt;&gt;&gt; let wed22nd = fromGregorian 2017 11 22 &gt;&gt;&gt;
--   nthdayofweekcontaining 1 wed22nd 2017-11-20 &gt;&gt;&gt;
--   nthdayofweekcontaining 2 wed22nd 2017-11-21 &gt;&gt;&gt;
--   nthdayofweekcontaining 3 wed22nd 2017-11-22 &gt;&gt;&gt;
--   nthdayofweekcontaining 4 wed22nd 2017-11-16 &gt;&gt;&gt;
--   nthdayofweekcontaining 5 wed22nd 2017-11-17
nthdayofweekcontaining :: WeekDay -> Day -> Day
addGregorianMonthsToMonthday :: MonthDay -> Integer -> Day -> Day

-- | Advance to the nth occurrence of the given weekday, on or after the
--   given date. Can call error.
advanceToNthWeekday :: Int -> WeekDay -> Day -> Day

-- | Find the next occurrence of some nth weekday of a month, on or after
--   the given date d.
--   
--   <pre>
--   &gt;&gt;&gt; let wed22nd = fromGregorian 2017 11 22
--   
--   &gt;&gt;&gt; nextNthWeekdayOfMonth 3 3 wed22nd  -- next third wednesday
--   2017-12-20
--   
--   &gt;&gt;&gt; nextNthWeekdayOfMonth 4 3 wed22nd  -- next fourth wednesday
--   2017-11-22
--   
--   &gt;&gt;&gt; nextNthWeekdayOfMonth 5 3 wed22nd  -- next fifth wednesday
--   2017-11-29
--   </pre>
nextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day

-- | Is this an empty span, ie closed with the end date on or before the
--   start date ?
isEmptySpan :: DateSpan -> Bool
instance GHC.Internal.Show.Show Hledger.Data.Types.DateSpan


-- | The <tt>.latest</tt> mechanism: a per-input-file record of the latest
--   transaction date(s) seen on the previous read, used by <tt>hledger
--   import</tt> (and any reader called with <tt>new_=True</tt>) to filter
--   out already-seen transactions.
--   
--   For an input file <tt>F</tt>, the latest dates are kept in a
--   <tt>.latest.F</tt> hidden file in <tt>F</tt>'s directory. They are
--   written after a successful import and read on the next one. The CSV
--   rules reader's <tt>archive</tt> 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
--   (<a>Read</a>) and the low-level CSV rules reader (<a>RulesReader</a>)
--   can use them without a module-graph cycle.
module Hledger.Read.LatestDates

-- | 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 <a>LatestDates</a>.
data LatestDatesForFile
LatestDatesForFile :: FilePath -> LatestDates -> LatestDatesForFile

-- | 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

-- | Where to save latest transaction dates for the given file path:
--   <tt>.latest.FILE</tt> in <tt>FILE</tt>'s directory.
latestDatesFileFor :: FilePath -> FilePath

-- | 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

-- | Save the given latest date(s) seen in the given data FILE, in a hidden
--   file named <tt>.latest.FILE</tt>, creating it if needed. Unless no
--   latest dates are provided, in which case do nothing.
saveLatestDates :: LatestDates -> FilePath -> IO ()

-- | Save each file's latest dates.
saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()

-- | 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)
instance GHC.Internal.Show.Show Hledger.Read.LatestDates.LatestDatesForFile


-- | <a>AccountName</a>s are strings like <tt>assets:cash:petty</tt>, with
--   multiple components separated by <tt>:</tt>. From a set of these we
--   derive the account hierarchy.
module Hledger.Data.AccountName
accountLeafName :: AccountName -> Text
accountNameComponents :: AccountName -> [Text]

-- | 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

-- | Remove some number of account name components from the front of the
--   account name. If the special "<a>unbudgeted</a>" top-level account is
--   present, it is preserved and dropping affects the rest of the account
--   name.
accountNameDrop :: Int -> AccountName -> AccountName
accountNameFromComponents :: [Text] -> AccountName

-- | The level (depth) of an account name.
--   
--   <pre>
--   &gt;&gt;&gt; accountNameLevel ""  -- special case
--   0
--   
--   &gt;&gt;&gt; accountNameLevel "assets"
--   1
--   
--   &gt;&gt;&gt; accountNameLevel "assets:cash"
--   2
--   </pre>
accountNameLevel :: AccountName -> Int

-- | Convert an account name to a regular expression matching it but not
--   its subaccounts.
accountNameToAccountOnlyRegex :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it but not
--   its subaccounts, case insensitively.
accountNameToAccountOnlyRegexCI :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it and its
--   subaccounts.
accountNameToAccountRegex :: AccountName -> Regexp

-- | Convert an account name to a regular expression matching it and its
--   subaccounts, case insensitively.
accountNameToAccountRegexCI :: AccountName -> Regexp

-- | 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

-- | Truncate all account name components but the last to two characters.
accountSummarisedName :: AccountName -> Text

-- | 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

-- | Like accountNameInferType, but exclude the provided types from the
--   guesses. Used eg to prevent "equity:conversion" being inferred as
--   Conversion when a different account has been declared with that type.
accountNameInferTypeExcept :: [AccountType] -> AccountName -> Maybe AccountType
accountNameType :: Map AccountName AccountType -> AccountName -> Maybe AccountType
defaultBaseConversionAccount :: IsString a => a
defaultGainAccount :: IsString a => a
defaultImbalanceAccount :: IsString a => a

-- | Regular expressions matching common English top-level account names,
--   used as a fallback when account types are not declared.
assetAccountRegex :: Regexp
cashAccountRegex :: Regexp
liabilityAccountRegex :: Regexp
equityAccountRegex :: Regexp
conversionAccountRegex :: Regexp
revenueAccountRegex :: Regexp
gainAccountRegex :: Regexp
unrealisedGainAccountRegex :: Regexp
imbalanceAccountRegex :: Regexp
expenseAccountRegex :: Regexp
acctsep :: Text
acctsepchar :: Char

-- | Clip an account name to a given <a>DepthSpec</a>, first checking
--   whether it matches any of the regular expressions controlling depth.
--   If so, clip to the depth of the most specific of those matches, i.e.
--   the one which starts matching the latest as you progress up the
--   parents of the account. Otherwise clip to the flat depth provided, or
--   return the full name if Nothing.
clipAccountName :: DepthSpec -> AccountName -> AccountName

-- | As <a>clipAccountName</a>, but return <tt>...</tt> if asked to clip to
--   depth 0.
clipOrEllipsifyAccountName :: DepthSpec -> AccountName -> AccountName

-- | Calculate the depth to which an account name should be clipped for a
--   given <a>DepthSpec</a>.
--   
--   First checking whether the account name matches any of the regular
--   expressions controlling depth. If so, clip to the depth of the most
--   specific of those matches, i.e. the one which starts matching the
--   latest as you progress up the parents of the account. Otherwise clip
--   to the flat depth provided, or return the full name if Nothing.
getAccountNameClippedDepth :: DepthSpec -> AccountName -> Maybe Int

-- | Elide an account name to fit in the specified width. From the ledger
--   2.6 news:
--   
--   <pre>
--   What Ledger now does is that if an account name is too long, it will
--   start abbreviating the first parts of the account name down to two
--   letters in length.  If this results in a string that is still too
--   long, the front will be elided -- not the end.  For example:
--   
--     Expenses:Cash           ; OK, not too long
--     Ex:Wednesday:Cash       ; <a>Expenses</a> was abbreviated to fit
--     Ex:We:Afternoon:Cash    ; <a>Expenses</a> and <a>Wednesday</a> abbreviated
--     ; Expenses:Wednesday:Afternoon:Lunch:Snack:Candy:Chocolate:Cash
--     ..:Af:Lu:Sn:Ca:Ch:Cash  ; Abbreviated and elided!
--   </pre>
elideAccountName :: Int -> AccountName -> AccountName

-- | Escape an AccountName for use within a regular expression.
--   &gt;&gt;&gt; putStr . T.unpack $ escapeName "First?!#$*?$(*) !<tt>^#*?
--   %)*!</tt>#" First?!#$*?$&lt;math&gt; !<tt>^#*? %)*!</tt># &gt;&gt;&gt;
--   putStr . T.unpack $ escapeName "assets:broker:{2026-01-01, $50}"
--   assets:broker:{2026-01-01, $50}
escapeName :: AccountName -> Text

-- | "a:b:c" -&gt; ["a","a:b","a:b:c"]
expandAccountName :: AccountName -> [AccountName]

-- | Sorted unique account names implied by these account names, ie these
--   plus all their parent accounts up to the root. Eg: ["a:b:c","d:e"]
--   -&gt; ["a","a:b","a:b:c","d","d:e"]
expandAccountNames :: [AccountName] -> [AccountName]

-- | Is the first account a parent or other ancestor of (and not the same
--   as) the second ?
isAccountNamePrefixOf :: AccountName -> AccountName -> Bool
isSubAccountNameOf :: AccountName -> AccountName -> Bool

-- | The parent of an account name, or "" if it has none. ("a:b:c" -&gt;
--   "a:b"). Returns a slice of the name, without copying.
parentAccountName :: AccountName -> AccountName
parentAccountNames :: AccountName -> [AccountName]

-- | From a list of account names, select those which are direct
--   subaccounts of the given account name.
subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName]

-- | <ul>
--   <li><i>"a:b:c","d:e"</i> -&gt; ["a","d"]</li>
--   </ul>
topAccountNames :: [AccountName] -> [AccountName]

-- | "a:b:c" -&gt; "a"
topAccountName :: AccountName -> AccountName

-- | A top-level account prefixed to some accounts in budget reports.
--   Defined here so it can be ignored by accountNameDrop.
unbudgetedAccountName :: Text
accountNamePostingType :: AccountName -> PostingRealness
accountNameWithoutPostingType :: AccountName -> AccountName
accountNameWithPostingType :: PostingRealness -> AccountName -> AccountName

-- | Prefix one account name to another, preserving posting type indicators
--   like concatAccountNames.
joinAccountNames :: AccountName -> AccountName -> AccountName

-- | Join account names into one. If any of them has () or [] posting type
--   indicators, these (the first type encountered) will also be applied to
--   the resulting account name.
concatAccountNames :: [AccountName] -> AccountName

-- | Rewrite an account name using all matching aliases from the given
--   list, in sequence. Each alias sees the result of applying the previous
--   aliases. Or, return any error arising from a bad regular expression in
--   the aliases.
accountNameApplyAliases :: [AccountAlias] -> AccountName -> Either RegexError AccountName

-- | Memoising version of accountNameApplyAliases, maybe overkill.
accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> Either RegexError AccountName
tests_AccountName :: TestTree


-- | Parse format strings provided by --format, with awareness of hledger's
--   report item fields. The formats are used by report-specific renderers
--   like renderBalanceReportItem.
module Hledger.Data.StringFormat

-- | Parse a string format specification, or return a parse error.
parseStringFormat :: Text -> Either String StringFormat
defaultStringFormatStyle :: [StringFormatComponent] -> StringFormat

-- | A format specification/template to use when rendering a report line
--   item as text.
--   
--   A format is a sequence of components; each is either a literal string,
--   or a hledger report item field with specified width and justification
--   whose value will be interpolated at render time.
--   
--   A component's value may be a multi-line string (or a multi-commodity
--   amount), in which case the final string will be either single-line or
--   a top or bottom-aligned multi-line string depending on the
--   StringFormat variant used.
--   
--   Currently this is only used in the balance command's single-column
--   mode, which provides a limited StringFormat renderer.
data StringFormat

-- | multi-line values will be rendered on one line, comma-separated
OneLine :: [StringFormatComponent] -> StringFormat

-- | values will be top-aligned (and bottom-padded to the same height)
TopAligned :: [StringFormatComponent] -> StringFormat

-- | values will be bottom-aligned (and top-padded)
BottomAligned :: [StringFormatComponent] -> StringFormat
data StringFormatComponent

-- | Literal text to be rendered as-is
FormatLiteral :: Text -> StringFormatComponent

-- | A data field to be formatted and interpolated. Parameters:
--   
--   <ul>
--   <li>Left justify ? Right justified if false</li>
--   <li>Minimum width ? Will be space-padded if narrower than this</li>
--   <li>Maximum width ? Will be clipped if wider than this</li>
--   <li>Which of the standard hledger report item fields to
--   interpolate</li>
--   </ul>
FormatField :: Bool -> Maybe Int -> Maybe Int -> ReportItemField -> StringFormatComponent

-- | An id identifying which report item field to interpolate. These are
--   drawn from several hledger report types, so are not all applicable for
--   a given report.
data ReportItemField

-- | A posting or balance report item's account name
AccountField :: ReportItemField

-- | A posting or register or entry report item's date
DefaultDateField :: ReportItemField

-- | A posting or register or entry report item's description
DescriptionField :: ReportItemField

-- | A balance or posting report item's balance or running total. Always
--   rendered right-justified.
TotalField :: ReportItemField

-- | A balance report item's indent level (which may be different from the
--   account name depth). Rendered as this number of spaces, multiplied by
--   the minimum width spec if any.
DepthSpacerField :: ReportItemField

-- | A report item's nth field. May be unimplemented.
FieldNo :: Int -> ReportItemField

-- | Default line format for balance report: "%20(total)
--   %2(depth_spacer)%-(account)"
defaultBalanceLineFormat :: StringFormat
tests_StringFormat :: TestTree
instance Data.Default.Internal.Default Hledger.Data.StringFormat.StringFormat
instance GHC.Internal.Classes.Eq Hledger.Data.StringFormat.ReportItemField
instance GHC.Internal.Classes.Eq Hledger.Data.StringFormat.StringFormat
instance GHC.Internal.Classes.Eq Hledger.Data.StringFormat.StringFormatComponent
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.ReportItemField
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.StringFormat
instance GHC.Internal.Show.Show Hledger.Data.StringFormat.StringFormatComponent


-- | A simple <a>Amount</a> is some quantity of money, shares, or anything
--   else. It has a (possibly null) <a>CommoditySymbol</a> and a numeric
--   quantity:
--   
--   <pre>
--   $1
--   £-50
--   EUR 3.44
--   GOOG 500
--   1.5h
--   90 apples
--   0
--   </pre>
--   
--   It may also have an <a>AmountCost</a>, representing this amount's
--   per-unit or total cost in a different commodity. If present, this is
--   rendered like so:
--   
--   <pre>
--   EUR 2 @ $1.50  (unit cost)
--   EUR 2 @@ $3   (total cost)
--   </pre>
--   
--   A <a>MixedAmount</a> is zero or more simple amounts, so can represent
--   multiple commodities; this is the type most often used:
--   
--   <pre>
--   0
--   $50 + EUR 3
--   16h + $13.55 + AAPL 500 + 6 oranges
--   </pre>
--   
--   A mixed amount is always "normalised", it has no more than one amount
--   in each commodity and cost. When calling <a>amounts</a> it will have
--   no zero amounts, or just a single zero amount and no other amounts.
--   
--   Limited arithmetic with simple and mixed amounts is supported, best
--   used with similar amounts since it mostly ignores costss and commodity
--   exchange rates.
module Hledger.Data.Amount

-- | Show space-containing commodity symbols quoted, as they are in a
--   journal.
showCommoditySymbol :: Text -> Text
isNonsimpleCommodityChar :: Char -> Bool
quoteCommoditySymbolIfNeeded :: Text -> Text

-- | The empty simple amount - a zero with no commodity symbol or cost and
--   the default amount display style.
nullamt :: Amount

-- | A special amount used as a marker, meaning "no explicit amount
--   provided here, infer it when needed". It is nullamt with commodity
--   symbol <a>AUTO</a>.
missingamt :: Amount
num :: Quantity -> Amount
usd :: DecimalRaw Integer -> Amount
eur :: DecimalRaw Integer -> Amount
gbp :: DecimalRaw Integer -> Amount
per :: Quantity -> Amount
hrs :: Quantity -> Amount
at :: Amount -> Amount -> Amount
(@@) :: Amount -> Amount -> Amount

-- | Convert an amount to the specified commodity, ignoring and discarding
--   any costs and assuming an exchange rate of 1.
amountWithCommodity :: CommoditySymbol -> Amount -> Amount

-- | Convert a amount to its total cost in another commodity, using its
--   attached cost amount if it has one. Notes:
--   
--   <ul>
--   <li>cost amounts must be MixedAmounts with exactly one component
--   Amount (or there will be a runtime error XXX)</li>
--   <li>cost amounts should be positive in the Journal (though this is
--   currently not enforced)</li>
--   </ul>
amountCost :: Amount -> Amount

-- | 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

-- | If this amount has a cost basis with a known per-unit cost, replace
--   its transacted cost with that basis cost, so that <a>amountCost</a>,
--   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

-- | Is this Amount (and its total cost, if it has one) exactly zero,
--   ignoring its display precision ?
amountIsZero :: Amount -> Bool

-- | Do this Amount and (and its total cost, if it has one) appear to be
--   zero when rendered with its display precision ? The display precision
--   should usually have a specific value here; if unset, it will be
--   treated like NaturalPrecision.
amountLooksZero :: Amount -> Bool

-- | 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

-- | 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

-- | Like <a>divideAmount</a>, but sets the display precision to exactly
--   the number of significant decimal digits in the quotient (capped at
--   <a>defaultMaxDisplayPrecision</a>), 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 <a>divideAmount</a>
--   to keep the report's chosen precision.
divideAmountAndUpdatePrecision :: Quantity -> Amount -> Amount

-- | Multiply an amount's quantity (and its total cost, if it has one) by a
--   constant.
multiplyAmount :: Quantity -> Amount -> Amount

-- | 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

-- | Invert an amount (replace its quantity q with 1/q). The amount's
--   transacted price, if any, is not changed. An amount with zero quantity
--   is left unchanged.
invertAmount :: Amount -> Amount

-- | Default amount style
amountstyle :: AmountStyle

-- | <i>Deprecated: please use styleAmounts instead</i>
canonicaliseAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | <i>Deprecated: please use styleAmounts instead</i>
styleAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | <i>Deprecated: please use styleAmounts instead</i>
amountSetStyles :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Set this amount style's rounding strategy when it is being applied to
--   amounts.
amountStyleSetRounding :: Rounding -> AmountStyle -> AmountStyle

-- | Set these amount styles' rounding strategy when they are being applied
--   to amounts.
amountStylesSetRounding :: Rounding -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle

-- | Reset this amount's display style to the default.
amountUnstyled :: Amount -> Amount

-- | Given a list of amounts, in parse order (roughly speaking; see
--   journalStyleInfluencingAmounts), build a map from their commodity
--   names to standard commodity display formats. Can return an error
--   message eg if inconsistent number formats are found.
--   
--   Though, these amounts may have come from multiple files, so we
--   shouldn't assume they use consistent number formats. Currently we
--   don't enforce that even within a single file, and this function never
--   reports an error.
commodityStylesFromAmounts :: [Amount] -> Either String (Map CommoditySymbol AmountStyle)

-- | 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 -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle

-- | Get an amount and its attached cost amount if any. Returns one or two
--   amounts.
getAmounts :: Amount -> [Amount]

-- | Formatting options available when displaying Amounts and MixedAmounts.
--   Similar to <a>AmountStyle</a> but lower level, not attached to amounts
--   or commodities, and can override it in some ways. See also hledger
--   manual &gt; "Amount formatting, parseability", which speaks of human,
--   hledger, and machine output.
data AmountFormat
AmountFormat :: Bool -> Bool -> Maybe [CommoditySymbol] -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> Bool -> AmountFormat

-- | Whether to display commodity symbols.
[displayCommodity] :: AmountFormat -> Bool

-- | Whether to display commodity symbols for zero Amounts.
[displayZeroCommodity] :: AmountFormat -> Bool

-- | For a MixedAmount, an optional order in which to display the
--   commodities. Also, causes 0s to be generated for any commodities which
--   are not present (important for tabular reports).
[displayCommodityOrder] :: AmountFormat -> Maybe [CommoditySymbol]

-- | Whether to display digit group marks (eg thousands separators)
[displayDigitGroups] :: AmountFormat -> Bool

-- | Whether to add a trailing decimal mark when there are no decimal
--   digits and there are digit group marks, to disambiguate
[displayForceDecimalMark] :: AmountFormat -> Bool

-- | Whether to display on one line.
[displayOneLine] :: AmountFormat -> Bool

-- | Minimum width to pad to
[displayMinWidth] :: AmountFormat -> Maybe Int

-- | Maximum width to clip to
[displayMaxWidth] :: AmountFormat -> Maybe Int

-- | Whether to display Amounts' costs.
[displayCost] :: AmountFormat -> Bool

-- | Whether to display Amounts' cost basis (Ledger-style lot syntax).
[displayCostBasis] :: AmountFormat -> Bool

-- | Whether to ansi-colourise negative Amounts.
[displayColour] :: AmountFormat -> Bool

-- | Whether to enclose complex symbols in quotes (normally true)
[displayQuotes] :: AmountFormat -> Bool

-- | Whether to display cost basis using Ledger-style lot syntax ({COST}
--   <a>DATE</a>) instead of hledger consolidated syntax.
[displayLedgerLotSyntax] :: AmountFormat -> Bool

-- | Display amounts without colour, and with various other defaults.
defaultFmt :: AmountFormat

-- | Like defaultFmt but show zero amounts with commodity symbol and
--   styling, like non-zero amounts.
fullZeroFmt :: AmountFormat

-- | Like defaultFmt but don't show costs or cost basis.
noCostFmt :: AmountFormat

-- | Like defaultFmt but display all amounts on one line.
oneLineFmt :: AmountFormat

-- | Like noCostFmt but display all amounts on one line.
oneLineNoCostFmt :: AmountFormat

-- | A (slightly more) machine-readable amount format; like
--   oneLineNoCostFmt but don't show digit group marks.
machineFmt :: AmountFormat

-- | Render an amount using its display style and the default amount
--   format. Zero-equivalent amounts are shown as just "0". The special
--   "missing" amount is shown as the empty string.
showAmount :: Amount -> String

-- | Like showAmount but uses the given amount format.
showAmountWith :: AmountFormat -> Amount -> String

-- | 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)

-- | Render an amount using its display style and the given amount format,
--   as a builder for efficiency. (This can be converted to a Text with
--   wbToText or to a String with wbUnpack). The special "missing" amount
--   is displayed as the empty string.
showAmountB :: AmountFormat -> Amount -> WideBuilder

-- | Get a Text Builder for the string representation of the number part of
--   of an amount, using the display settings from its commodity. Also
--   returns the width of the number. With a true first argument, if there
--   are no decimal digits but there are digit group separators, it shows
--   the amount with a trailing decimal mark to help disambiguate it for
--   parsing.
showAmountQuantity :: Bool -> Amount -> WideBuilder
showAmountCost :: Amount -> String
showAmountCostB :: AmountFormat -> Amount -> WideBuilder

-- | Show an amount's cost basis as consolidated lot syntax: {DATE,
--   <a>LABEL</a>, COST}.
showAmountCostBasis :: Amount -> String
showAmountCostBasisB :: AmountFormat -> Amount -> WideBuilder

-- | Show an amount's cost basis as Ledger-style lot syntax: {LOTCOST}
--   <a>LOTDATE</a>. Kept for future --ledger-lot-syntax flag (step 3).
showAmountCostBasisLedger :: Amount -> String
showAmountCostBasisLedgerB :: AmountFormat -> Amount -> WideBuilder

-- | Colour version. For a negative amount, adds ANSI codes to change the
--   colour, currently to hard-coded red.
--   
--   <pre>
--   cshowAmount = wbUnpack . showAmountB def{displayColour=True}
--   </pre>
cshowAmount :: Amount -> String

-- | Like showAmount, but show a zero amount's commodity if it has one.
--   
--   <pre>
--   showAmountWithZeroCommodity = wbUnpack . showAmountB defaultFmt{displayZeryCommodity=True}
--   </pre>
showAmountWithZeroCommodity :: Amount -> String

-- | Get a string representation of an amount for debugging, appropriate to
--   the current debug level. 9 shows maximum detail.
showAmountDebug :: Amount -> String

-- | Get the string representation of an amount, without any @ cost.
--   
--   <pre>
--   showAmountWithoutCost = wbUnpack . showAmountB noCostFmt
--   </pre>
showAmountWithoutCost :: Amount -> String

-- | Set an amount's display precision.
amountSetPrecision :: AmountPrecision -> Amount -> Amount

-- | Ensure an amount's display precision is at least the given minimum
--   precision. Always sets an explicit Precision.
amountSetPrecisionMin :: Word8 -> Amount -> Amount

-- | Ensure an amount's display precision is at most the given maximum
--   precision. Always sets an explicit Precision.
amountSetPrecisionMax :: Word8 -> Amount -> Amount

-- | Set an amount's display precision, flipped.
withPrecision :: Amount -> AmountPrecision -> Amount

-- | Increase an amount's display precision, if needed, to enough decimal
--   places to show it exactly (showing all significant decimal digits,
--   without trailing zeros). If the amount's display precision is unset,
--   it will be treated as precision 0.
amountSetFullPrecision :: Amount -> Amount

-- | We often want to display "infinite decimal" amounts rounded to some
--   readable number of digits, while still displaying amounts with a large
--   but "non infinite" number of decimal digits (eg 10 or 100 or 200
--   digits) in full. This helper is like amountSetFullPrecision, but with
--   some refinements:
--   
--   <ol>
--   <li>A maximum display precision can be specified, setting a hard upper
--   limit.</li>
--   <li>If no limit is specified, and the internal precision is the
--   maximum (255), indicating an infinite decimal, display precision is
--   set to a smaller default (8).</li>
--   </ol>
--   
--   This function always sets an explicit display precision (ie, Precision
--   n).
amountSetFullPrecisionUpTo :: Maybe Word8 -> Amount -> Amount

-- | How many internal decimal digits are stored for this amount ?
amountInternalPrecision :: Amount -> Word8

-- | How many decimal digits will be displayed for this amount ?
amountDisplayPrecision :: Amount -> Word8

-- | The fallback display precision used when showing amounts representing
--   an infinite decimal.
defaultMaxDisplayPrecision :: Word8

-- | Set an amount's internal decimal precision as well as its display
--   precision. This rounds or pads its Decimal quantity to the specified
--   number of decimal places. Rounding is done with Data.Decimal's default
--   roundTo function: "If the value ends in 5 then it is rounded to the
--   nearest even value (Banker's Rounding)".
setAmountInternalPrecision :: Word8 -> Amount -> Amount

-- | setAmountInternalPrecision with arguments flipped.
withInternalPrecision :: Amount -> Word8 -> Amount

-- | Set (or clear) an amount's display decimal point.
setAmountDecimalPoint :: Maybe Char -> Amount -> Amount

-- | Set (or clear) an amount's display decimal point, flipped.
withDecimalPoint :: Amount -> Maybe Char -> Amount

-- | Strip all costs from an Amount
amountStripCost :: Amount -> Amount

-- | The empty mixed amount.
nullmixedamt :: MixedAmount

-- | A special mixed amount used as a marker, meaning "no explicit amount
--   provided here, infer it when needed".
missingmixedamt :: MixedAmount

-- | Does this MixedAmount include the "missing amount" marker ? Note:
--   currently does not test for equality with missingmixedamt, instead it
--   looks for missingamt among the Amounts. missingamt should always be
--   alone, but detect it even if not.
isMissingMixedAmount :: MixedAmount -> Bool

-- | Convert amounts in various commodities into a mixed amount.
mixed :: Foldable t => t Amount -> MixedAmount

-- | Create a MixedAmount from a single Amount.
mixedAmount :: Amount -> MixedAmount

-- | Add an Amount to a MixedAmount, and then normalise that. (Any cost
--   basis on the amounts will be lost.)
maAddAmount :: MixedAmount -> Amount -> MixedAmount

-- | 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

-- | Get a mixed amount's component amounts, with some cleanups. The
--   following descriptions are old and possibly wrong:
--   
--   <ul>
--   <li>amounts in the same commodity are combined unless they have
--   different costs or total costs</li>
--   <li>multiple zero amounts, all with the same non-null commodity, are
--   replaced by just the last of them, preserving the commodity and amount
--   style (all but the last zero amount are discarded)</li>
--   <li>multiple zero amounts with multiple commodities, or no
--   commodities, are replaced by one commodity-less zero amount</li>
--   <li>an empty amount list is replaced by one commodity-less zero
--   amount</li>
--   <li>the special "missing" mixed amount remains unchanged</li>
--   </ul>
amounts :: MixedAmount -> [Amount]

-- | Get a mixed amount's component amounts without normalising zero and
--   missing amounts. This is used for JSON serialisation, so the order is
--   important. In particular, we want the Amounts given in the order of
--   the MixedAmountKeys, i.e. sorted by commodity and transacted cost.
amountsRaw :: MixedAmount -> [Amount]

-- | Get a mixed amount's component amounts, with some cleanups. This is a
--   new version of <tt>amounts</tt>, with updated descriptions and
--   optimised for <tt>print</tt> to show commodityful zeros.
--   
--   <ul>
--   <li>If it contains the "missing amount" marker, only that is returned
--   (discarding any additional amounts).</li>
--   <li>Or if it contains any non-zero amounts, only those are returned
--   (discarding any zeroes).</li>
--   <li>Or if it contains any zero amounts (possibly more than one,
--   possibly in different commodities), all of those are returned.</li>
--   <li>Otherwise the null amount is returned.</li>
--   </ul>
amountsPreservingZeros :: MixedAmount -> [Amount]

-- | Get this mixed amount's commodities as a set. Returns an empty set if
--   there are no amounts.
maCommodities :: MixedAmount -> Set CommoditySymbol

-- | Filter a mixed amount's component amounts by a predicate.
filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount

-- | 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

-- | Apply a transform to a mixed amount's component <a>Amount</a>s.
mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount

-- | Unify a MixedAmount to a single commodity value if possible. This
--   consolidates amounts of the same commodity and discards zero amounts;
--   but this one insists on simplifying to a single commodity, and will
--   return Nothing if this is not possible.
unifyMixedAmount :: MixedAmount -> Maybe Amount

-- | Remove all transacted costs and cost bases from a MixedAmount.
mixedAmountStripCosts :: MixedAmount -> MixedAmount

-- | Convert all component amounts to cost where possible (see amountCost).
mixedAmountCost :: MixedAmount -> MixedAmount

-- | Convert all component amounts to cost basis (or else transacted cost)
--   where possible (see amountCostBasis).
mixedAmountCostBasis :: MixedAmount -> MixedAmount

-- | Negate mixed amount's quantities (and total costs, if any).
maNegate :: MixedAmount -> MixedAmount

-- | Sum two MixedAmounts. (Any cost basis on the amounts will be lost.)
maPlus :: MixedAmount -> MixedAmount -> MixedAmount

-- | Subtract a MixedAmount from another. (Any cost basis on the amounts
--   will be lost.)
maMinus :: MixedAmount -> MixedAmount -> MixedAmount

-- | Sum a collection of MixedAmounts. (Any cost basis on the amounts will
--   be lost.)
maSum :: Foldable t => t MixedAmount -> MixedAmount

-- | 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

-- | Like <a>divideMixedAmount</a>, but sets each component amount's
--   display precision to exactly the number of significant decimal digits
--   in the quotient (capped at <a>defaultMaxDisplayPrecision</a>), 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 <a>divideMixedAmount</a>.
divideMixedAmountAndUpdatePrecision :: Quantity -> MixedAmount -> MixedAmount

-- | Multiply a mixed amount's quantities (and total costs, if any) by a
--   constant.
multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount

-- | Calculate the average of some mixed amounts.
averageMixedAmounts :: Foldable f => f MixedAmount -> MixedAmount

-- | Calculate the sum and average of some mixed amounts.
sumAndAverageMixedAmounts :: Foldable f => f MixedAmount -> (MixedAmount, MixedAmount)

-- | Is this amount negative ? The cost is ignored.
isNegativeAmount :: Amount -> Bool

-- | Is this mixed amount negative, if we can tell that unambiguously? Ie
--   when normalised, are all individual commodity amounts negative ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool

-- | Round an Amount's Quantity (internally) to match its display
--   precision. If that is unset or NaturalPrecision, this does nothing.
amountRoundedQuantity :: Amount -> Quantity

-- | Is this mixed amount exactly zero, ignoring its display precision? See
--   amountIsZero.
mixedAmountIsZero :: MixedAmount -> Bool

-- | Is this mixed amount exactly zero, ignoring its display precision?
--   
--   A convenient alias for mixedAmountIsZero.
maIsZero :: MixedAmount -> Bool

-- | Is this mixed amount non-zero, ignoring its display precision?
--   
--   A convenient alias for not . mixedAmountIsZero.
maIsNonZero :: MixedAmount -> Bool

-- | Does this mixed amount appear to be zero when rendered with its
--   display precision? See amountLooksZero.
mixedAmountLooksZero :: MixedAmount -> Bool

-- | <i>Deprecated: please use mixedAmountSetStyle False (or styleAmounts)
--   instead</i>
canonicaliseMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Given a map of standard commodity display styles, find and apply the
--   appropriate style to each individual amount.

-- | <i>Deprecated: please use styleAmounts instead</i>
styleMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | <i>Deprecated: please use styleAmounts instead</i>
mixedAmountSetStyles :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Reset each individual amount's display style to the default.
mixedAmountUnstyled :: MixedAmount -> MixedAmount

-- | Render a mixed amount using its amount display styles and the default
--   amount format, after normalising it (to at most one amount in each of
--   its commodities). See showMixedAmountB for special cases.
showMixedAmount :: MixedAmount -> String

-- | Like showMixedAmount but uses the given amount format. See
--   showMixedAmountB for special cases.
showMixedAmountWith :: AmountFormat -> MixedAmount -> String

-- | Like <a>showAmountsDistinctly</a> but for <a>MixedAmount</a>. 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)

-- | Get the one-line string representation of a mixed amount (also showing
--   any costs). See showMixedAmountB for special cases.
showMixedAmountOneLine :: MixedAmount -> String

-- | Get an unambiguous string representation of a mixed amount for
--   debugging.
showMixedAmountDebug :: MixedAmount -> String

-- | Get the string representation of a mixed amount, without showing any
--   costs. With a True argument, adds ANSI codes to show negative amounts
--   in red. See showMixedAmountB for special cases.
showMixedAmountWithoutCost :: Bool -> MixedAmount -> String

-- | Get the one-line string representation of a mixed amount, but without
--   any @ costs. With a True argument, adds ANSI codes to show negative
--   amounts in red. See showMixedAmountB for special cases.
showMixedAmountOneLineWithoutCost :: Bool -> MixedAmount -> String

-- | Like showMixedAmountOneLineWithoutCost, but show at most the given
--   width, with an elision indicator if there are more. With a True
--   argument, adds ANSI codes to show negative amounts in red. See
--   showMixedAmountB for special cases.
showMixedAmountElided :: Int -> Bool -> MixedAmount -> String

-- | Like showMixedAmount, but zero amounts are shown with their commodity
--   if they have one. See showMixedAmountB for special cases.
showMixedAmountWithZeroCommodity :: MixedAmount -> String

-- | Render a mixed amount using its amount display styles and the given
--   amount format, as a builder for efficiency. (This can be converted to
--   a Text with wbToText or to a String with wbUnpack).
--   
--   Warning: this (and its showMixedAmount aliases above) basically
--   assumes amounts have no costs. It can show misleading costs or not
--   show costs which are there.
--   
--   If a maximum width is given then:
--   
--   <ul>
--   <li>If displayed on one line, it will display as many Amounts as can
--   fit in the given width, and further Amounts will be elided. There will
--   always be at least one amount displayed, even if this will exceed the
--   requested maximum width.</li>
--   <li>If displayed on multiple lines, any Amounts longer than the
--   maximum width will be elided.</li>
--   </ul>
--   
--   Zero-equivalent amounts are shown as just "0".
--   
--   The special "missing" amount is shown as the empty string (?).
showMixedAmountB :: AmountFormat -> MixedAmount -> WideBuilder

-- | Helper for showMixedAmountB (and postingAsLines, ...) to show a list
--   of Amounts on multiple lines. This returns the list of WideBuilders:
--   one for each Amount, and padded/elided to the appropriate width. This
--   does not honour displayOneLine; all amounts will be displayed as if
--   displayOneLine were False.
showMixedAmountLinesB :: AmountFormat -> MixedAmount -> [WideBuilder]

-- | Like <a>showMixedAmountLinesB</a> but also returns the amounts
--   associated with each text builder.
showMixedAmountLinesPartsB :: AmountFormat -> MixedAmount -> [(WideBuilder, Amount)]

-- | Like <a>showMixedAmountOneLineB</a> 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)]

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String

-- | Set the display precision in the amount's commodities.
mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount

-- | In each component amount, increase the display precision sufficiently
--   to render it exactly (showing all significant decimal digits).
mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount

-- | 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

-- | In each component amount, increase the display precision sufficiently
--   to render it exactly if possible, but not more than the given max
--   precision, and if no max precision is given and the amount has
--   infinite decimals, limit display precision to a hard-coded smaller
--   number (8). See amountSetFullPrecisionUpTo.
mixedAmountSetFullPrecisionUpTo :: Maybe Word8 -> MixedAmount -> MixedAmount

-- | In each component amount, ensure the display precision is at least the
--   given value. Makes all amounts have an explicit Precision.
mixedAmountSetPrecisionMin :: Word8 -> MixedAmount -> MixedAmount

-- | In each component amount, ensure the display precision is at most the
--   given value. Makes all amounts have an explicit Precision.
mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount

-- | 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 -> Text
tests_Amount :: TestTree
instance Data.Default.Internal.Default Hledger.Data.Amount.AmountFormat
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (Hledger.Data.Types.Account a)
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Amount
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.BalanceData
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.MixedAmount
instance Hledger.Data.Types.HasAmounts a => Hledger.Data.Types.HasAmounts (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Base.Monoid Hledger.Data.Types.MixedAmount
instance GHC.Internal.Num.Num Hledger.Data.Types.Amount
instance GHC.Internal.Num.Num Hledger.Data.Types.MixedAmount
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.MixedAmount
instance GHC.Internal.Show.Show Hledger.Data.Amount.AmountDisplay
instance GHC.Internal.Show.Show Hledger.Data.Amount.AmountFormat


-- | Rich data type to describe data in a table. This is the basis for ODS
--   and HTML export.
module Hledger.Write.Spreadsheet
data Type
TypeString :: Type
TypeInteger :: Type
TypeAmount :: Amount -> Type
TypeMixedAmount :: Type
TypeDate :: Type
data Style
Body :: Emphasis -> Style
Head :: Style
data Emphasis
Item :: Emphasis
Total :: Emphasis
data Cell border text
Cell :: Type -> Border border -> Style -> Span -> Text -> Text -> Class -> [text] -> text -> Cell border text
[cellType] :: Cell border text -> Type
[cellBorder] :: Cell border text -> Border border
[cellStyle] :: Cell border text -> Style
[cellSpan] :: Cell border text -> Span
[cellAnchor] :: Cell border text -> Text

-- | A whole-phrase description of where <a>cellAnchor</a> leads, for
--   writers that can attach one to a link (HTML's title attribute).
--   Ignored when there is no anchor.
[cellTitle] :: Cell border text -> Text
[cellClass] :: Cell border text -> 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;
--   <a>cellContent</a> is always complete.
[cellParts] :: Cell border text -> [text]
[cellContent] :: Cell border text -> text
newtype Class
Class :: Text -> Class
textFromClass :: Class -> Text

-- | <ul>
--   <li><a>NoSpan</a> means a single unmerged cell.</li>
--   <li><a>Covered</a> is a cell if it is part of a horizontally or
--   vertically merged cell. We maintain these cells although they are
--   ignored in HTML output. In contrast to that, FODS can store covered
--   cells and allows to access the hidden cell content via formulas. CSV
--   does not support merged cells and thus simply writes the content of
--   covered cells. Maintaining <a>Covered</a> cells also simplifies
--   transposing.</li>
--   <li><tt><a>SpanHorizontal</a> n</tt> denotes the first cell in a row
--   that is part of a merged cell. The merged cell contains <tt>n</tt>
--   atomic cells, including the first one. That is <tt>SpanHorizontal
--   1</tt> is actually like <tt>NoSpan</tt>. The content of this cell is
--   shown as content of the merged cell.</li>
--   <li><tt><a>SpanVertical</a> n</tt> starts a vertically merged
--   cell.</li>
--   </ul>
--   
--   The writer functions expect consistent data, that is, <a>Covered</a>
--   cells must actually be part of a merged cell and merged cells must
--   only cover <a>Covered</a> cells.
data Span
NoSpan :: Span
Covered :: Span
SpanHorizontal :: Int -> Span
SpanVertical :: Int -> Span
data Border lines
Border :: lines -> lines -> lines -> lines -> Border lines
[borderLeft] :: Border lines -> lines
[borderRight] :: Border lines -> lines
[borderTop] :: Border lines -> lines
[borderBottom] :: Border lines -> lines
class Lines border
noLine :: Lines border => border

-- | The same as Tab.Properties, but has <a>Eq</a> and <a>Ord</a>
--   instances. We need those for storing <a>NumLines</a> in <tt>Set</tt>s.
data NumLines
NoLine :: NumLines
SingleLine :: NumLines
DoubleLine :: NumLines
noBorder :: Lines border => Border border
defaultCell :: Lines border => text -> Cell border text
headerCell :: Lines borders => Text -> Cell borders Text
emptyCell :: (Lines border, Monoid text) => Cell border text
transposeCell :: Cell border text -> Cell border text
transpose :: [[Cell border text]] -> [[Cell border text]]
horizontalSpan :: (Lines border, Monoid text) => [a] -> Cell border text -> [Cell border text]
addHeaderBorders :: Functor f => f (Cell () text) -> f (Cell NumLines text)
addRowSpanHeader :: Cell border text -> [[Cell border text]] -> [[Cell border text]]
addRowSpanHeaderNE :: Cell border text -> [[Cell border text]] -> [NonEmpty (Cell border text)]
rawTableContent :: Functor f => [f (Cell border text)] -> [f text]
cellFromMixedAmount :: Lines border => AmountFormat -> (Class, MixedAmount) -> Cell border WideBuilder
cellsFromMixedAmount :: Lines border => AmountFormat -> (Class, MixedAmount) -> [Cell border WideBuilder]
cellFromAmount :: Lines border => AmountFormat -> (Class, (wb, Amount)) -> Cell border wb
integerCell :: Lines border => Integer -> Cell border Text
instance GHC.Internal.Base.Applicative Hledger.Write.Spreadsheet.Border
instance GHC.Internal.Classes.Eq lines => GHC.Internal.Classes.Eq (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Internal.Classes.Eq Hledger.Write.Spreadsheet.Emphasis
instance GHC.Internal.Classes.Eq Hledger.Write.Spreadsheet.NumLines
instance GHC.Internal.Classes.Eq Hledger.Write.Spreadsheet.Span
instance GHC.Internal.Classes.Eq Hledger.Write.Spreadsheet.Style
instance GHC.Internal.Classes.Eq Hledger.Write.Spreadsheet.Type
instance GHC.Internal.Data.Foldable.Foldable Hledger.Write.Spreadsheet.Border
instance GHC.Internal.Base.Functor Hledger.Write.Spreadsheet.Border
instance GHC.Internal.Base.Functor (Hledger.Write.Spreadsheet.Cell border)
instance Hledger.Write.Spreadsheet.Lines Hledger.Write.Spreadsheet.NumLines
instance Hledger.Write.Spreadsheet.Lines ()
instance GHC.Internal.Classes.Ord lines => GHC.Internal.Classes.Ord (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Internal.Classes.Ord Hledger.Write.Spreadsheet.Emphasis
instance GHC.Internal.Classes.Ord Hledger.Write.Spreadsheet.NumLines
instance GHC.Internal.Classes.Ord Hledger.Write.Spreadsheet.Style
instance GHC.Internal.Classes.Ord Hledger.Write.Spreadsheet.Type
instance GHC.Internal.Show.Show lines => GHC.Internal.Show.Show (Hledger.Write.Spreadsheet.Border lines)
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Emphasis
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.NumLines
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Style
instance GHC.Internal.Show.Show Hledger.Write.Spreadsheet.Type


-- | Export table data as OpenDocument Spreadsheet
--   <a>https://docs.oasis-open.org/office/OpenDocument/v1.3/</a>. This
--   format supports character encodings, fixed header rows and columns,
--   number formatting, text styles, merged cells, formulas, hyperlinks.
--   Currently we support Flat ODS, a plain uncompressed XML format.
--   
--   This is derived from
--   <a>https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs</a>
module Hledger.Write.Ods
printFods :: TextEncoding -> Map Text ((Int, Int), [[Cell NumLines Text]]) -> Text
instance GHC.Internal.Classes.Eq Hledger.Write.Ods.CommodityStyle
instance GHC.Internal.Classes.Eq Hledger.Write.Ods.DataStyle
instance GHC.Internal.Classes.Ord Hledger.Write.Ods.CommodityStyle
instance GHC.Internal.Classes.Ord Hledger.Write.Ods.DataStyle
instance GHC.Internal.Show.Show Hledger.Write.Ods.CommodityStyle
instance GHC.Internal.Show.Show Hledger.Write.Ods.DataStyle


-- | HTML writing helpers, using blaze-html, whose markup type is also the
--   one hledger-web's pages are made of.
--   
--   They render <a>Hledger.Write.Spreadsheet</a> tables as HTML tables:
--   the CLI's <tt>-O html</tt> output uses <a>styledTableHtml</a> and
--   <a>titledTableHtml</a>, and hledger-web's report pages use
--   <a>formatCell</a> 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 <a>nl</a>).
module Hledger.Write.Html
type Html = Markup
toHtml :: ToMarkup a => a -> Html
class Lines border => Lines border

-- | The class suffix naming this kind of border line, if it is drawn.
borderClass :: Lines border => border -> Maybe Text

-- | The CSS classes marking a cell's borders, eg
--   <tt>border-top-double</tt>. 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
--   <a>Hledger.Write.Html.Attribute</a>.
borderClasses :: Lines border => Cell border text -> [Text]
formatCell :: Lines border => Cell border Html -> Html
formatRow :: Lines border => [Cell border Html] -> Html

-- | Render a report title as an HTML heading.
formatTitle :: Text -> Html
htmlAsText :: Html -> Text
htmlAsLazyText :: Html -> Text

-- | 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

-- | Export spreadsheet table data as HTML table. This is derived from
--   <a>https://hackage.haskell.org/package/classify-frog-0.2.4.3/src/src/Spreadsheet/Format.hs</a>
styledTableHtml :: Lines border => [[Cell border Html]] -> Html

-- | Like <a>styledTableHtml</a>, but with the given report title, if
--   non-empty, as a heading above the table.
titledTableHtml :: Lines border => Text -> [[Cell border Html]] -> Html
tests_Hledger_Write_Html :: TestTree
instance Hledger.Write.Html.Lines Hledger.Write.Spreadsheet.NumLines
instance Hledger.Write.Html.Lines ()


-- | Convert amounts to some related value in various ways. This involves
--   looking up historical market prices (exchange rates) between
--   commodities.
module Hledger.Data.Valuation

-- | 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 :: ConversionOp
ToCost :: ConversionOp
ToTransactedCost :: ConversionOp

-- | What kind of value conversion should be done on amounts ? CLI:
--   --value=then|end|now|DATE[,COMM]
data ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at each posting's date
AtThen :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at period end(s)
AtEnd :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using current market
--   prices
AtNow :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   on some date
AtDate :: Day -> Maybe CommoditySymbol -> ValuationType

-- | A price oracle is a magic memoising function that efficiently looks up
--   market prices (exchange rates) from one commodity to another (or if
--   unspecified, to a default valuation commodity) on a given date.
type PriceOracle = (Day, CommoditySymbol, Maybe CommoditySymbol) -> Maybe (CommoditySymbol, Quantity)

-- | Generate a price oracle (memoising price lookup function) from a
--   journal's directive-declared and transaction-inferred market prices.
--   For best performance, generate this only once per journal, reusing it
--   across reports if there are more than one, as compoundBalanceCommand
--   does. The boolean argument is whether to infer market prices from
--   transactions or not.
--   
--   Commodity aliases are also used, as fixed exchange rates (see
--   <a>buildPriceIndexes</a>), 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

-- | A journal's commodity aliases, as fixed exchange rates: price
--   directives dated <a>nulldate</a>, 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]

-- | Convert all component amounts to cost/selling price if requested, and
--   style them.
mixedAmountToCost :: Map CommoditySymbol AmountStyle -> ConversionOp -> MixedAmount -> MixedAmount

-- | Apply a specified valuation to this mixed amount, using the provided
--   price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
mixedAmountApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount

-- | Find the market value of each component amount in the given commodity,
--   or its default valuation commodity, at the given valuation date, using
--   the given market price oracle. When market prices available on that
--   date are not sufficient to calculate the value, amounts are left
--   unchanged.
mixedAmountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount

-- | Find the market value of this amount in the given valuation commodity
--   if any, otherwise the default valuation commodity, at the given
--   valuation date. (The default valuation commodity is the commodity of
--   the latest applicable market price before the valuation date.)
--   
--   The returned amount will have its commodity's canonical style applied,
--   (with soft display rounding).
--   
--   If the market prices available on that date are not sufficient to
--   calculate this value, the amount is left unchanged.
amountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> Amount -> Amount

-- | Calculate the gain of each component amount, that is the difference
--   between the valued amount and the value of the cost basis (see
--   mixedAmountApplyValuation).
--   
--   Note: the cost subtracted here is the sum of every contributing
--   posting's cost basis where known (lot postings), else transacted cost,
--   regardless of direction. (Summing postings merges amounts and can drop
--   their bases, so for --gain reports, lot postings' transacted costs are
--   first replaced by their basis costs; see
--   Hledger.Cli.Utils.journalPrepareLotDetail.) For a non-lot disposal
--   posting recording its sale price with <tt>, 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 </tt>
--   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 -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount

-- | Calculate the gain of each component amount, that is the difference
--   between the valued amount and the value of the cost basis.
--   
--   If the commodity we are valuing in is not the same as the commodity of
--   the cost, this will value the cost at the same date as the primary
--   amount. This may not be what you want; for example you may want the
--   cost valued at the posting date. If so, let us know and we can change
--   this behaviour.
mixedAmountGainAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
marketPriceReverse :: MarketPrice -> MarketPrice
priceDirectiveToMarketPrice :: PriceDirective -> MarketPrice

-- | Infer a market price from the given amount and its cost (if any), and
--   make a corresponding price directive on the given date. The price's
--   display precision will be set to show all significant decimal digits;
--   or if they seem to be infinite, defaultPrecisionLimit.
amountPriceDirectiveFromCost :: Day -> Amount -> Maybe PriceDirective
valuationTypeValuationCommodity :: ValuationType -> Maybe CommoditySymbol
tests_Valuation :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Data.Valuation.ConversionOp
instance GHC.Internal.Classes.Eq Hledger.Data.Valuation.ValuationType
instance GHC.Internal.Generics.Generic Hledger.Data.Valuation.PriceGraph
instance GHC.Internal.Show.Show Hledger.Data.Valuation.ConversionOp
instance GHC.Internal.Show.Show Hledger.Data.Valuation.PriceGraph
instance GHC.Internal.Show.Show Hledger.Data.Valuation.ValuationType


-- | A <a>Posting</a> represents a change (by some <a>MixedAmount</a>) of
--   the balance in some <a>Account</a>. Each <a>Transaction</a> contains
--   two or more postings which should add up to 0. Postings reference
--   their parent transaction, so we can look up the date or description
--   there.
module Hledger.Data.Posting
nullposting :: Posting
posting :: Posting

-- | Make a posting to an account.
post :: AccountName -> Amount -> Posting

-- | Make a virtual (unbalanced) posting to an account.
vpost :: AccountName -> Amount -> Posting

-- | Make a posting to an account, maybe with a balance assertion.
post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting

-- | Make a virtual (unbalanced) posting to an account, maybe with a
--   balance assertion.
vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
nullassertion :: BalanceAssertion

-- | Make a partial, exclusive balance assertion.
balassert :: Amount -> Maybe BalanceAssertion

-- | Make a total, exclusive balance assertion.
balassertTot :: Amount -> Maybe BalanceAssertion

-- | Make a partial, inclusive balance assertion.
balassertParInc :: Amount -> Maybe BalanceAssertion

-- | Make a total, inclusive balance assertion.
balassertTotInc :: Amount -> Maybe BalanceAssertion
originalPosting :: Posting -> Posting

-- | Get a posting's status. This is cleared or pending if those are
--   explicitly set on the posting, otherwise the status of its parent
--   transaction, or unmarked if there is no parent transaction. (Note the
--   ambiguity, unmarked can mean "posting and transaction are both
--   unmarked" or "posting is unmarked and don't know about the
--   transaction".
postingStatus :: Posting -> Status
isReal :: Posting -> Bool
isVirtual :: Posting -> Bool
isBalancedVirtual :: Posting -> Bool
isEmptyPosting :: Posting -> Bool
hasBalanceAssignment :: Posting -> Bool
hasAmount :: Posting -> Bool

-- | 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

-- | Tags for this posting including any inherited from its parent
--   transaction.
postingAllTags :: Posting -> [Tag]

-- | Tags for this transaction including any from its postings (which
--   includes any from the postings' accounts).
transactionAllTags :: Transaction -> [Tag]
relatedPostings :: Posting -> [Posting]

-- | Strip all prices from a Posting.
postingStripCosts :: Posting -> Posting

-- | Apply some account aliases to the posting's account name, as described
--   by accountNameApplyAliases. This can fail due to a bad replacement
--   pattern in a regular expression alias.
postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting

-- | Find and apply the appropriate display style to the posting amounts in
--   each commodity (see journalCommodityStyles). Main amount precisions
--   may be set or not according to the styles, but cost precisions are not
--   set.

-- | <i>Deprecated: please use styleAmounts instead</i>
postingApplyCommodityStyles :: Map CommoditySymbol AmountStyle -> Posting -> Posting

-- | Like postingApplyCommodityStyles, but neither main amount precisions
--   or cost precisions are set.

-- | <i>Deprecated: please use styleAmounts instead</i>
postingStyleAmounts :: Map CommoditySymbol AmountStyle -> Posting -> Posting

-- | Add tags to a posting, discarding any for which the posting already
--   has a value. Note this does not add tags to the posting's comment.
postingAddTags :: Posting -> [Tag] -> Posting

-- | Add the given hidden tag to a posting; and with a true argument, also
--   add the equivalent visible tag to the posting's tags and comment
--   fields. If the posting already has these tags (with any value), do
--   nothing.
postingAddHiddenAndMaybeVisibleTag :: Bool -> Bool -> HiddenTag -> Posting -> Posting

-- | Remove the given hidden tag from a posting, and the equivalent visible
--   tag if <a>postingAddHiddenAndMaybeVisibleTag</a> added one: from the
--   posting's tags, and from its comment, where it appears as <tt>NAME:
--   VALUE</tt>, comma-separated from any other content.
postingRemoveHiddenAndVisibleTag :: HiddenTag -> Posting -> Posting

-- | Get a posting's (primary) date - it's own primary date if specified,
--   otherwise the parent transaction's primary date, or the null date if
--   there is no parent transaction.
postingDate :: Posting -> Day

-- | Get a posting's secondary (secondary) date, which is the first of:
--   posting's secondary date, transaction's secondary date, posting's
--   primary date, transaction's primary date, or the null date if there is
--   no parent transaction.
postingDate2 :: Posting -> Day

-- | Get a posting's primary or secondary date, as specified.
postingDateOrDate2 :: WhichDate -> Posting -> Day

-- | Sorted unique account names referenced by these postings.
accountNamesFromPostings :: [Posting] -> [AccountName]

-- | Join two parts of a comment, eg a tag and another tag, or a tag and a
--   non-tag, on a single line. Interpolates a comma and space unless one
--   of the parts is empty.
commentJoin :: Text -> Text -> Text

-- | Add a tag to a comment, comma-separated from any prior content. A
--   space is inserted following the colon, before the value.
commentAddTag :: Text -> Tag -> Text

-- | Like commentAddTag, but omits the space after the colon.
commentAddTagUnspaced :: Text -> Tag -> Text

-- | Add a tag on its own line to a comment, preserving any prior content.
--   A space is inserted following the colon, before the value.
commentAddTagNextLine :: Text -> Tag -> Text

-- | 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

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
generatedTransactionTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
modifiedTransactionTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
generatedPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
feesplitPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
lotsplitPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
lotParentAssertionTagName :: TagName

-- | True if the posting has a tag with the given name (hidden or visible).
postingHasTag :: TagName -> Posting -> Bool

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
costPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
conversionPostingTagName :: TagName

-- | Special tags hledger sometimes adds to mark various things. These
--   should be hidden tag names, beginning with _. With --verbose-tags, the
--   equivalent visible tags will also be added. These tag names are
--   mentioned in docs and can be matched by user queries, so consider the
--   impact before changing them.
imbalancePostingTagName :: TagName

-- | Sum all amounts from a list of postings.
sumPostings :: [Posting] -> MixedAmount

-- | Negate the posting's main amount and balance assertion amount if any.
postingNegate :: Posting -> Posting

-- | Negate the posting's main amount but not the balance assertion amount.
postingNegateMainAmount :: Posting -> Posting
showPosting :: Posting -> String

-- | Render a posting, at the appropriate width for aligning with its
--   siblings if any. Used by the rewrite command.
showPostingLines :: Posting -> [Text]

-- | Render one posting, on one or more lines, suitable for <a>print</a>
--   output. Also returns the <a>PostingWidths</a> computed from this
--   posting's structural data (account name, main amount, assertion
--   operator / amount), used by the caller's lazy knot to derive the
--   layout columns.
--   
--   There will be an indented account name, plus one or more of status
--   flag, posting amount, balance assertion, same-line comment, next-line
--   comments.
--   
--   If the posting's amount is implicit or if elideamount is true, no
--   amount is shown. If the posting's amount is explicit and
--   multi-commodity, multiple similar postings are shown, one for each
--   commodity, to help produce parseable journal syntax. Or if
--   onelineamounts is true, such amounts are shown on one line,
--   comma-separated (and the output will not be valid journal syntax).
--   
--   If an amount is zero, any commodity symbol attached to it is shown
--   (and the corresponding commodity display style is used).
--   
--   Three target columns are supplied via <a>AmountCols</a>:
--   
--   <ul>
--   <li><tt>acDecMark</tt> — 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.</li>
--   <li><tt>acEquals</tt> — the first <tt>=</tt> of any balance-assertion
--   operator (<tt>=</tt>, <tt>==</tt>, <tt>=*</tt>, or <tt>==*</tt>) is
--   padded to land here, one space past the rightmost main amount across
--   all postings.</li>
--   <li><tt>acAssDecMark</tt> — 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.</li>
--   </ul>
--   
--   <tt>acEquals</tt> and <tt>acAssDecMark</tt> 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
--   <tt>AmountFormat</tt>:
--   
--   <ul>
--   <li><tt>displayZeroCommodity = True</tt> — always show the commodity
--   on zero amounts so they participate in alignment.</li>
--   <li><tt>displayForceDecimalMark = True</tt> — force a decimal mark
--   when digit groups are shown, for unambiguous display.</li>
--   <li><tt>displayOneLine = onelineamounts</tt> — driven by this
--   function's parameter.</li>
--   <li><tt>displayMinWidth = Nothing</tt> — disable the legacy
--   right-alignment of multi-commodity amount lines, since this function
--   provides its own decimal-mark alignment.</li>
--   </ul>
postingAsLines :: AmountFormat -> Bool -> Bool -> Int -> Int -> AmountCols -> Posting -> ([Text], PostingWidths)

-- | Render a transaction's postings as indented lines, suitable for
--   <a>print</a> output, using the default posting layout (decimal-mark
--   alignment at column 53).
--   
--   Normally these will be in valid journal syntax which hledger can
--   reparse (though they may include no-longer-valid balance assertions).
--   Explicit amounts are shown, implicit amounts are not.
--   
--   Postings with multicommodity explicit amounts are handled as follows:
--   if onelineamounts is true, these amounts are shown on one line,
--   comma-separated, and the output will not be valid journal syntax.
--   Otherwise, they are shown as several similar postings, one per
--   commodity. When the posting has a balance assertion, it is attached to
--   the last of these postings.
--   
--   Note: a few fields of the caller's <tt>AmountFormat</tt> are
--   overridden internally; see <a>postingAsLines</a> for details.
postingsAsLines :: AmountFormat -> Bool -> [Posting] -> [Text]

-- | Like <a>postingsAsLines</a> but with an explicit <a>PostingLayout</a>:
--   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]

-- | Prepend a suitable indent for a posting (or transaction/posting
--   comment) line.
postingIndent :: Text -> Text

-- | Show an account name, clipped to the given width if any, and
--   appropriately bracketed/parenthesised for the given posting realness.
showAccountName :: Maybe Int -> PostingRealness -> AccountName -> Text

-- | Render a transaction or posting's comment as indented,
--   semicolon-prefixed comment lines. The first line (unless empty) will
--   have leading space, subsequent lines will have a larger indent.
renderCommentLines :: Text -> [Text]

-- | 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

-- | Render the balance-assertion operator glyph: "=", "==", "=*", or
--   "==*".
balanceAssertionOperatorB :: BalanceAssertion -> WideBuilder

-- | Render a balance assertion's expected amount, using the given
--   AmountFormat.
balanceAssertionAmountB :: AmountFormat -> BalanceAssertion -> WideBuilder

-- | How posting lines should be aligned by <a>postingsAsLines</a> /
--   <tt>showTransaction</tt>.
data PostingLayout

-- | Right-align amounts in a 12+-char field, as in hledger 1.x.
LayoutHledger1 :: PostingLayout

-- | Align the first decimal mark of each amount at the given target
--   column.
LayoutDecimal :: Int -> PostingLayout

-- | Default posting layout: decimal-mark alignment at column
--   <a>defaultDecimalMarkColumn</a>.
defaultPostingLayout :: PostingLayout

-- | Default visible column (1-indexed) where posting amount decimal marks
--   should be aligned in <a>print</a> output. Used as the target unless a
--   transaction's account names + amount widths force amounts further
--   right.
defaultDecimalMarkColumn :: Int

-- | Visible-character widths derived from one posting, for cross-posting
--   alignment in <a>postingsAsLinesDecimal</a>. 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 :: Int -> Int -> Int -> Int -> Int -> PostingWidths

-- | Account-name visible width. Used to size the account/status field so
--   all postings' account names line up.
[pwAcct] :: PostingWidths -> 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
--   <a>amountIntegerWidth</a>. For a multi-commodity amount rendered on
--   multiple lines, this is the max across rows. Used to position the
--   decimal mark column.
[pwLeft] :: PostingWidths -> 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 <tt>wbWidth wb - lw</tt> per amount row, taken as the max across
--   rows. Used to position the assertion <tt>=</tt> column one space past
--   the rightmost amount.
[pwRight] :: PostingWidths -> Int

-- | Visible width of this posting's balance-assertion operator: 1
--   (<tt>=</tt>), 2 (<tt>==</tt> or <tt>=*</tt>), 3 (<tt>==*</tt>), or 0
--   if the posting has no <tt>pbalanceassertion</tt>. Used to position the
--   assertion-amount column one space past the widest operator.
[pwOperator] :: PostingWidths -> Int

-- | Assertion amount's integer-side width, computed via
--   <a>amountIntegerWidth</a> on <tt>baamount</tt> with the same display
--   options used for the main amount. 0 if no assertion. Used to
--   decimal-align the assertion amounts.
[pwAsnLeft] :: PostingWidths -> Int

-- | The three target columns derived in the knot of
--   <a>postingsAsLinesDecimal</a> and consumed by <a>postingAsLines</a>
--   for aligning the main amount, the <tt>=</tt> glyph, and the assertion
--   amount. <tt>acEquals</tt> and <tt>acAssDecMark</tt> are 0 when no
--   posting in the group has a balance assertion (in which case the
--   renderer never consults them).
data AmountCols
AmountCols :: Int -> Int -> Int -> AmountCols

-- | Column for the main amount's decimal mark.
[acDecMark] :: AmountCols -> Int

-- | Column for the first <tt>=</tt> of the balance assertion/assignment.
[acEquals] :: AmountCols -> Int

-- | Column for the assertion amount's decimal mark.
[acAssDecMark] :: AmountCols -> Int

-- | 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 <a>Amount</a> 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

-- | Apply a transform function to this posting's main amount (but not its
--   balance assertion amount).
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting

-- | Apply a specified valuation to this posting's amount, using the
--   provided price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
postingApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting

-- | Maybe convert this <a>Posting</a>s amount to cost: to cost basis where
--   known, else transacted cost (ToCost); or to transacted cost
--   (ToTransactedCost).
postingToCost :: ConversionOp -> Posting -> Maybe Posting

-- | 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
--   <a>postingsAddInferredEquityPostings</a>.
postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]

-- | Like <a>postingAddInferredEquityPostings</a>, for a posting or for the
--   consecutive per-lot fragments of one posting (cf
--   <tt>transactionInferEquityPostings</tt>): 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]

-- | Make a market price equivalent to this posting's amount's unit price,
--   if any.
postingPriceDirectivesFromCost :: Posting -> [PriceDirective]

-- | Get the commodity symbols used in a posting's amounts (not including
--   costs).
postingCommodities :: Posting -> [CommoditySymbol]
tests_Posting :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Data.Posting.AmountCols
instance GHC.Internal.Classes.Eq Hledger.Data.Posting.PostingLayout
instance GHC.Internal.Classes.Eq Hledger.Data.Posting.PostingWidths
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.BalanceAssertion
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Posting
instance GHC.Internal.Show.Show Hledger.Data.Posting.AmountCols
instance GHC.Internal.Show.Show Hledger.Data.Posting.PostingLayout
instance GHC.Internal.Show.Show Hledger.Data.Posting.PostingWidths


-- | A <a>Transaction</a> represents a movement of some commodity(ies)
--   between two or more accounts. It consists of multiple account
--   <a>Posting</a>s which balance to zero, a date, and optional extras
--   like description, cleared status, and tags.
module Hledger.Data.Transaction
nulltransaction :: Transaction

-- | Make a simple transaction with the given date and postings.
transaction :: Day -> [Posting] -> Transaction

-- | Ensure a transaction's postings refer back to it, so that eg
--   relatedPostings works right.
txnTieKnot :: Transaction -> Transaction

-- | Ensure a transaction's postings do not refer back to it, so that eg
--   recursiveSize and GHCI's :sprint work right.
txnUntieKnot :: Transaction -> Transaction
hasRealPostings :: Transaction -> Bool
realPostings :: Transaction -> [Posting]
assignmentPostings :: Transaction -> [Posting]
virtualPostings :: Transaction -> [Posting]
balancedVirtualPostings :: Transaction -> [Posting]
transactionsPostings :: [Transaction] -> [Posting]

-- | Apply a transform function to this transaction's amounts.
transactionTransformPostings :: (Posting -> Posting) -> Transaction -> Transaction

-- | Apply a specified valuation to this transaction's amounts, using the
--   provided price oracle, commodity styles, and reference dates. See
--   amountApplyValuation.
transactionApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Transaction -> Transaction

-- | Maybe convert this <a>Transaction</a>s amounts to cost.
transactionToCost :: ConversionOp -> Transaction -> Transaction

-- | For any costs in this <a>Transaction</a> which don't have associated
--   equity conversion postings, generate and add those. Generated amounts
--   are rounded to the transaction's local display precision to avoid
--   arithmetic artifacts (e.g. 9.216 * 1801.215277778 = 16600.000000002
--   -&gt; 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

-- | Find, associate, and tag the corresponding equity conversion postings
--   and costful or potentially costful postings in this transaction. With
--   a true addcosts argument, also generate and add any equivalent costs
--   that are missing. The (previously detected) names of all equity
--   conversion accounts should be provided.
--   
--   For every pair of adjacent conversion postings, this first searches
--   for a posting with equivalent cost (1). If no such posting is found,
--   it then searches the costless postings, for one matching one of the
--   conversion amounts (2). If either of these found a candidate posting,
--   it is tagged with costPostingTagName. Then if in addcosts mode, if a
--   costless posting was found, a cost equivalent to the conversion
--   amounts is added to it.
--   
--   The name reflects the complexity of this and its helpers;
--   clarification is ongoing.
transactionTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> [AccountName] -> Transaction -> Either String Transaction

-- | Apply some account aliases to all posting account names in the
--   transaction, as described by accountNameApplyAliases. This can fail
--   due to a bad replacement pattern in a regular expression alias.
transactionApplyAliases :: [AccountAlias] -> Transaction -> Either RegexError Transaction

-- | Apply a transformation to a transaction's postings.
transactionMapPostings :: (Posting -> Posting) -> Transaction -> Transaction

-- | Apply a transformation to a transaction's posting amounts.
transactionMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Transaction -> Transaction

-- | All posting amounts from this transaction, in order.
transactionAmounts :: Transaction -> [MixedAmount]

-- | 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 -> Map CommoditySymbol AmountStyle

-- | Like transactionCommodityStyles, but attach a particular rounding
--   strategy to the styles, affecting how they will affect display
--   precisions when applied.
transactionCommodityStylesWith :: Rounding -> Transaction -> Map CommoditySymbol AmountStyle

-- | Flip the sign of this transaction's posting amounts (and balance
--   assertion amounts).
transactionNegate :: Transaction -> Transaction
partitionAndCheckConversionPostings :: Bool -> [AccountName] -> [IdxPosting] -> Either Text ([(IdxPosting, IdxPosting)], ([IdxPosting], [IdxPosting]))

-- | Add tags to a transaction, discarding any for which it already has a
--   value. Note this does not add tags to the transaction's comment.
transactionAddTags :: Transaction -> [Tag] -> Transaction

-- | Add the given hidden tag to a transaction; and with a true argument,
--   also add the equivalent visible tag to the transaction's tags and
--   comment fields. If the transaction already has these tags (with any
--   value), do nothing.
transactionAddHiddenAndMaybeVisibleTag :: Bool -> HiddenTag -> Transaction -> Transaction

-- | 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

-- | Legacy behaviour, as in hledger &lt;1.50, included to ease upgrades.
--   use precision inferred from the whole journal, overridable by
--   commodity directive or -c. Display precision is also transaction
--   balancing precision; increasing it can break journal reading. Some
--   valid journals are rejected until commodity directives are added.
--   Larger imbalances can be hidden, and in accounts that are never
--   reconciled, can accumulate over time.
TBPDisplay :: TransactionBalancingPrecision

-- | Simpler, more robust behaviour, like Ledger: use precision inferred
--   from the transaction's journal entry. Display precision and
--   transaction balancing precision are independent; display precision
--   never affects journal reading. Valid journals from ledger or beancount
--   are accepted without needing commodity directives. Imbalances smaller
--   than the entry's precision are still tolerated, and can accumulate.
TBPEntry :: TransactionBalancingPrecision

-- | Parse a transaction's description into payee and note (aka narration)
--   fields, assuming a convention of separating these with | (like
--   Beancount). Ie, everything up to the first | is the payee, everything
--   after it is the note. When there's no |, payee == note == description.
payeeAndNoteFromDescription :: Text -> (Text, Text)

-- | Like payeeAndNoteFromDescription, but if there's no | then payee is
--   empty.
payeeAndNoteFromDescription' :: Text -> (Text, Text)
transactionDate2 :: Transaction -> Day
transactionDateOrDate2 :: WhichDate -> Transaction -> Day
transactionPayee :: Transaction -> Text
transactionNote :: Transaction -> Text

-- | Render a journal transaction as text similar to the style of Ledger's
--   print command.
--   
--   Adapted from Ledger 2.x and 3.x standard format:
--   
--   <pre>
--   yyyy-mm-dd[ *][ CODE] description.........          [  ; comment...............]
--       account name 1.....................  ...$amount1[  ; comment...............]
--       account name 2.....................  ..$-amount1[  ; comment...............]
--   
--   pcodewidth    = no limit -- 10          -- mimicking ledger layout.
--   pdescwidth    = no limit -- 20          -- I don't remember what these mean,
--   pacctwidth    = 35 minimum, no maximum  -- they were important at the time.
--   pamtwidth     = 11
--   pcommentwidth = no limit -- 22
--   </pre>
--   
--   The output will be parseable journal syntax. To facilitate this,
--   postings with explicit multi-commodity amounts are displayed as
--   multiple similar postings, one per commodity. (Normally does not
--   happen with this function).
showTransaction :: Transaction -> Text

-- | Like <a>showTransaction</a>, but with an explicit posting layout (e.g.
--   to support <tt>print --layout=hledger1</tt>).
showTransactionWithLayout :: PostingLayout -> Transaction -> Text

-- | 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

-- | 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
--   <a>showTransactionOneLineAmounts</a>, which shows the whole
--   transaction but with multi-commodity amounts on one line.)
showTransactionOneLine :: Transaction -> Text
showTransactionLineFirstPart :: Transaction -> Text

-- | The file path from which this transaction was parsed.
transactionFile :: Transaction -> FilePath
annotateErrorWithTransaction :: Transaction -> String -> String
tests_Transaction :: TestTree
instance GHC.Internal.Enum.Bounded Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Enum.Enum Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Classes.Eq Hledger.Data.Transaction.TransactionBalancingPrecision
instance Hledger.Data.Types.HasAmounts Hledger.Data.Types.Transaction
instance GHC.Internal.Classes.Ord Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Read.Read Hledger.Data.Transaction.TransactionBalancingPrecision
instance GHC.Internal.Show.Show Hledger.Data.Transaction.TransactionBalancingPrecision


-- | Helpers for Ledger-compatible output.
module Hledger.Write.Ledger

-- | Like showTransaction, but renders cost basis using Ledger-style lot
--   syntax ({COST} <a>DATE</a>) instead of hledger consolidated syntax.
showTransactionLedger :: Transaction -> Text

-- | 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


-- | A general query system for matching things (accounts, postings,
--   transactions..) by various criteria, and a SimpleTextParser for query
--   expressions.
module Hledger.Query

-- | A query is a composition of search criteria, which can be used to
--   match postings, transactions, accounts and more.
data Query

-- | always match
Any :: Query

-- | never match data queries (in "standard" order, roughly as they appear
--   in a transaction)
None :: Query

-- | match primary dates in this date span
Date :: DateSpan -> Query

-- | match secondary dates in this date span
Date2 :: DateSpan -> Query

-- | match this txn/posting status
StatusQ :: Status -> Query

-- | match txn codes infix-matched by this regexp
Code :: Regexp -> Query

-- | match txn descriptions infix-matched by this regexp
Desc :: Regexp -> Query

-- | match if a tag's name, and optionally its value, is infix-matched by
--   the respective regexps
Tag :: Regexp -> Maybe Regexp -> Query

-- | match account names infix-matched by this regexp
Acct :: Regexp -> Query

-- | match accounts whose type is one of these (or with no types, any
--   account)
Type :: [AccountType] -> Query

-- | match if account depth is less than or equal to this value (or,
--   sometimes used as a display option)
Depth :: Int -> Query

-- | match if the account matches and account depth is less than or equal
--   to this value (usually used as a display option)
DepthAcct :: Regexp -> Int -> Query

-- | match postings with this "realness" value
Real :: Bool -> Query

-- | match if the amount's numeric quantity is less than<i>greater
--   than</i>equal to/unsignedly equal to some value, considering just
--   amounts in this commodity if one is given
Amt :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query

-- | match if the commodity symbol is fully matched by this regexp.
Cur :: Regexp -> Query

-- | 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 <a>querySplitRowTerms</a>).
Change :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query

-- | 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 <a>querySplitRowTerms</a>).
Balance :: OrdPlus -> Quantity -> Maybe CommoditySymbol -> Query

-- | 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:)
Find :: Regexp -> Maybe DateSpan -> Query

-- | negate this match
Not :: Query -> Query

-- | match if all of these match
And :: [Query] -> Query

-- | match if any of these match compound queries selecting whole
--   transactions (any:, all:). When matching a posting, these look at the
--   postings of its parent transaction, so a posting can be matched
--   because of its siblings. In contexts with neither a transaction nor
--   sibling postings available (matching an account name, a commodity
--   symbol...), they are equivalent to And.
Or :: [Query] -> Query

-- | match if any one posting is matched by all of these
AnyPosting :: [Query] -> Query

-- | match if all of one or more postings are matched by all of these
AllPostings :: [Query] -> Query

-- | A query option changes a query's/report's behaviour and output in some
--   way.
data QueryOpt

-- | show an account register focussed on this account
QueryOptInAcctOnly :: AccountName -> QueryOpt

-- | as above but include sub-accounts in the account register
QueryOptInAcct :: AccountName -> QueryOpt

-- | report interval extracted from a date: query | QueryOptCostBasis -- ^
--   show amounts converted to cost where possible | QueryOptDate2 -- ^
--   show secondary dates instead of primary dates
QueryOptInterval :: Interval -> QueryOpt

-- | 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 :: OrdPlus
LtEq :: OrdPlus
Gt :: OrdPlus
GtEq :: OrdPlus
Eq :: OrdPlus
AbsLt :: OrdPlus
AbsLtEq :: OrdPlus
AbsGt :: OrdPlus
AbsGtEq :: OrdPlus
AbsEq :: OrdPlus

-- | Construct a query for the payee: tag
payeeTag :: Maybe Text -> Either RegexError Query

-- | Construct a query for the note: tag
noteTag :: Maybe Text -> Either RegexError Query

-- | Construct a query for the generated-transaction: tag
generatedTransactionTag :: Query

-- | A version of parseQueryList which acts on a single Text of
--   space-separated terms.
--   
--   The usual shell quoting rules are assumed. When a pattern contains
--   whitespace, it (or the whole term including prefix) should be enclosed
--   in single or double quotes.
--   
--   A query term is either:
--   
--   <ol>
--   <li>a search pattern, which matches on one or more fields,
--   eg:acct:REGEXP - match the account name with a regular expression
--   desc:REGEXP - match the transaction description date:PERIODEXP - match
--   the date with a period expression</li>
--   </ol>
--   
--   The prefix indicates the field to match, or if there is no prefix
--   account name is assumed.
--   
--   <ol>
--   <li>a query option, which modifies the reporting behaviour in some
--   way. There is currently one of these, which may appear only
--   once:inacct:FULLACCTNAME</li>
--   </ol>
--   
--   Period expressions may contain relative dates, so a reference date is
--   required to fully parse these.
--   
--   <pre>
--   &gt;&gt;&gt; parseQuery nulldate "expenses:dining out"
--   Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseQuery nulldate "\"expenses:dining out\""
--   Right (Acct (RegexpCI "expenses:dining out"),[])
--   </pre>
parseQuery :: Day -> Text -> Either String (Query, [QueryOpt])

-- | Convert a list of space-separated queries to a single query
--   
--   Multiple terms are combined as follows: 1. multiple account patterns
--   are OR'd together 2. multiple description patterns are OR'd together
--   3. multiple status patterns are OR'd together 4. then all terms are
--   AND'd together
parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt])

-- | Parse a single query term as either a query or a query option, or
--   return an error message if parsing fails.
parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt])

-- | 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
parseDepthSpec :: Text -> Either RegexError DepthSpec

-- | Parse the argument of an amt:, change: or balance: query term: a
--   comparison ([OP][SIGN]NUM, see <a>parseAmountQueryTerm</a>),
--   optionally with a commodity symbol before or after the number (and its
--   sign), as in <tt>&gt;$100</tt>, <tt>&gt;-$100</tt>, <tt>&gt;100
--   EUR</tt> or <tt>&gt;"AAPL 2026" 5</tt>. Returns an OrdPlus, a Quantity
--   and the commodity symbol if any, or if parsing fails, an error message
--   mentioning the given query type.
--   
--   <pre>
--   &gt;&gt;&gt; parseAmountQueryArg "amt" "&gt;100"
--   Right (AbsGt,100,Nothing)
--   
--   &gt;&gt;&gt; parseAmountQueryArg "amt" "&lt;-$100"
--   Right (Lt,-100,Just "$")
--   
--   &gt;&gt;&gt; parseAmountQueryArg "change" "&gt;= 100 EUR"
--   Right (AbsGtEq,100,Just "EUR")
--   
--   &gt;&gt;&gt; parseAmountQueryArg "change" "\"AAPL 2026\"+5"
--   Right (Eq,5,Just "AAPL 2026")
--   </pre>
parseAmountQueryArg :: String -> Text -> Either String (OrdPlus, Quantity, Maybe CommoditySymbol)

-- | 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
simplifyQuery :: Query -> Query

-- | Remove query terms (or whole sub-expressions) from this query which do
--   not match the given predicate. XXX Semantics not completely clear.
--   Also calls simplifyQuery on the result.
filterQuery :: (Query -> Bool) -> Query -> Query

-- | Remove query terms (or whole sub-expressions) from this query which
--   match neither the given predicate nor that predicate negated (eg, if
--   predicate is queryIsAcct, this will keep both "acct:" and "not:acct:"
--   terms). Also calls simplifyQuery on the result. (Since 1.24.1, might
--   be merged into filterQuery in future.) XXX Semantics not completely
--   clear.
filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query

-- | 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.
--   
--   <pre>
--   &gt;&gt;&gt; querySplitRowTerms (And [Acct (toRegexCI' "a"), Not (Change AbsGt 1 Nothing)])
--   Right (Not (Change AbsGt 1 Nothing),Acct (RegexpCI "a"))
--   </pre>
querySplitRowTerms :: Query -> Either String (Query, Query)

-- | Does this simple query predicate match any part of this possibly
--   compound query ?
matchesQuery :: (Query -> Bool) -> Query -> Bool

-- | Does this query match everything ?
queryIsNull :: Query -> Bool

-- | Is this a simple query of this type (date:) ? Does not match a
--   compound query involving and<i>or</i>not. Likewise for the following
--   functions.
queryIsDate :: Query -> Bool
queryIsDate2 :: Query -> Bool
queryIsDateOrDate2 :: Query -> Bool
queryIsStatus :: Query -> Bool
queryIsCode :: Query -> Bool
queryIsDesc :: Query -> Bool
queryIsTag :: Query -> Bool
queryIsAcct :: Query -> Bool
queryIsFind :: Query -> Bool
queryIsType :: Query -> Bool
queryIsDepth :: Query -> Bool

-- | Is this a flat depth limit (depth:N), applying to all accounts, rather
--   than a per-account one (depth:REGEX=N) ?
queryIsFlatDepth :: Query -> Bool
queryIsReal :: Query -> Bool
queryIsAmt :: Query -> Bool
queryIsCur :: Query -> Bool
queryIsAmtOrCur :: Query -> Bool
queryIsChange :: Query -> Bool
queryIsBalance :: Query -> Bool

-- | Is this a change: or balance: term (a "row term", tested against a
--   report row's summed amounts) ?
queryIsRowTerm :: Query -> Bool

-- | 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

-- | Does this query contain a change: term anywhere (possibly negated) ?
queryHasChange :: Query -> Bool

-- | Does this query specify a start date and nothing else (that would
--   filter postings prior to the date) ? When the flag is true, look for a
--   starting secondary date instead.
queryIsStartDateOnly :: Bool -> Query -> Bool

-- | Does this query involve a property of transactions (or their
--   postings), making it inapplicable to account declarations ?
queryIsTransactionRelated :: Query -> Bool

-- | What start date (or secondary date) does this query specify, if any ?
--   For OR expressions, use the earliest of the dates. NOT is ignored.
queryStartDate :: Bool -> Query -> Maybe Day

-- | What end date (or secondary date) does this query specify, if any ?
--   For OR expressions, use the latest of the dates. NOT is ignored.
queryEndDate :: Bool -> Query -> Maybe Day

-- | What date span (or with a true argument, what secondary date span)
--   does this query specify ? OR clauses specifying multiple spans return
--   their union (the span enclosing all of them). AND clauses specifying
--   multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan :: Bool -> Query -> DateSpan

-- | What date span does this query specify, treating primary and secondary
--   dates as equivalent ? OR clauses specifying multiple spans return
--   their union (the span enclosing all of them). AND clauses specifying
--   multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan' :: Query -> DateSpan

-- | The depth limit this query specifies, if it has one
queryDepth :: Query -> DepthSpec

-- | The account we are currently focussed on, if any, and whether
--   subaccounts are included. Just looks at the first query option.
inAccount :: [QueryOpt] -> Maybe (AccountName, Bool)

-- | A query for the account(s) we are currently focussed on, if any. Just
--   looks at the first query option.
inAccountQuery :: [QueryOpt] -> Maybe Query

-- | 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

-- | 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

-- | 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

-- | 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

-- | 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

-- | 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 <a>matchesPostingExtra</a> 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, <tt>matchesPostingExtra
--   atype (postingQueryForAccount atype a morig q) p ==
--   matchesPostingExtra atype q p</tt>. This lets the account terms be
--   tested once per account, rather than once per posting; checking assert
--   rules uses it this way (see <a>Hledger.Data.JournalChecks.Assert</a>).
postingQueryForAccount :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe AccountName -> Query -> Query

-- | Does the query match this account name ? Only acct: and depth: terms
--   can match; any other term (a date:, desc: etc.) fails to match, since
--   an account name on its own has no such properties. (For matching type:
--   and tag: terms against an account's other data, see
--   matchesAccountExtra.)
matchesAccount :: Query -> AccountName -> Bool

-- | Like matchesAccount, but with optional extra matching features:
--   
--   <ul>
--   <li>If the account's type is provided, any type: terms in the query
--   must match it (and any negated type: terms must not match it).</li>
--   <li>If the account's tags are provided, any tag: terms must match at
--   least one of them (and any negated tag: terms must match none).</li>
--   </ul>
matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool

-- | 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

-- | Does the match expression match this (simple) amount ?
matchesAmount :: Query -> Amount -> Bool

-- | 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 <a>matchesMixedAmount</a>): 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
matchesCommodity :: Query -> CommoditySymbol -> Bool

-- | Like matchesCommodity, but also supporting Tag queries, using the
--   provided function to look up a commodity's tags.
matchesCommodityExtra :: (CommoditySymbol -> [Tag]) -> Query -> CommoditySymbol -> Bool

-- | Does the query match the name and optionally the value of this tag ?
--   Non-tag: query terms are ignored (this might disrupt some boolean
--   queries).
matchesTag :: Query -> Tag -> Bool

-- | Does the query match this market price ?
matchesPriceDirective :: Query -> PriceDirective -> Bool

-- | Quote-and-prefix-aware version of words - don't split on spaces which
--   are inside quotes, including quotes which may have one of the
--   specified prefixes in front, and maybe an additional not: prefix in
--   front of that.
words'' :: [Text] -> Text -> [Text]
queryprefixes :: [Text]
tests_Query :: TestTree
instance Data.Default.Internal.Default Hledger.Query.Query
instance GHC.Internal.Classes.Eq Hledger.Query.OrdPlus
instance GHC.Internal.Classes.Eq Hledger.Query.Query
instance GHC.Internal.Classes.Eq Hledger.Query.QueryOpt
instance GHC.Internal.Show.Show Hledger.Query.OrdPlus
instance GHC.Internal.Show.Show Hledger.Query.Query
instance GHC.Internal.Show.Show Hledger.Query.QueryOpt


-- | A <a>TransactionModifier</a> is a rule that modifies certain
--   <a>Transaction</a>s, typically adding automated postings to them.
module Hledger.Data.TransactionModifier

-- | Apply all the given transaction modifiers, in turn, to each
--   transaction. Or if any of them fails to be parsed, return the first
--   error. A reference date is provided to help interpret relative dates
--   in transaction modifier queries.
modifyTransactions :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Map CommoditySymbol AmountStyle -> Day -> Bool -> [TransactionModifier] -> [Transaction] -> Either String [Transaction]


-- | A <a>TimeclockEntry</a> is a clock-in, clock-out, or other directive
--   in a timeclock file (see timeclock.el or the command-line version).
--   These can be converted to <tt>Transactions</tt> and queried like a
--   ledger.
module Hledger.Data.Timeclock

-- | Convert timeclock entries to journal transactions. This is the new,
--   default version added in hledger 1.43 and improved in 1.50. It allows
--   concurrent clocked-in sessions (though not with the same account
--   name), and clock-in/clock-out entries in any order.
--   
--   Entries are processed in parse order. Sessions crossing midnight are
--   split into days to give accurate per-day totals. At the end, any
--   sessions with no clockout get an implicit clockout with the provided
--   "now" time. If any entries cannot be paired as expected, an error is
--   raised.
timeclockToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]

-- | Convert timeclock entries to journal transactions. This is the old
--   version from hledger &lt;1.43, now enabled by --old-timeclock. It
--   requires strictly alternating clock-in and clock-entries. It was
--   documented as allowing only one clocked-in session at a time, but in
--   fact it allows concurrent sessions, even with the same account name.
--   
--   Entries must be a strict alternation of in and out, beginning with in.
--   When there is no clockout, one is added with the provided current
--   time. Sessions crossing midnight are split into days to give accurate
--   per-day totals. If entries are not in the expected in/out order, an
--   error is raised.
timeclockToTransactionsOld :: LocalTime -> [TimeclockEntry] -> [Transaction]
tests_Timeclock :: TestTree
instance GHC.Internal.Read.Read Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Show.Show Hledger.Data.Timeclock.Session
instance GHC.Internal.Show.Show Hledger.Data.Timeclock.Sessions
instance GHC.Internal.Show.Show Hledger.Data.Types.TimeclockCode
instance GHC.Internal.Show.Show Hledger.Data.Types.TimeclockEntry


-- | Data values for zero or more report periods, and for the pre-report
--   period. Report periods are assumed to be contiguous, and represented
--   only by start dates (as keys of an IntMap).
module Hledger.Data.PeriodData

-- | Construct a <a>PeriodData</a> from a historical data value and a list
--   of (period start, period data) pairs.
periodDataFromList :: a -> [(Day, a)] -> PeriodData a

-- | Convert <a>PeriodData</a> to a historical data value and a list of
--   (period start, period data) pairs.
periodDataToList :: PeriodData a -> (a, [(Day, a)])

-- | Get the data for the period containing the given <a>Day</a>, and that
--   period's start date. If the day is after the end of the last period,
--   it is assumed to be within the last period. If the day is before the
--   start of the first period (ie, in the historical period), return
--   Nothing.
lookupPeriodData :: Day -> PeriodData a -> Maybe (Day, a)

-- | Get the data for the period containing the given <a>Day</a>, and that
--   period's start date. If the day is after the end of the last period,
--   it is assumed to be within the last period. If the day is before the
--   start of the first period (ie, in the historical period), return the
--   data for the historical period and no start date.
lookupPeriodDataOrHistorical :: Day -> PeriodData a -> (Maybe Day, a)

-- | Set historical or period data in the appropriate location in a
--   <a>PeriodData</a>.
insertPeriodData :: Semigroup a => Maybe Day -> a -> PeriodData a -> PeriodData a

-- | Merge two <a>PeriodData</a>, using the given operation to combine
--   their data values.
--   
--   This will drop keys if they are not present in both <a>PeriodData</a>.
opPeriodData :: (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c

-- | Merge two <a>PeriodData</a>, using the given operations for combining
--   data that's only in the first, only in the second, or in both,
--   respectively.
mergePeriodData :: (a -> c) -> (b -> c) -> (a -> b -> c) -> PeriodData a -> PeriodData b -> PeriodData c

-- | Pad out the date map of a <a>PeriodData</a> so that every key from
--   another <a>PeriodData</a> is present.
padPeriodData :: a -> PeriodData b -> PeriodData a -> PeriodData a
tests_PeriodData :: TestTree
instance Data.Foldable1.Foldable1 Hledger.Data.Types.PeriodData
instance GHC.Internal.Data.Foldable.Foldable Hledger.Data.Types.PeriodData
instance GHC.Internal.Base.Monoid a => GHC.Internal.Base.Monoid (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Base.Semigroup a => GHC.Internal.Base.Semigroup (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Types.PeriodData a)
instance GHC.Internal.Data.Traversable.Traversable Hledger.Data.Types.PeriodData


-- | A partition of time into contiguous spans, for defining reporting
--   periods.
module Hledger.Data.DayPartition

-- | A partition of time into one or more contiguous periods, plus a
--   historical period that precedes them. Note <a>DayPartition</a> does
--   not store per-period data - only the periods' start/end dates.
data DayPartition

-- | Construct a <a>DayPartition</a> from a non-empty list of period
--   boundary dates (start dates plus a final exclusive end date).
--   
--   <pre>
--   &gt;&gt;&gt; boundariesToDayPartition (fromGregorian 2025 01 01 :| [fromGregorian 2025 02 01])
--   DayPartition {dayPartitionToPeriodData = PeriodData{ pdpre = 2024-12-31, pdperiods = fromList [(2025-01-01,2025-01-31)]}}
--   </pre>
boundariesToDayPartition :: NonEmpty Day -> DayPartition

-- | Construct a <a>DayPartition</a> from a list of period boundary dates
--   (start dates plus a final exclusive end date), if it's a non-empty
--   list.
boundariesToMaybeDayPartition :: [Day] -> Maybe DayPartition

-- | Convert <a>DayPartition</a> to a non-empty list of period start and
--   end dates (both inclusive). Each end date will be one day before the
--   next period's start date.
dayPartitionToNonEmpty :: DayPartition -> NonEmpty (Day, Day)

-- | Convert <a>DayPartition</a> to a list (which will always be non-empty)
--   of period start and end dates (both inclusive). Each end date will be
--   one day before the next period's start date.
dayPartitionToList :: DayPartition -> [(Day, Day)]

-- | Convert <a>DayPartition</a> to a list of <a>DateSpan</a>s. Each span
--   will end one day before the next span begins (the span's exclusive end
--   date will be equal to the next span's start date).
dayPartitionToDateSpans :: DayPartition -> [DateSpan]
dayPartitionToPeriodData :: DayPartition -> PeriodData Day
maybeDayPartitionToDateSpans :: Maybe DayPartition -> [DateSpan]

-- | Return the union of two <a>DayPartition</a>s if that is a valid
--   <a>DayPartition</a>, or <a>Nothing</a> otherwise.
unionDayPartitions :: DayPartition -> DayPartition -> Maybe DayPartition

-- | Get this DayPartition's overall start date and end date (both
--   inclusive).
dayPartitionStartEnd :: DayPartition -> (Day, Day)

-- | Find the start and end dates of the period within a
--   <a>DayPartition</a> which contains a given day. If the day is after
--   the end of the last period, it is assumed to be within the last
--   period. If the day is before the start of the first period (ie, in the
--   historical period), only the historical period's end date is returned.
dayPartitionFind :: Day -> DayPartition -> (Maybe Day, Day)

-- | Split a <a>DateSpan</a> into a <a>DayPartition</a> consisting of
--   consecutive exact spans of the specified Interval, or <a>Nothing</a>
--   if the span is invalid. If no interval is specified, the original span
--   is returned. If the original span is the null date span, ie unbounded,
--   <a>Nothing</a> is returned. If the original span is empty, eg if the
--   end date is &lt;= the start date, <a>Nothing</a> is returned.
--   
--   <h4>Date adjustment</h4>
--   
--   Some intervals respect the "adjust" flag (years, quarters, months,
--   weeks, every Nth weekday of month seem to be the ones that need it).
--   This will move the start date earlier, if needed, to the previous
--   natural interval boundary (first of year, first of quarter, first of
--   month, monday, previous Nth weekday of month). Related: #1982 #2218
--   
--   The end date is always moved later if needed to the next natural
--   interval boundary, so that the last period is the same length as the
--   others.
--   
--   <h4>Examples</h4>
--   
--   <pre>
--   &gt;&gt;&gt; let t i y1 m1 d1 y2 m2 d2 = fmap dayPartitionToNonEmpty . splitSpan True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)
--   
--   &gt;&gt;&gt; t NoInterval 2008 01 01 2009 01 01
--   Just ((2008-01-01,2008-12-31) :| [])
--   
--   &gt;&gt;&gt; t (Quarters 1) 2008 01 01 2009 01 01
--   Just ((2008-01-01,2008-03-31) :| [(2008-04-01,2008-06-30),(2008-07-01,2008-09-30),(2008-10-01,2008-12-31)])
--   
--   &gt;&gt;&gt; splitSpan True (Quarters 1) nulldatespan
--   Nothing
--   
--   &gt;&gt;&gt; t (Days 1) 2008 01 01 2008 01 01  -- an empty datespan
--   Nothing
--   
--   &gt;&gt;&gt; t (Quarters 1) 2008 01 01 2008 01 01
--   Nothing
--   
--   &gt;&gt;&gt; t (Months 1) 2008 01 01 2008 04 01
--   Just ((2008-01-01,2008-01-31) :| [(2008-02-01,2008-02-29),(2008-03-01,2008-03-31)])
--   
--   &gt;&gt;&gt; t (Months 2) 2008 01 01 2008 04 01
--   Just ((2008-01-01,2008-02-29) :| [(2008-03-01,2008-04-30)])
--   
--   &gt;&gt;&gt; t (Weeks 1) 2008 01 01 2008 01 15
--   Just ((2007-12-31,2008-01-06) :| [(2008-01-07,2008-01-13),(2008-01-14,2008-01-20)])
--   
--   &gt;&gt;&gt; t (Weeks 2) 2008 01 01 2008 01 15
--   Just ((2007-12-31,2008-01-13) :| [(2008-01-14,2008-01-27)])
--   
--   &gt;&gt;&gt; t (MonthDay 2) 2008 01 01 2008 04 01
--   Just ((2008-01-02,2008-02-01) :| [(2008-02-02,2008-03-01),(2008-03-02,2008-04-01)])
--   
--   &gt;&gt;&gt; t (NthWeekdayOfMonth 2 4) 2011 01 01 2011 02 15
--   Just ((2010-12-09,2011-01-12) :| [(2011-01-13,2011-02-09),(2011-02-10,2011-03-09)])
--   
--   &gt;&gt;&gt; t (DaysOfWeek [2]) 2011 01 01 2011 01 15
--   Just ((2010-12-28,2011-01-03) :| [(2011-01-04,2011-01-10),(2011-01-11,2011-01-17)])
--   
--   &gt;&gt;&gt; t (MonthAndDay 11 29) 2012 10 01 2013 10 15
--   Just ((2012-11-29,2013-11-28) :| [])
--   </pre>
splitSpan :: Bool -> Interval -> DateSpan -> Maybe DayPartition

-- | Like <a>splitSpan</a>, but returns the periods as a lazily generated
--   list of <a>DateSpan</a>s (each ending where the next begins), without
--   building a <a>DayPartition</a>. 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
--   <a>splitSpan</a> would return Nothing.
--   
--   <pre>
--   &gt;&gt;&gt; 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)
--   
--   &gt;&gt;&gt; t (Months 1) 2008 01 01 2008 04 01
--   [DateSpan 2008-01,DateSpan 2008-02,DateSpan 2008-03]
--   
--   &gt;&gt;&gt; t (Days 1) 2008 01 01 2008 01 01
--   []
--   </pre>
splitSpanToDateSpans :: Bool -> Interval -> DateSpan -> [DateSpan]

-- | The start date and exclusive end date of the periods <a>splitSpan</a>
--   would produce (ie the first boundary, and the first boundary not
--   before the span's end), found in constant memory. Nothing if
--   <a>splitSpan</a> would return Nothing.
splitSpanStartEnd :: Bool -> Interval -> DateSpan -> Maybe (Day, Day)

-- | Get the natural start for the given interval that falls on or before
--   the given day, when applicable. Works for Weeks, Months, Quarters,
--   Years, eg.
intervalBoundaryBefore :: Interval -> Day -> Day
tests_DayPartition :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Data.DayPartition.DayPartition
instance GHC.Internal.Classes.Ord Hledger.Data.DayPartition.DayPartition
instance GHC.Internal.Show.Show Hledger.Data.DayPartition.DayPartition


-- | A <a>PeriodicTransaction</a> is a rule describing recurring
--   transactions.
module Hledger.Data.PeriodicTransaction

-- | Generate transactions from <a>PeriodicTransaction</a> within a
--   <a>DateSpan</a>. This should be a closed span with both start and end
--   dates specified; an open ended span will generate no transactions.
--   
--   Note that new transactions require <a>txnTieKnot</a> post-processing.
--   The new transactions will have three tags added: - a
--   recur:PERIODICEXPR tag whose value is the generating periodic
--   expression - a generated-transaction: tag - a hidden
--   _generated-transaction: tag which does not appear in the comment.
--   
--   <pre>
--   &gt;&gt;&gt; import Data.Time (fromGregorian)
--   
--   &gt;&gt;&gt; _ptgen "monthly from 2017/1 to 2017/4"
--   2017-01-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a                                             $1.00
--   
--   2017-02-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a                                             $1.00
--   
--   2017-03-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _ptgen "monthly from 2017/1 to 2017/5"
--   2017-01-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a                                             $1.00
--   
--   2017-02-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a                                             $1.00
--   
--   2017-03-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a                                             $1.00
--   
--   2017-04-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/5
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _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
--   
--   2017-03-02
--       ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _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
--   
--   2017-02-28
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a                                             $1.00
--   
--   2017-03-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a                                             $1.00
--   
--   2017-04-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _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
--   
--   2017-02-09
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a                                             $1.00
--   
--   2017-03-09
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _ptgen "every nov 29th from 2017 to 2019"
--   2017-11-29
--       ; generated-transaction: ~ every nov 29th from 2017 to 2019
--       a                                             $1.00
--   
--   2018-11-29
--       ; generated-transaction: ~ every nov 29th from 2017 to 2019
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _ptgen "2017/1"
--   2017-01-01
--       ; generated-transaction: ~ 2017/1
--       a                                             $1.00
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; 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))
--   []
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 01 01) (Just $ Flex $ fromGregorian 2020 02 01))
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; _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
--   
--   
--   &gt;&gt;&gt; _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
--   
--   2018-01-04
--       ; generated-transaction: ~ every 3 days from 2018
--       a                                             $1.00
--   
--   
--   &gt;&gt;&gt; _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
--   </pre>
runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]

-- | 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]

-- | Check that this date span begins at a boundary of this interval, or
--   return an explanatory error message including the provided period
--   expression (from which the span and interval are derived).
checkPeriodicTransactionStartDate :: Interval -> DateSpan -> Text -> Maybe String
instance GHC.Internal.Show.Show Hledger.Data.Types.PeriodicTransaction

module Hledger.Data.Json

-- | Show a JSON-convertible haskell value as pretty-printed JSON text.
toJsonText :: ToJSON a => a -> Text

-- | Write a JSON-convertible haskell value to a pretty-printed JSON file.
--   Eg: writeJsonFile "a.json" nulltransaction
writeJsonFile :: ToJSON a => FilePath -> a -> IO ()

-- | Read a JSON file and decode it to the target type, or raise an error
--   if we can't. Eg: readJsonFile "a.json" :: IO Transaction
readJsonFile :: FromJSON a => FilePath -> IO a
instance Data.Aeson.Types.FromJSON.FromJSON a => Data.Aeson.Types.FromJSON.FromJSON (Hledger.Data.Types.Account a)
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountCost
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.BalanceData
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.CostBasis
instance Data.Aeson.Types.FromJSON.FromJSON (Data.Decimal.DecimalRaw GHC.Internal.Bignum.Integer.Integer)
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.FromJSON.FromJSON a => Data.Aeson.Types.FromJSON.FromJSON (Hledger.Data.Types.PeriodData a)
instance Data.Aeson.Types.FromJSON.FromJSON Text.Megaparsec.Pos.Pos
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.PostingRealness
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Rounding
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.FromJSON.FromJSON Text.Megaparsec.Pos.SourcePos
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.ToJSON.ToJSONKey Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Data.Types.Account a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountAlias
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountCost
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.BalanceData
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Commodity
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.CostBasis
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DateSpan
instance (GHC.Internal.Real.Integral a, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Data.Decimal.DecimalRaw a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.EFDay
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Interval
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Journal
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.JournalFile
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Ledger
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PayeeDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Period
instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Data.Types.PeriodData a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PeriodicTransaction
instance Data.Aeson.Types.ToJSON.ToJSON Text.Megaparsec.Pos.Pos
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PostingRealness
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PriceDirective
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Rounding
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.ToJSON.ToJSON Text.Megaparsec.Pos.SourcePos
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TMPostingRule
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TagDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TimeclockCode
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TimeclockEntry
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TransactionModifier


-- | A renderer-independent description of a chart, made from a report.
--   
--   This is to charts what <a>Hledger.Write.Spreadsheet</a> is to tables:
--   each chart-capable report has an adapter that turns its report data
--   into a <a>Chart</a>, choosing a useful default chart for that report
--   (see doc/SPEC-charts.md, "Smart defaults"), and renderers turn a
--   <a>Chart</a> 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<i>is</i>cf).
--   
--   Values are kept exact here (<a>Quantity</a>); renderers convert them
--   to Double only for drawing.
module Hledger.Write.Chart

-- | 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 :: Text -> XAxis -> [Panel] -> [Text] -> Chart

-- | the report's title, as its table would show it (may be empty)
[chTitle] :: Chart -> Text

-- | the x positions, shared by all panels
[chXAxis] :: Chart -> XAxis

-- | the panels, in display order (eg largest commodity first)
[chPanels] :: Chart -> [Panel]

-- | notes to show below the chart, eg about what its values leave out
[chNotes] :: Chart -> [Text]

-- | 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

-- | unordered categories, eg the accounts of a single-period balance
--   report
XCategories :: [ChartLabel] -> XAxis

-- | consecutive report periods, each with its heading as the report's
--   table shows it
XPeriods :: [(DateSpan, Text)] -> XAxis

-- | individual dates, possibly irregular and repeated, eg one per
--   transaction in a register
XDates :: [Day] -> XAxis

-- | 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 :: Text -> Text -> Int -> Maybe AccountType -> Bool -> [Text] -> ChartLabel

-- | the full name, eg a full account name; used in CSV/JSON and tooltips
[lbFull] :: ChartLabel -> Text

-- | the name to display, eg a leaf account name in tree mode
[lbShort] :: ChartLabel -> Text

-- | indentation level to display it with (0 for none)
[lbIndent] :: ChartLabel -> Int

-- | the account type, if this names an account (or accounts) of a known
--   type; charts colour accounts by their main type (see
--   <a>seriesColours</a>)
[lbType] :: ChartLabel -> Maybe AccountType

-- | does this name an account (or accounts) ? Otherwise it's something
--   else, eg a total.
[lbAccount] :: ChartLabel -> Bool

-- | more lines for tooltips, eg the accounts that an "other" series
--   combines
[lbTipLines] :: ChartLabel -> [Text]

-- | One chart area with its own y axis, holding series of values in a
--   single unit.
data Panel
Panel :: Amount -> [Series] -> [Text] -> Maybe Quantity -> BarLayout -> Bool -> [Summary] -> [Maybe Text] -> Panel

-- | 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, <tt>%</tt> (as produced
--   by --percent), or no commodity with precision 0 for counts.
[pnUnit] :: Panel -> Amount

-- | the series, in display order (legend order)
[pnSeries] :: Panel -> [Series]

-- | names for the groups of series, by group number (see <a>seGroup</a>),
--   if they have names; eg a compound report's section titles. Text charts
--   show them.
[pnGroupNames] :: Panel -> [Text]

-- | a fixed scale, if one was requested: the amount spanned by the chart
--   (see <a>scaleSpans</a>), so that charts with the same scale are drawn
--   at the same size per amount. Otherwise the chart is scaled to fit its
--   values.
[pnScale] :: Panel -> Maybe Quantity

-- | how to draw bars of several groups
[pnLayout] :: Panel -> BarLayout

-- | 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).
[pnCounts] :: Panel -> Bool

-- | values summarising the whole chart, shown below it (eg with -T and -A,
--   the total and the average per period)
[pnSummary] :: Panel -> [Summary]

-- | 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
[pnValueLabels] :: Panel -> [Maybe Text]

-- | How to draw the bars of a panel whose series are in several groups (eg
--   a compound report's sections).
data BarLayout

-- | all groups stacked in one bar at each x position, positive values
--   above (or right of) zero and negative ones below
Diverging :: BarLayout

-- | 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 <a>setChartLayout</a>)
Grouped :: BarLayout

-- | A named sequence of values, one per x position.
data Series
Series :: ChartLabel -> SeriesRole -> Mark -> [Maybe Quantity] -> Int -> Int -> Series
[seLabel] :: Series -> ChartLabel
[seRole] :: Series -> SeriesRole
[seMark] :: Series -> Mark

-- | 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.
[seValues] :: Series -> [Maybe Quantity]

-- | 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 <a>pnLayout</a> says.
[seGroup] :: Series -> 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.
[seSign] :: Series -> Int

-- | What a series represents, which renderers may show differently (eg a
--   muted colour for <a>SeriesOther</a>).
data SeriesRole

-- | an ordinary series, eg one account
SeriesItem :: SeriesRole

-- | several items combined, eg "other (5 accounts)", to limit the number
--   of series
SeriesOther :: SeriesRole

-- | a total of other series, eg the net total of stacked bars, or net
--   worth
SeriesTotal :: SeriesRole

-- | 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
SeriesShortfall :: SeriesRole

-- | an amount not yet final, eg an unrealised gain or loss: drawn hatched,
--   in its place in the stack
SeriesProvisional :: SeriesRole

-- | How a series is drawn.
data Mark

-- | a bar from zero to the value
MarkBar :: Mark

-- | a line joining the values (in text charts, drawn as bars)
MarkLine :: Mark

-- | a marker at the value, not joined, eg a net total over stacked bars,
--   or a budget goal
MarkMarker :: Mark

-- | not drawn: values shown only as text (text charts' value column,
--   tooltips, chart data), eg holdings' values, which their bars' solid
--   parts reach already
MarkNone :: Mark

-- | A value summarising a panel's values over the whole x axis, such as
--   their total or their average.
data Summary
Summary :: SummaryKind -> Text -> Amount -> Summary
[suKind] :: Summary -> SummaryKind

-- | its name, as the report's table would show it (eg <a>Total</a>,
--   <a>Average</a>)
[suLabel] :: Summary -> Text

-- | its value, with its own display style (eg an average of counts has a
--   decimal place)
[suValue] :: Summary -> Amount
data SummaryKind

-- | the total of all x positions' values
SummaryTotal :: SummaryKind

-- | the average per x position, which SVG charts also draw as a line
--   across the plot (with a legend entry)
SummaryAverage :: SummaryKind

-- | How a series (or a bar) is coloured, in a renderer-independent way.
data Colour

-- | the conventional hue of this main account type, in its Nth tint (to
--   distinguish several of that type)
TypeColour :: AccountType -> Int -> Colour

-- | the Nth categorical colour, for series with no account type
IndexColour :: Int -> Colour

-- | 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
LoneColour :: Colour

-- | a neutral colour, eg for the contra amounts legend swatch
NeutralColour :: Colour

-- | a muted colour, for a series combining several items: grey, tinged
--   with their main account type's hue if any
OtherColour :: Maybe AccountType -> Colour

-- | the ink (text) colour, for a total
TotalColour :: Colour

-- | Colours for a panel's series, in order, for the chart's colouring (see
--   <a>chartColouring</a>). 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 <a>maxTints</a> 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 <a>stableSlots</a>), 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]

-- | 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

-- | in distinct colours chosen by name, to tell them apart: when none has
--   a known type
ByName :: Colouring

-- | 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
ByType :: Colouring

-- | by type, or if unknown in the lone colour: when each panel shows just
--   one account, so there is nothing to tell apart
Single :: Colouring

-- | 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

-- | 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]

-- | Like <a>stableSlots</a>, 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]

-- | 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 <a>seriesColours</a> 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]

-- | A series' size, for ranking: the sum of its absolute values.
seriesSize :: Series -> Quantity

-- | How many tints of a type's colour renderers provide, to distinguish
--   several accounts of one type.
maxTints :: Int

-- | 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

-- | A series' values, indexed by x position, for fast lookup by renderers.
type SeriesValues = Array Int Maybe Quantity

-- | Is this value of the series a contra amount (of the opposite sign to
--   the series' usual sign) ?
isContra :: Series -> Quantity -> Bool

-- | Is this value of the series drawn hatched ? Contra amounts are, and
--   the values of hatched series (see <a>hatchedSeries</a>).
isHatched :: Series -> Quantity -> Bool

-- | Is this series drawn hatched throughout, in its colour (and so shown
--   hatched in legends) ? Shortfalls and provisional amounts are (see
--   <a>SeriesShortfall</a>, <a>SeriesProvisional</a>).
hatchedSeries :: Series -> Bool

-- | 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
seriesValues :: Series -> SeriesValues

-- | The value at this x position, if there is one.
valueAt :: SeriesValues -> Int -> Maybe Quantity

-- | Give each panel a fixed scale (see <a>pnScale</a>): 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

-- | Don't draw the totals (or nets): give each panel's total series no
--   mark (<a>MarkNone</a>), so that it is still shown as values where
--   those are shown (eg in tooltips), but not drawn.
chartWithoutTotalMarks :: Chart -> Chart

-- | 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

-- | 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)

-- | 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 <a>pnSummary</a>) follow
--   its series, with role "rowtotal" or "average", and no mark or x.
chartAsCsv :: Chart -> CSV
tests_Hledger_Write_Chart :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.BarLayout
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Chart
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.ChartLabel
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Colour
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Colouring
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Mark
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Panel
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Series
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.SeriesRole
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Summary
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.SummaryKind
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.XAxis
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.BarLayout
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.Chart
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.ChartLabel
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.Mark
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.Panel
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.Series
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.SeriesRole
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.Summary
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.SummaryKind
instance GHC.Internal.Generics.Generic Hledger.Write.Chart.XAxis
instance GHC.Internal.Show.Show Hledger.Write.Chart.BarLayout
instance GHC.Internal.Show.Show Hledger.Write.Chart.Chart
instance GHC.Internal.Show.Show Hledger.Write.Chart.ChartLabel
instance GHC.Internal.Show.Show Hledger.Write.Chart.Colour
instance GHC.Internal.Show.Show Hledger.Write.Chart.Colouring
instance GHC.Internal.Show.Show Hledger.Write.Chart.Mark
instance GHC.Internal.Show.Show Hledger.Write.Chart.Panel
instance GHC.Internal.Show.Show Hledger.Write.Chart.Series
instance GHC.Internal.Show.Show Hledger.Write.Chart.SeriesRole
instance GHC.Internal.Show.Show Hledger.Write.Chart.Summary
instance GHC.Internal.Show.Show Hledger.Write.Chart.SummaryKind
instance GHC.Internal.Show.Show Hledger.Write.Chart.XAxis
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.BarLayout
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Chart
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.ChartLabel
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Mark
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Panel
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Series
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.SeriesRole
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.Summary
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.SummaryKind
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Write.Chart.XAxis


-- | 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).
module Hledger.Write.Chart.Palette

-- | A chart colour as #rrggbb, in its light variant (for light
--   backgrounds) or its dark variant (for dark backgrounds).
colourHex :: Bool -> Colour -> Text

-- | Mix a #rrggbb colour with white (by a positive fraction) or black (by
--   a negative fraction).
tint :: Double -> Text -> Text
tests_Hledger_Write_Chart_Palette :: TestTree


-- | Draw a <a>Chart</a> 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: <a>styledLinesAsText</a> turns them
--   into plain or ANSI-coloured text.
module Hledger.Write.Chart.Text

-- | Options for drawing a text chart.
data TextChartOpts
TextChartOpts :: Int -> Bool -> TextChartOpts

-- | the width to fill, in characters (eg the terminal width)
[tcWidth] :: TextChartOpts -> Int

-- | use unicode block characters (otherwise ASCII)
[tcUnicode] :: TextChartOpts -> Bool

-- | How a piece of text should be shown.
data Style
StylePlain :: Style

-- | the colour of the Nth ordinary series in a panel
StyleSeries :: Int -> Style

-- | the colour of a main account type, in its Nth variant
StyleType :: AccountType -> Int -> Style

-- | the colour of a series combining several items ("other"), of this main
--   account type if any
StyleOther :: Maybe AccountType -> Style

-- | the colour of a chart's only series, when it is not an account
StyleLone :: Style

-- | a negative value
StyleNegative :: Style

-- | How to colour a text chart.
data ColourMode
NoColour :: ColourMode

-- | with the terminal's basic ANSI colours (whose exact shades depend on
--   its colour theme)
BasicColour :: ColourMode

-- | with exact 24-bit colours, the same as SVG charts'; their variants for
--   a dark background if true
RgbColour :: Bool -> ColourMode

-- | A line of text made of styled pieces.
type StyledLine = [(Style, Text)]

-- | 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
--   <a>legendListsSeries</a>) 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]

-- | Render styled lines as text, with ANSI colours or without.
styledLinesAsText :: ColourMode -> [StyledLine] -> Text
tests_Hledger_Write_Chart_Text :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Text.ColourMode
instance GHC.Internal.Classes.Eq Hledger.Write.Chart.Text.Style
instance GHC.Internal.Show.Show Hledger.Write.Chart.Text.ColourMode
instance GHC.Internal.Show.Show Hledger.Write.Chart.Text.Style


-- | Draw a <a>Chart</a> 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 <a>legendListsSeries</a>), 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 <a>SvgOptions</a>, eg
--   without its styles, which the page then supplies
--   (<a>chartStylesheet</a>).
module Hledger.Write.Chart.Svg

-- | Render a chart as a complete SVG document, with a dark variant for
--   viewers preferring a dark colour scheme.
chartAsSvg :: Chart -> Text

-- | 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 -> Text

-- | A chart as SVG markup, which can also be embedded in HTML; with or
--   without the dark variant.
chartSvgMarkup :: Bool -> Chart -> Svg

-- | How to draw a chart as SVG.
data SvgOptions
SvgOptions :: Bool -> Bool -> Double -> Double -> (Int -> Maybe Text) -> Bool -> Maybe Day -> Text -> SvgOptions

-- | include the chart's styles ? A page embedding the chart can leave them
--   out and supply <a>chartStylesheet</a> itself, eg one whose
--   Content-Security-Policy allows no inline styles.
[svgStyles] :: SvgOptions -> Bool

-- | include the styles' dark variant, for viewers preferring a dark colour
--   scheme ?
[svgDark] :: SvgOptions -> Bool

-- | 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.
[svgWidth] :: SvgOptions -> 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 <a>plotIntervals</a>). (Horizontal bars are as tall
--   as their rows.)
[svgPlotHeight] :: SvgOptions -> Double

-- | 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.
[svgPointLink] :: SvgOptions -> Int -> Maybe Text

-- | 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 ?
[svgDateScale] :: SvgOptions -> Bool

-- | 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.
[svgToday] :: SvgOptions -> Maybe Day

-- | 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.
[svgIds] :: SvgOptions -> Text

-- | 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

-- | A chart as SVG markup, which can also be embedded in HTML, drawn with
--   these options.
chartSvgMarkupWith :: SvgOptions -> Chart -> Svg

-- | 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
--   <a>svgIds</a>), the given prefix numbered.
chartPanelsSvgMarkupWith :: SvgOptions -> Chart -> [Svg]

-- | 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 <a>SvgOptions</a>).
chartStylesheet :: Bool -> Text
tests_Hledger_Write_Chart_Svg :: TestTree


-- | Helpers for making error messages.
module Hledger.Data.Errors

-- | 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

-- | Given an account name and its account directive, and a problem tag
--   within the latter: render it as a megaparsec-style excerpt, showing
--   the original line number and marked column or region. Returns the file
--   path, line number, column(s) if known, and the rendered excerpt, or as
--   much of these as is possible. The returned columns will be accurate
--   for the rendered error message but not for the original journal data.
makeAccountTagErrorExcerpt :: (AccountName, AccountDeclarationInfo) -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | 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)

-- | Given a problem price directive, and maybe a function to calculate the
--   error region's column(s) (currently ignored): generate a
--   megaparsec-style error message with highlighted excerpt. Returns the
--   source file path, line number, column(s) if known, and the rendered
--   excerpt, or as much of these as possible. Columns will be accurate for
--   the rendered error message, not for the original journal entry.
makePriceDirectiveErrorExcerpt :: PriceDirective -> Maybe (PriceDirective -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
makeTransactionErrorExcerpt :: Transaction -> (Transaction -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Given a problem posting and a function calculating the best column(s)
--   for marking the error region: look up error info from the parent
--   transaction, and render the transaction as a megaparsec-style excerpt,
--   showing the original line number on the problem posting's line, and a
--   column indicator. Returns the file path, line number, column(s) if
--   known, and the rendered excerpt, or as much of these as is possible. A
--   limitation: columns will be accurate for the rendered error message
--   but not for the original journal data.
makePostingErrorExcerpt :: Posting -> (Posting -> Transaction -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Like <a>makePostingErrorExcerpt</a>, 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)

-- | From the given posting, make an error excerpt showing the transaction
--   with this posting's account part highlighted.
makePostingAccountErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | From the given posting, make an error excerpt showing the transaction
--   with the balance assertion highlighted.
makeBalanceAssertionErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)

-- | Find the 1-based index of the first posting in this transaction
--   satisfying the given predicate.
transactionFindPostingIndex :: (Posting -> Bool) -> Transaction -> Maybe Int

module Hledger.Data.JournalChecks.Ordereddates
journalCheckOrdereddates :: Journal -> Either String ()


-- | A <a>Journal</a> is a set of transactions, plus optional related data.
--   This is hledger's primary data object. It is usually parsed from a
--   journal file or other data format (see <a>Hledger.Read</a>).
module Hledger.Data.Journal

-- | A parser of text that runs in some monad, keeping a Journal as state.
type JournalParser (m :: Type -> Type) a = StateT Journal ParsecT HledgerParseErrorData Text m a

-- | A parser of text that runs in some monad, keeping a Journal as state,
--   that can throw an exception to end parsing, preventing further parser
--   backtracking.
type ErroringJournalParser (m :: Type -> Type) a = StateT Journal ParsecT HledgerParseErrorData Text ExceptT FinalParseError m a
addPriceDirective :: PriceDirective -> Journal -> Journal
addTransactionModifier :: TransactionModifier -> Journal -> Journal

-- | 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

-- | 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
addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addAssertDirective :: AssertDirective -> Journal -> Journal
addTransaction :: Transaction -> Journal -> Journal
journalDbg :: Journal -> String

-- | Infer transaction-implied market prices from commodity-exchanging
--   transactions, if any. It's best to call this after transactions have
--   been balanced and posting amounts have appropriate prices attached.
journalInferMarketPricesFromTransactions :: Journal -> Journal

-- | 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 <a>Left</a> 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

-- | 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 = Map CommoditySymbol (CommoditySymbol, Quantity, Maybe AmountStyle)

-- | The commodity aliases declared in this journal.
journalCommodityAliases :: Journal -> CommodityAliases

-- | 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)

-- | Aliases declared on a commodity directive by its <tt>alias:</tt> tags.
commodityAliases :: Commodity -> [CommoditySymbol]

-- | 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

-- | 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 <a>commodityRedeclare</a>, 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

-- | All commodity symbols that this journal treats as declared: both the
--   canonical <a>jdeclaredcommodities</a> keys and any 'alias:' values
--   declared on those commodity directives.
commoditiesAndAliases :: Journal -> Set CommoditySymbol

-- | 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

-- | 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
--   <tt>get</tt>'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

-- | Get the canonical amount styles for this journal, whether (in order of
--   precedence): set globally in InputOpts, declared by commodity
--   directives, declared by a default commodity (D) directive, or inferred
--   from posting amounts, as a map from symbol to style. Styles from
--   directives are assumed to specify the decimal mark.
journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle

-- | Like journalCommodityStyles, but attach a particular rounding strategy
--   to the styles, affecting how they will affect display precisions when
--   applied.
journalCommodityStylesWith :: Rounding -> Journal -> Map CommoditySymbol AmountStyle

-- | Convert all this journal's amounts to cost using their attached
--   prices, if any.
journalToCost :: ConversionOp -> Journal -> Journal

-- | Add equity postings inferred from costs, where needed and possible.
--   See hledger manual &gt; Cost reporting.
journalInferEquityFromCosts :: Bool -> Journal -> Journal

-- | Identify and tag (1) equity conversion postings and (2) postings which
--   have (or could have ?) redundant costs. And if the addcosts flag is
--   true, also add any costs which can be inferred from equity conversion
--   postings. This is always called before transaction balancing to tag
--   the redundant-cost postings so they can be ignored. With
--   --infer-costs, it is called again after transaction balancing (when it
--   has more information to work with) to infer costs from equity
--   postings. See transactionTagCostsAndEquityAndMaybeInferCosts for more
--   details, and hledger manual &gt; Cost reporting for more background.
journalTagCostsAndEquityAndMaybeInferCosts :: Bool -> Bool -> Journal -> Either String Journal

-- | Reverse all lists of parsed items, which during parsing were prepended
--   to, so that the items are in parse order. Part of post-parse
--   finalisation.
journalReverse :: Journal -> Journal

-- | Set this journal's last read time, ie when its files were last read.
journalSetLastReadTime :: POSIXTime -> Journal -> Journal

-- | Renumber all the account declarations. This is useful to call when
--   finalising or concatenating Journals, to give account declarations a
--   total order across files.
journalRenumberAccountDeclarations :: Journal -> Journal

-- | Apply the pivot transformation to all postings in a journal, replacing
--   their account name by their value for the given field or tag.
journalPivot :: Text -> Journal -> Journal

-- | 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

-- | 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

-- | 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

-- | 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

-- | Does this commodity have a 'lots:' tag declared ?
journalCommodityUsesLots :: Journal -> CommoditySymbol -> Bool

-- | 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

-- | The declared lots: tag values by account (the first value, if an
--   account somehow has several).
journalAccountLotsTags :: Journal -> Map AccountName Text

-- | Like journalAccountUsesNoLots, but taking the
--   <a>journalAccountLotsTags</a> map (useful where no Journal is at hand,
--   eg during balancing).
accountUsesNoLotsWith :: Map AccountName Text -> AccountName -> Bool

-- | All commodities with a 'lots:' tag declared.
journalLotfulCommodities :: Journal -> Set CommoditySymbol

-- | Get the reduction method from a commodity's lots: tag value, if any.
journalCommodityLotsMethod :: Journal -> CommoditySymbol -> Maybe ReductionMethod

-- | Get the reduction method from a posting's lots: tag value (typically
--   inherited from its account), if any.
postingLotsMethod :: Posting -> Maybe ReductionMethod

-- | Parse a reduction method name from a lots: tag value.
parseReductionMethod :: Text -> Maybe ReductionMethod

-- | Check that all lots: tag values on commodity and account declarations
--   are recognised. On a commodity declaration, an empty value (bare
--   <tt>lots:</tt> 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

-- | Keep only transactions matching the query expression.
filterJournalTransactions :: Query -> Journal -> Journal

-- | Keep only postings matching the query expression. This can leave
--   unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal

-- | Keep only postings which do not match the query expression, but for
--   which a related posting does. This can leave unbalanced transactions.
filterJournalRelatedPostings :: Query -> Journal -> Journal

-- | Within each posting's amount, keep only the parts matching the query,
--   and remove any postings with all amounts removed. This can leave
--   unbalanced transactions.
filterJournalAmounts :: Query -> Journal -> Journal

-- | Filter out all parts of this transaction's amounts which do not match
--   the query, and remove any postings with all amounts removed. This can
--   leave the transaction unbalanced.
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionPostings :: Query -> Transaction -> Transaction
filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction
filterTransactionRelatedPostings :: Query -> Transaction -> Transaction

-- | Filter out all parts of this posting's amount which do not match the
--   query, and remove the posting if this removes all amounts.
filterPostingAmount :: Query -> Posting -> Maybe Posting

-- | Apply a transformation to a journal's transactions.
journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal

-- | Apply a transformation to a journal's postings.
journalMapPostings :: (Posting -> Posting) -> Journal -> Journal

-- | Apply a transformation to a journal's posting amounts.
journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal

-- | Sorted unique account names posted to by this journal's transactions.
journalAccountNamesUsed :: Journal -> [AccountName]

-- | Sorted unique account names implied by this journal's transactions -
--   accounts posted to and all their implied parent accounts.
journalAccountNamesImplied :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives in this
--   journal.
journalAccountNamesDeclared :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives or posted
--   to by transactions in this journal.
journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]

-- | Sorted unique account names declared by account directives, or posted
--   to or implied as parents by transactions in this journal.
journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]

-- | Convenience/compatibility alias for
--   journalAccountNamesDeclaredOrImplied.
journalAccountNames :: Journal -> [AccountName]

-- | Sorted unique account names declared or implied in this journal which
--   have no children.
journalLeafAccountNames :: Journal -> [AccountName]
journalAccountNameTree :: Journal -> Tree AccountName

-- | Which tags have been declared explicitly for this account, if any ?
journalAccountTags :: Journal -> AccountName -> [Tag]

-- | Get any tags declared for this commodity.
journalCommodityTags :: Journal -> CommoditySymbol -> [Tag]

-- | Which tags are in effect for this account, including tags inherited
--   from parent accounts ?
journalInheritedAccountTags :: Journal -> AccountName -> [Tag]

-- | Sorted unique payees declared by payee directives in this journal.
journalPayeesDeclared :: Journal -> [Payee]

-- | Sorted unique payees used by transactions in this journal.
journalPayeesUsed :: Journal -> [Payee]

-- | Sorted unique payees used in transactions or declared by payee
--   directives in this journal.
journalPayeesDeclaredOrUsed :: Journal -> [Payee]

-- | Sorted unique tag names declared by tag directives in this journal.
journalTagsDeclared :: Journal -> [TagName]

-- | Sorted unique tag names used in this journal (in account directives,
--   transactions, postings..)
journalTagsUsed :: Journal -> [TagName]

-- | Sorted unique tag names used in transactions or declared by tag
--   directives in this journal.
journalTagsDeclaredOrUsed :: Journal -> [TagName]

-- | All raw amounts appearing in this journal, with MixedAmounts
--   flattened, in no particular order. (Including from posting amounts,
--   cost amounts, P directives, and the last D directive.)
journalAmounts :: Journal -> Set Amount

-- | All posting amounts from this journal, in order.
journalPostingAmounts :: Journal -> [MixedAmount]

-- | All raw amounts used in this journal's postings and costs, with
--   MixedAmounts flattened, in parse order.
journalPostingAndCostAmounts :: Journal -> [Amount]

-- | Sorted unique commodity symbols declared by commodity directives in
--   this journal.
journalCommoditiesDeclared :: Journal -> [CommoditySymbol]

-- | Sorted unique commodity symbols used anywhere in this journal,
--   including commodity directives, P directives, the last D directive,
--   posting amounts and cost amounts.
journalCommoditiesUsed :: Journal -> [CommoditySymbol]

-- | Sorted unique commodity symbols mentioned anywhere in this journal.
--   (Including commodity directives, P directives, the last D directive,
--   posting amounts and cost amounts.)
journalCommodities :: Journal -> Set CommoditySymbol

-- | Sorted unique commodity symbols mentioned in this journal's P
--   directives.
journalCommoditiesFromPriceDirectives :: Journal -> Set CommoditySymbol

-- | Sorted unique commodity symbols used in transactions, in either
--   posting or cost amounts.
journalCommoditiesFromTransactions :: Journal -> Set CommoditySymbol

-- | 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)

-- | The ISO 4217 currency code of this journal's guessed base currency
--   (<a>journalBaseCurrency</a>), defaulting to <a>USD</a>.
journalBaseCurrencyCode :: Journal -> CurrencyCode

-- | The fully specified exact date span enclosing the dates (primary or
--   secondary) of all this journal's transactions and postings, or
--   DateSpan Nothing Nothing if there are none.
journalDateSpan :: Bool -> Journal -> DateSpan

-- | The fully specified date span enclosing the dates (primary and
--   secondary) of all this journal's transactions and postings, or
--   DateSpan Nothing Nothing if there are none.
journalDateSpanBothDates :: Journal -> DateSpan

-- | The earliest of this journal's transaction and posting dates, or
--   Nothing if there are none.
journalStartDate :: Bool -> Journal -> Maybe Day

-- | The "exclusive end date" of this journal: the day following its latest
--   transaction or posting date, or Nothing if there are none.
journalEndDate :: Bool -> Journal -> Maybe Day

-- | The latest of this journal's transaction and posting dates, or Nothing
--   if there are none.
journalLastDay :: Bool -> Journal -> Maybe Day

-- | Unique transaction descriptions used in this journal.
journalDescriptions :: Journal -> [Text]
journalFilePath :: Journal -> FilePath
journalFilePaths :: Journal -> [FilePath]

-- | 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]

-- | Get the transaction with this index (its 1-based position in the input
--   stream), if any.
journalTransactionAt :: Journal -> Integer -> Maybe Transaction

-- | Get the transaction that appeared immediately after this one in the
--   input stream, if any.
journalNextTransaction :: Journal -> Transaction -> Maybe Transaction

-- | Get the transaction that appeared immediately before this one in the
--   input stream, if any.
journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction

-- | All postings from this journal's transactions, in order.
journalPostings :: Journal -> [Posting]

-- | Show the journal posting amounts rendered, suitable for debug logging.
showJournalPostingAmountsDebug :: Journal -> String

-- | Find up to N most similar and nearest-dated transactions matching the
--   given transaction description and query and exceeding the given
--   description similarity score (0 to 1, see compareDescriptions). The
--   provided Day (today) is used as the reference date; transactions are
--   penalised by their absolute distance from it in days (both past and
--   future). Returns transactions along with their distance in days from
--   today, their description similarity score, and a heuristically
--   date-weighted variant of this that favours nearby transactions.
journalTransactionsSimilarTo :: Journal -> Day -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, TimeDistance, SimilarityScore, Transaction)]
journalAccountType :: Journal -> AccountName -> Maybe AccountType

-- | Build a map of all known account types, explicitly declared or
--   inferred from the account's parent or name.
journalAccountTypes :: Journal -> Map AccountName AccountType

-- | Add a map of all known account types to the journal.
journalAddAccountTypes :: Journal -> Journal
defaultBaseConversionAccount :: IsString a => a

-- | 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

-- | The account name to use for conversion postings generated by
--   --infer-equity (see journalAccountForType; the default is
--   equity:conversion).
journalBaseConversionAccount :: Journal -> AccountName

-- | 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]
defaultGainAccount :: IsString a => a

-- | The account name to use for inferred gain postings (see
--   journalAccountForType; the default is revenues:gain).
journalBaseGainAccount :: Journal -> AccountName

-- | All the accounts in this journal which are declared or inferred as
--   G/Gain type, alphabetically.
journalGainAccounts :: Journal -> [AccountName]
nulljournal :: Journal

-- | Merge two journals into one. Transaction counts are summed, map fields
--   are combined, the second's list fields are appended to the first's,
--   the second's parse state is kept.
journalConcat :: Journal -> Journal -> Journal

-- | Number (set the tindex field) this journal's transactions, counting
--   upward from 1.
journalNumberTransactions :: Journal -> Journal

-- | 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

-- | Tie the knot in all of this journal's transactions, ensuring their
--   postings refer to them. This should be done last, after any other
--   transaction-modifying operations.
journalTieTransactions :: Journal -> Journal

-- | Untie all transaction-posting knots in this journal, so that eg
--   recursiveSize and GHCI's :sprint can work on it.
journalUntieTransactions :: Transaction -> Transaction

-- | Apply any transaction modifier rules in the journal (adding automated
--   postings to transactions, eg). Or if a modifier rule fails to parse,
--   return the error message. A reference date is provided to help
--   interpret relative dates in transaction modifier queries. The first
--   argument selects whether to add visible tags to generated postings
--   &amp; modified transactions.
journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal

-- | Apply some account aliases to all posting account names in the
--   journal, as described by accountNameApplyAliases. This can fail due to
--   a bad replacement pattern in a regular expression alias.
journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal

-- | Debug log the ordering of a journal's account declarations (at debug
--   level 7+).
dbgJournalAcctDeclOrder :: String -> Journal -> Journal
samplejournal :: Journal
samplejournalMaybeExplicit :: Bool -> Journal
tests_Journal :: TestTree
instance Data.Default.Internal.Default Hledger.Data.Types.Journal
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.Journal
instance GHC.Internal.Show.Show Hledger.Data.Types.AssertDirective
instance GHC.Internal.Show.Show Hledger.Data.Types.Journal


-- | Helpers for beancount output.
module Hledger.Write.Beancount

-- | Like showTransaction, but applies various adjustments to produce valid
--   Beancount journal data.
showTransactionBeancount :: Transaction -> Text

-- | Render a PriceDirective in Beancount format: DATE price COMMODITY
--   AMOUNT
showPriceDirectiveBeancount :: PriceDirective -> Text

-- | 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]

-- | 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])

-- | 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] -> Text

-- | 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

-- | Make a list of tags ready to be rendered as Beancount metadata: Encode
--   and lengthen names, encode values, and combine repeated tags into one.
--   Metadatas will be sorted by (encoded) name and then value.
tagsToBeancountMetadata :: [Tag] -> [BMetadata]

-- | Render a Beancount metadata as a metadata line (without the
--   indentation or newline). If a maximum name length is provided, space
--   will be left after the colon so that successive metadata values will
--   all start at the same column.
showBeancountMetadata :: Maybe Int -> BMetadata -> Text

-- | Convert a hledger account name to a valid Beancount account name. It
--   replaces spaces and underscores with dashes and other non-supported
--   characters with C<a>HEXBYTES</a>; prepends the letter A to any part
--   which doesn't begin with a letter or number; adds a second :A part if
--   there is only one part; and capitalises each part. It also checks that
--   the first part is one of the required english account names Assets,
--   Liabilities, Equity, Income, or Expenses, and if not raises an
--   informative error. Ref:
--   <a>https://beancount.github.io/docs/beancount_language_syntax.html#accounts</a>
accountNameToBeancount :: AccountName -> BeancountAccountName

-- | Convert a hledger commodity name to a valid Beancount commodity name.
--   That is: 2-24 uppercase letters <i> digits </i> apostrophe <i> period
--   </i> underscore / dash, starting with a letter, and ending with a
--   letter or digit. Ref:
--   <a>https://beancount.github.io/docs/beancount_language_syntax.html#commodities-currencies</a>
--   So this: replaces common currency symbols with their ISO 4217 currency
--   codes, capitalises all letters, replaces spaces with dashes and other
--   invalid characters with C<a>HEXBYTES</a>, 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.
--   
--   <pre>
--   &gt;&gt;&gt; commodityToBeancount ""
--   "CC"
--   
--   &gt;&gt;&gt; commodityToBeancount "$"
--   "USD"
--   
--   &gt;&gt;&gt; commodityToBeancount "Usd"
--   "USD"
--   
--   &gt;&gt;&gt; commodityToBeancount "\"a1\""
--   "A1"
--   
--   &gt;&gt;&gt; commodityToBeancount "\"A 1!\""
--   "A-1C21"
--   
--   &gt;&gt;&gt; commodityToBeancount "K"
--   "KK"
--   </pre>
commodityToBeancount :: CommoditySymbol -> BeancountCommoditySymbol
tests_WriteBeancount :: TestTree


-- | Lot tracking for investment accounting.
--   
--   This module implements two pipeline stages (see
--   doc/SPEC-finalising.md):
--   
--   <ol>
--   <li>Classification (<a>journalClassifyLotPostings</a>): identifies lot
--   postings and tags them as acquire, dispose, transfer-from, or
--   transfer-to.</li>
--   <li>Calculation (<a>journalCalculateLots</a>): walks transactions in
--   date order, accumulating a map from commodities to their lots,
--   and:</li>
--   </ol>
--   
--   <ul>
--   <li>For acquire postings: generates lot names from cost basis and
--   appends them to the account name as subaccounts.</li>
--   <li>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
--   <tt>lots:</tt> 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.</li>
--   <li>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 <tt>{}</tt> to transfer all lots).</li>
--   </ul>
--   
--   For background, see doc/SPEC-lots.md and doc/PLAN-lots.md.
--   
--   <h2>Errors</h2>
--   
--   User-visible errors from this module. See also Hledger.Data.Errors and
--   doc/ERRORS.md.
--   
--   journalCalculateLots:
--   
--   <ul>
--   <li>validateUserLabels: "lot id is not unique: commodity X, date D,
--   label L"</li>
--   <li>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"</li>
--   <li>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"</li>
--   <li>groupIndexedTransferPostings: "transfer-to/from posting ... has no
--   matching ... posting", "Mismatched transfer quantities for lot-tracked
--   commodity X", "... posting has no lotful commodity"</li>
--   <li>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"</li>
--   <li>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"</li>
--   <li>validateGlobalCompliance: "METHOD: lot(s) on other account(s) have
--   higher priority than the lots in ACCT"</li>
--   <li>poolWeightedAvgCost: "no lots with cost basis available for
--   averaging", "cannot average lots with different cost commodities",
--   "cannot average lots with zero total quantity"</li>
--   <li>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)</li>
--   </ul>
module Hledger.Data.Lots

-- | 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

-- | 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 :: Set CommoditySymbol -> Transaction -> Bool

-- | 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

-- | Remove balancer-copied cost basis annotations (see
--   <a>hasBalancerCopiedBasis</a>) 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

-- | 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

-- | 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

-- | 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
--   <tt>journalInferPostingsTransactedCost</tt>).
journalCheckAcquireBasis :: Journal -> Either String Journal

-- | 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

-- | 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 -> Map (AccountName, CommoditySymbol) (Quantity, Amount)

-- | 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
--   <a>journalAveragePoolTotals</a>.
journalAveragePoolCosts :: Journal -> Maybe Day -> Map (AccountName, CommoditySymbol) Amount

-- | Collapse lot-tracking detail from a journal for display when --lots is
--   off. Makes these targeted changes to each transaction:
--   
--   <ul>
--   <li>drops postings tagged <tt>_lot-parent-assertion</tt> (synthetic
--   balance-assertion carriers added when splitting a posting into lot
--   subaccounts);</li>
--   <li>strips any lot subaccount (the trailing <tt>{...}</tt> component)
--   from each remaining posting's account name;</li>
--   <li>merges per-lot split fragments back into one posting (see
--   mergeLotSplits).</li>
--   </ul>
--   
--   Lot-inferred cost basis annotations (<tt>acostbasis</tt>) are kept on
--   the amounts: <a>print</a> shows them, so that lot entries are
--   self-describing and can be re-read without the commodity's
--   <tt>lots:</tt> declaration (under the default method). A merged
--   multi-lot posting gets an unspecified basis (<tt>{}</tt>), meaning
--   "lots selected by the account's method".
--   
--   Postings tagged <tt>_feesplit-posting</tt> (synthetic fee fragments
--   from auto-split) are retained so transactions stay balanced in reports
--   like <a>print</a>.
--   
--   <a>print</a> relies on its existing
--   <tt>transactionWithMostlyOriginalPostings</tt> logic to revert pamount
--   to <a>poriginal</a> when displaying non-explicit output (carrying the
--   inferred basis over).
--   
--   Journals with no lot content are returned unchanged.
journalCollapseLotDetail :: Journal -> Journal

-- | Apply <a>transactionTagGainPostings</a> 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

-- | In a disposal transaction, tag the user-written realised gain postings
--   with <tt>_ptype:gain</tt>, so that the transaction balancer sets them
--   aside (see <a>transactionCheckBalanced</a>).
--   
--   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 <tt>q*B + q*(T-B)
--   == q*T</tt>, 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
--   <a>journalAddOrCheckGainPostings</a>.
--   
--   Disposal transactions are recognised by shape, since classification
--   has not run yet: a real posting with a negative lotful or cost-basis
--   amount (<a>postingHasDisposeShape</a>; 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:
--   
--   <ol>
--   <li>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
--   <a>journalAddOrCheckGainPostings</a> sets its amount to the calculated
--   gain.</li>
--   <li>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.</li>
--   </ol>
--   
--   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 -> Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction

-- | For each disposal transaction with a transacted price, add a
--   realised-gain posting to a <a>Gain</a>-type account (default
--   <tt>revenues:gain</tt>) with the negated gain amount; or if the
--   transaction already has gain posting(s) (user-written; see
--   <a>transactionTagGainPostings</a>), 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 <tt>aquantity
--   * (B - T)</tt> (equivalently: cost-basis value minus transacted-cost
--   value). Acquire and other postings do not contribute. Eg for <tt>-5
--   AAPL {$50} @ $70</tt>: gain contribution is <tt>-5 * ($50 - $70) =
--   $100</tt>.
--   
--   Runs after <a>journalCalculateLots</a> so that cost basis is populated
--   on dispose postings. The generated posting carries the
--   <tt>_generated-posting</tt> hidden tag, visible as
--   <tt>generated-posting:</tt> in <tt>print --verbose-tags</tt>.
journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal

-- | Check if a posting is a dispose posting (has _ptype:dispose tag).
isDisposePosting :: Posting -> Bool

-- | 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

-- | 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
--   <a>transactionTagGainPostings</a>). 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

-- | Strip any trailing lot subaccount (a final <tt>:{...}</tt> component)
--   from an account name. E.g., <tt>"assets:broker:{2026-01-15, $50}"</tt>
--   becomes <tt>"assets:broker"</tt>.
lotBaseAccount :: AccountName -> AccountName

-- | 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
--   <a>LotDirection</a>.
lotDirectionOf :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe LotDirection

-- | The lot direction of an account in this journal. See
--   <a>lotDirectionOf</a>.
journalLotDirection :: Journal -> AccountName -> Maybe LotDirection

-- | Extract the lot subaccount name (the <tt>{...}</tt> component) from an
--   account name, or <tt>Nothing</tt> if there is none. E.g.,
--   <tt>"assets:broker:{2026-01-15, $50}"</tt> returns <tt>Just
--   "{2026-01-15, $50}"</tt>.
lotSubaccountName :: AccountName -> Maybe Text

-- | Merge two <a>CostBasis</a> values. For each field, if both are
--   <tt>Just</tt>, they must agree (returns error if not); otherwise takes
--   whichever is <tt>Just</tt>. 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

-- | Parse a lot name (as produced by <a>showLotName</a>) back into a
--   <a>CostBasis</a>. The input should be the full <tt>{...}</tt> string
--   including braces. Parts are comma-separated and all optional: date
--   (<tt>YYYY-MM-DD</tt>), label (<tt>"LABEL"</tt>), 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

-- | 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)

-- | Render a lot name in the consolidated hledger format for use as a
--   subaccount name. Format: <tt>{YYYY-MM-DD, COST}</tt> or
--   <tt>{YYYY-MM-DD, "LABEL", COST}</tt>. 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 <a>CostBasis</a> with
--   <a>styleLotCbCost</a>.
showLotName :: CostBasis -> Text

module Hledger.Data.JournalChecks.Uniqueleafnames

-- | Check that all the journal's postings are to accounts with a unique
--   leaf name. Otherwise, return an error message for the first offending
--   posting.
journalCheckUniqueleafnames :: Journal -> Either String ()


-- | 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 <tt>hledger bal -E QUERY</tt> would show,
--   rather than by running the balance report, which would make journal
--   reading depend on the reports code.
module Hledger.Data.JournalChecks.Assert

-- | 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 ()


-- | Functions for ensuring transactions and journals are balanced.
module Hledger.Data.Balancing
data BalancingOpts
BalancingOpts :: Bool -> Bool -> Maybe (Map CommoditySymbol AmountStyle) -> TransactionBalancingPrecision -> Bool -> AccountName -> Map AccountName AccountType -> Set CommoditySymbol -> Map AccountName Text -> Bool -> Bool -> BalancingOpts

-- | should failing balance assertions be ignored ?
[ignore_assertions_] :: BalancingOpts -> Bool

-- | Are we permitted to infer missing costs to balance transactions ?
--   Distinct from InputOpts{infer_costs_}.
[infer_balancing_costs_] :: BalancingOpts -> Bool

-- | commodity display styles
[commodity_styles_] :: BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
[txn_balancing_] :: BalancingOpts -> TransactionBalancingPrecision

-- | should tolerated imbalances be shown, by adding imbalance postings to
--   transactions ?
[infer_imbalance_] :: BalancingOpts -> Bool

-- | the account for imbalance postings (see journalAccountForType)
[imbalance_account_] :: BalancingOpts -> AccountName

-- | account type map, passed through for any balancing helpers that need
--   it
[account_types_] :: BalancingOpts -> Map AccountName AccountType

-- | commodities declared lotful, used to guide balancing cost inference
--   (when lots are enabled)
[lotful_commodities_] :: BalancingOpts -> Set CommoditySymbol

-- | declared lots: tag values by account, used to detect lots: NONE
--   opt-outs (when lots are enabled)
[account_lots_tags_] :: BalancingOpts -> Map AccountName Text

-- | with --ignore-lots: relax the lot quantity mismatch veto, inferring a
--   balancing conversion cost anyway
[lenient_lots_] :: BalancingOpts -> Bool

-- | should tags added by balancing helpers (eg lot fee splits) also be
--   made visible in comments ?
[verbose_balancing_tags_] :: BalancingOpts -> Bool
class HasBalancingOpts c
balancingOpts :: HasBalancingOpts c => Lens' c BalancingOpts
account_lots_tags :: HasBalancingOpts c => Lens' c (Map AccountName Text)
account_types :: HasBalancingOpts c => Lens' c (Map AccountName AccountType)
commodity_styles :: HasBalancingOpts c => Lens' c (Maybe (Map CommoditySymbol AmountStyle))
ignore_assertions :: HasBalancingOpts c => Lens' c Bool
imbalance_account :: HasBalancingOpts c => Lens' c AccountName
infer_balancing_costs :: HasBalancingOpts c => Lens' c Bool
infer_imbalance :: HasBalancingOpts c => Lens' c Bool
lenient_lots :: HasBalancingOpts c => Lens' c Bool
lotful_commodities :: HasBalancingOpts c => Lens' c (Set CommoditySymbol)
txn_balancing :: HasBalancingOpts c => Lens' c TransactionBalancingPrecision
verbose_balancing_tags :: HasBalancingOpts c => Lens' c Bool
defbalancingopts :: BalancingOpts

-- | Legacy form of transactionCheckBalanced.
isTransactionBalanced :: BalancingOpts -> Transaction -> Bool

-- | Balance this isolated transaction, ensuring that its postings (and its
--   balanced virtual postings) sum to 0, by inferring a missing amount or
--   conversion price(s) if needed. Or if balancing is not possible,
--   because the amounts don't sum to 0 or because there's more than one
--   missing amount, return an error message.
--   
--   Note this is not as accurate as <tt>balanceTransactionInJournal</tt>,
--   which considers the whole journal when calculating balance assignments
--   and balance assertions.
balanceSingleTransaction :: BalancingOpts -> Transaction -> Either String Transaction

-- | Helper used by balanceSingleTransaction and
--   balanceTransactionWithBalanceAssignmentAndCheckAssertionsB; use one of
--   those instead. It also returns a list of accounts and amounts that
--   were inferred.
balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])

-- | Generate a transaction balancing error message, given the transaction
--   and one or more suberror messages.
transactionBalanceError :: Transaction -> [String] -> String

-- | 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

-- | 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

-- | 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

-- | 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 :: Map CommoditySymbol AmountStyle -> Posting -> (Posting, Bool)

-- | Verify that any assertions in this transaction hold when included in
--   the larger journal.
transactionCheckAssertions :: BalancingOpts -> Journal -> Transaction -> Either String Transaction

-- | Infer any missing amounts and/or conversion costs (as needed to
--   balance transactions and satisfy balance assignments); and check that
--   all transactions are balanced; and (optional) check that all balance
--   assertions pass. Or, return an error message (just the first error
--   encountered).
--   
--   Assumes journalStyleAmounts has been called, since amount styles
--   affect transaction balancing.
--   
--   This does multiple things at once because amount inferring, balance
--   assignments, balance assertions and posting dates are interdependent.
journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal

-- | 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)
tests_Balancing :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Data.Balancing.BalancingOpts
instance Hledger.Data.Balancing.HasBalancingOpts Hledger.Data.Balancing.BalancingOpts
instance GHC.Internal.Classes.Ord Hledger.Data.Balancing.BalancingOpts
instance GHC.Internal.Show.Show Hledger.Data.Balancing.BalancingOpts


-- | Various options to use when reading journal files. Similar to
--   CliOptions.inputflags, simplifies the journal-reading functions.
module Hledger.Read.InputOptions
data InputOpts
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

-- | a file/storage format to try, unless overridden by a filename prefix.
--   Nothing means try all.
[mformat_] :: InputOpts -> Maybe StorageFormat

-- | a conversion rules file to use (when reading CSV)
[mrules_file_] :: InputOpts -> Maybe FilePath

-- | account name aliases to apply
[aliases_] :: InputOpts -> [String]

-- | do light obfuscation of the data ? Now corresponds to --obfuscate, not
--   the old --anon flag.
[anon_] :: InputOpts -> Bool

-- | read only new transactions since this file was last read ?
[new_] :: InputOpts -> Bool

-- | save latest new transactions state for next time ?
[new_save_] :: InputOpts -> Bool

-- | use the given field's value as the account name
[pivot_] :: InputOpts -> String

-- | span in which to generate forecast transactions
[forecast_] :: InputOpts -> Maybe DateSpan

-- | add user-visible tags when generating/modifying transactions &amp;
--   postings ?
[verbose_tags_] :: InputOpts -> Bool

-- | a dirty hack keeping the query dates in InputOpts. This rightfully
--   lives in ReportSpec, but is duplicated here.
[reportspan_] :: InputOpts -> DateSpan

-- | generate extra postings according to auto posting rules ?
[auto_] :: InputOpts -> Bool

-- | infer equity conversion postings from costs ?
[infer_equity_] :: InputOpts -> Bool

-- | infer costs from equity conversion postings ? distinct from
--   BalancingOpts{infer_balancing_costs_}
[infer_costs_] :: InputOpts -> Bool

-- | skip lot tracking and its checks, silencing lot errors ? (basic lot
--   inference still runs, leniently, so lot entries balance)
[ignore_lots_] :: InputOpts -> Bool

-- | options for transaction balancing
[balancingopts_] :: InputOpts -> BalancingOpts

-- | do extra correctness checks ?
[strict_] :: InputOpts -> Bool

-- | internal flag: postpone checks, because we are processing multiple
--   files ?
[_defer] :: InputOpts -> Bool

-- | internal flag: is this the <tt>import</tt> command reading its data
--   files ? Enables the CSV rules reader's import-specific behaviour:
--   preferring the oldest file matched by a <tt>source</tt> glob, and
--   honouring the <tt>archive</tt> rule. Set by <tt>importcmd</tt>; other
--   reads should leave it off.
[_importing] :: InputOpts -> Bool

-- | internal flag: is this a <tt>import --dry-run</tt> command ? If set,
--   the CSV rules reader will never archive or remove a data file.
[_dryrun] :: InputOpts -> 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.
[_scanfiles] :: InputOpts -> 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.
[_forecastOnlyForDisplay] :: InputOpts -> Bool

-- | today's date, for use with forecast transactions XXX this duplicates
--   _rsDay, and should eventually be removed when it's not needed anymore.
[_ioDay] :: InputOpts -> Day

-- | parse with the old timeclock pairing rules?
[_oldtimeclock] :: InputOpts -> Bool

-- | The main journal file's directory. Used eg by the CSV rules reader to
--   locate the journal's <tt>data/</tt> directory. Set by the CLI entry
--   points <tt>withJournal</tt>, <tt>withPossibleJournal</tt>, and
--   <tt>journalReload</tt>. If you do a further <tt>readJournalFile</tt> /
--   <tt>readJournalFiles</tt> call after a journal has been loaded (eg as
--   <tt>import</tt> does), apply <a>inputOptsSetJournalDir</a> to its
--   <a>InputOpts</a> so the CSV rules reader can find the right
--   <tt>data/</tt>. Otherwise, the CSV rules reader falls back to the
--   rules file's own directory.
[_journaldir] :: InputOpts -> Maybe FilePath

-- | internal: replacement content for some files, keyed by canonical path
--   (see <a>canonicalizePath</a>), 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 <tt>journalCheckChange</tt>
--   in hledger's Hledger.Cli.Utils).
[_fileoverrides] :: InputOpts -> Map FilePath Text
class HasInputOpts c
inputOpts :: HasInputOpts c => Lens' c InputOpts
aliases :: HasInputOpts c => Lens' c [String]
anon__ :: HasInputOpts c => Lens' c Bool
auto__ :: HasInputOpts c => Lens' c Bool
balancingopts :: HasInputOpts c => Lens' c BalancingOpts
defer :: HasInputOpts c => Lens' c Bool
dryrun :: HasInputOpts c => Lens' c Bool
fileoverrides :: HasInputOpts c => Lens' c (Map FilePath Text)
forecast :: HasInputOpts c => Lens' c (Maybe DateSpan)
forecastOnlyForDisplay :: HasInputOpts c => Lens' c Bool
ignore_lots :: HasInputOpts c => Lens' c Bool
importing :: HasInputOpts c => Lens' c Bool
infer_costs :: HasInputOpts c => Lens' c Bool
infer_equity :: HasInputOpts c => Lens' c Bool
ioDay :: HasInputOpts c => Lens' c Day
journaldir :: HasInputOpts c => Lens' c (Maybe FilePath)
mformat :: HasInputOpts c => Lens' c (Maybe StorageFormat)
mrules_file :: HasInputOpts c => Lens' c (Maybe FilePath)
new__ :: HasInputOpts c => Lens' c Bool
new_save :: HasInputOpts c => Lens' c Bool
oldtimeclock :: HasInputOpts c => Lens' c Bool
pivot :: HasInputOpts c => Lens' c String
reportspan :: HasInputOpts c => Lens' c DateSpan
scanfiles :: HasInputOpts c => Lens' c Bool
strict :: HasInputOpts c => Lens' c Bool
verbose_tags :: HasInputOpts c => Lens' c Bool
definputopts :: InputOpts

-- | The replacement content for this file in the input options'
--   <a>_fileoverrides</a>, 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)

-- | Set <a>_journaldir</a> from a parsed <a>Journal</a> (using
--   <tt>takeDirectory . journalFilePath</tt>).
--   
--   Use this when you want to do a further <tt>readJournalFile</tt> /
--   <tt>readJournalFiles</tt> call after a journal has been loaded — eg
--   the <tt>hledger import</tt> command reads the user's rules files in a
--   second pass — so the CSV rules reader can find the journal's
--   <tt>data/</tt> directory for <tt>source</tt> lookups and
--   <tt>archive</tt> saves. Otherwise it will fall back to using the rules
--   file's own directory, which is no longer the preferred place.
--   
--   Usage:
--   
--   <pre>
--   iopts' = inputOptsSetJournalDir j $ iopts { ...other tweaks... }
--   </pre>
inputOptsSetJournalDir :: Journal -> InputOpts -> InputOpts

-- | Get the Maybe the DateSpan to generate forecast options from. This
--   begins on: - the start date supplied to the `--forecast` argument, if
--   present - otherwise, the later of - the report start date if specified
--   with -b<i>-p</i>date: - the day after the latest normal (non-periodic)
--   transaction in the journal, if any - otherwise today. It ends on: -
--   the end date supplied to the `--forecast` argument, if present -
--   otherwise the report end date if specified with -e<i>-p</i>date: -
--   otherwise 180 days (6 months) from today.
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
instance GHC.Internal.Classes.Eq Hledger.Read.InputOptions.InputOpts
instance Hledger.Data.Balancing.HasBalancingOpts Hledger.Read.InputOptions.InputOpts
instance Hledger.Read.InputOptions.HasInputOpts Hledger.Read.InputOptions.InputOpts
instance GHC.Internal.Classes.Ord Hledger.Read.InputOptions.InputOpts
instance GHC.Internal.Show.Show Hledger.Read.InputOptions.InputOpts


-- | Various additional validation checks that can be performed on a
--   Journal. Some are called as part of reading a file in strict mode,
--   others can be called only via the check command.
module Hledger.Data.JournalChecks

-- | Run the extra -s/--strict checks on a journal, in order of priority,
--   returning the first error message if any of them fail.
journalStrictChecks :: Journal -> Either String ()

-- | 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 ()

-- | 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 ()

-- | 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 ()

-- | 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 ()

-- | The commodities referenced by this journal's postings and P directives
--   that have not been declared by a commodity directive, nor as an
--   <tt>alias:</tt> of one. These are exactly the commodities that make
--   <a>journalCheckCommodities</a> (hledger check commodities, and -s)
--   fail. The synthetic 1:1 price directives inferred from <tt>alias:</tt>
--   tags contribute only aliases, so they never appear here.
journalUndeclaredCommodities :: Journal -> [CommoditySymbol]

-- | 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 <tt>hledger check lots</tt> remains a valid command, and
--   also re-enables the validation when -I was passed.
journalCheckLots :: Journal -> Either String ()

-- | Check that all the journal's transactions have payees declared with
--   payee directives, returning an error message otherwise.
journalCheckPayees :: Journal -> Either String ()

-- | In each tranaction, check that any conversion postings occur in
--   adjacent pairs.
journalCheckPairedConversionPostings :: Journal -> Either String ()

-- | Check that accounts with balance assertions have no posting more than
--   maxlag days after their latest balance assertion.
journalCheckRecentAssertions :: Journal -> Either String ()

-- | 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 ()


-- | A 'BalanceData is a data type tracking a number of postings,
--   exclusive, and inclusive balance for given date ranges.
module Hledger.Data.BalanceData

-- | Apply an operation to both <a>MixedAmount</a> in an
--   <a>BalanceData</a>.
mapBalanceData :: (MixedAmount -> MixedAmount) -> BalanceData -> BalanceData

-- | Merge two <a>BalanceData</a>, using the given operation to combine
--   their amounts.
opBalanceData :: (MixedAmount -> MixedAmount -> MixedAmount) -> BalanceData -> BalanceData -> BalanceData
tests_BalanceData :: TestTree
instance GHC.Internal.Base.Monoid Hledger.Data.Types.BalanceData
instance GHC.Internal.Base.Semigroup Hledger.Data.Types.BalanceData
instance GHC.Internal.Show.Show Hledger.Data.Types.BalanceData


-- | An <a>Account</a> has a name, a list of subaccounts, an optional
--   parent account, and subaccounting-excluding and -including balances.
module Hledger.Data.Account
nullacct :: Account BalanceData

-- | Construct an 'Account" from an account name and balances. Other fields
--   are left blank.
accountFromBalances :: AccountName -> PeriodData a -> Account a

-- | Derive 1. an account tree and 2. each account's total exclusive and
--   inclusive changes associated with dates from a list of postings and a
--   function for associating a date to each posting (usually representing
--   the start dates of report subperiods). This is the core of the balance
--   command (and of *ledger). The accounts are returned as a tree.
accountFromPostings :: (Posting -> Maybe Day) -> [Posting] -> Account BalanceData

-- | Derive 1. an account tree and 2. each account's total exclusive and
--   inclusive changes associated with dates from a list of postings and a
--   function for associating a date to each posting (usually representing
--   the start dates of report subperiods). This is the core of the balance
--   command (and of *ledger). The accounts are returned as a list in
--   flattened tree order, and also reference each other as a tree. (The
--   first account is the root of the tree.)
accountsFromPostings :: (Posting -> Maybe Day) -> [Posting] -> [Account BalanceData]

-- | Convert a list of account names to a tree of Account objects, with
--   just the account names filled in and an empty balance. A single root
--   account with the given name is added.
accountTree :: Monoid a => AccountName -> [AccountName] -> Account a

-- | Convert a list of account names to a tree of Account objects, with
--   just the account names filled in. Each account is given the same
--   supplied balance. A single root account with the given name is added.
accountTreeFromBalanceAndNames :: AccountName -> PeriodData a -> [AccountName] -> Account a
showAccounts :: Show a => Account a -> String
showAccountsBoringFlag :: Account a -> String
printAccounts :: Show a => Account a -> IO ()

-- | Search an account list by name.
lookupAccount :: AccountName -> [Account a] -> Maybe (Account a)

-- | Get this account's parent accounts, from the nearest up to the root.
parentAccounts :: Account a -> [Account a]

-- | List the accounts at each level of the account tree.
accountsLevels :: Account a -> [[Account a]]

-- | Map a (non-tree-structure-modifying) function over this and sub
--   accounts.
mapAccounts :: (Account a -> Account a) -> Account a -> Account a

-- | Apply a function to all <a>PeriodData</a> within this and sub
--   accounts.
mapPeriodData :: (PeriodData a -> PeriodData a) -> Account a -> Account a

-- | Is the predicate true on any of this account or its subaccounts ?
anyAccounts :: (Account a -> Bool) -> Account a -> Bool

-- | Filter an account tree (to a list).
filterAccounts :: (Account a -> Bool) -> Account a -> [Account a]

-- | Recalculate all the subaccount-inclusive balances in this tree.
sumAccounts :: Account BalanceData -> Account BalanceData

-- | Remove all subaccounts below a certain depth.
clipAccounts :: Int -> Account a -> Account a

-- | Remove subaccounts below the specified depth, aggregating their
--   balance at the depth limit (accounts at the depth limit will have any
--   sub-balances merged into their exclusive balance). If the depth is
--   Nothing, return the original accounts
clipAccountsAndAggregate :: Monoid a => DepthSpec -> [Account a] -> [Account a]

-- | Remove all leaf accounts and subtrees matching a predicate.
pruneAccounts :: (Account a -> Bool) -> Account a -> Maybe (Account a)

-- | Flatten an account tree into a list, which is sometimes convenient.
--   Note since accounts link to their parents/subs, the tree's structure
--   remains intact and can still be used. It's a tree/list!
flattenAccounts :: Account a -> [Account a]

-- | Merge two account trees and their subaccounts.
--   
--   This assumes that the top-level <a>Account</a>s have the same name.
mergeAccounts :: Account a -> Account b -> Account (These a b)

-- | Add extra info for this account derived from the Journal's account
--   directives, if any (comment, tags, declaration order..).
accountSetDeclarationInfo :: Journal -> Account a -> Account a

-- | Sort account names by the order in which they were declared in the
--   journal, at each level of the account tree (ie within each group of
--   siblings). Undeclared accounts are sorted last and alphabetically.
--   This is hledger's default sort for reports organised by account. The
--   account list is converted to a tree temporarily, adding any missing
--   parents; these can be kept (suitable for a tree-mode report) or
--   removed (suitable for a flat-mode report).
sortAccountNamesByDeclaration :: Journal -> Bool -> [AccountName] -> [AccountName]

-- | Sort each group of siblings in an account tree by declaration order,
--   then account name. So each group will contain first the declared
--   accounts, in the same order as their account directives were parsed,
--   and then the undeclared accounts, sorted by account name.
sortAccountTreeByDeclaration :: Account a -> Account a

-- | Sort each group of siblings in an account tree by projecting through a
--   provided function.
sortAccountTreeOn :: Ord b => (Account a -> b) -> Account a -> Account a
tests_Account :: TestTree
instance GHC.Internal.Classes.Eq (Hledger.Data.Types.Account a)
instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (Hledger.Data.Account.FastTree a)
instance GHC.Internal.Classes.Ord a => GHC.Internal.Classes.Ord (Hledger.Data.Account.FastTree a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Types.Account a)
instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Hledger.Data.Account.FastTree a)


-- | A <a>Ledger</a> is derived from a <a>Journal</a> by applying a filter
--   specification to select <a>Transaction</a>s and <a>Posting</a>s of
--   interest. It contains the filtered journal and knows the resulting
--   chart of accounts, account balances, and postings in each account.
module Hledger.Data.Ledger
nullledger :: Ledger

-- | Filter a journal's transactions with the given query, then build a
--   <a>Ledger</a>, containing the journal plus the tree of all its
--   accounts with their subaccount-inclusive and subaccount-exclusive
--   balances. If the query includes a depth limit, the ledger's journal
--   will be depth limited, but the ledger's account tree will not.
ledgerFromJournal :: Query -> Journal -> Ledger

-- | List a ledger's account names.
ledgerAccountNames :: Ledger -> [AccountName]

-- | Get the named account from a ledger.
ledgerAccount :: Ledger -> AccountName -> Maybe (Account BalanceData)

-- | Get this ledger's root account, which is a dummy "root" account above
--   all others. This should always be first in the account list, if
--   somehow not this returns a null account.
ledgerRootAccount :: Ledger -> Account BalanceData

-- | List a ledger's top-level accounts (the ones below the root), in tree
--   order.
ledgerTopAccounts :: Ledger -> [Account BalanceData]

-- | List a ledger's bottom-level (subaccount-less) accounts, in tree
--   order.
ledgerLeafAccounts :: Ledger -> [Account BalanceData]

-- | List a ledger's postings, in the order parsed.
ledgerPostings :: Ledger -> [Posting]

-- | The (fully specified) date span containing all the ledger's (filtered)
--   transactions, or DateSpan Nothing Nothing if there are none.
ledgerDateSpan :: Ledger -> DateSpan

-- | All commodities used in this ledger.
ledgerCommodities :: Ledger -> [CommoditySymbol]
tests_Ledger :: TestTree
instance GHC.Internal.Show.Show Hledger.Data.Types.Ledger


-- | The Hledger.Data library allows parsing and querying of C++
--   ledger-style journal files. It generally provides a compatible subset
--   of C++ ledger's functionality. This package re-exports all the
--   Hledger.Data.* modules (except UTF8, which requires an explicit
--   import.)
module Hledger.Data
fromEFDay :: EFDay -> Day
isBalanceSheetAccountType :: AccountType -> Bool
isDecimalMark :: Char -> Bool

-- | Does this tag name begin with the hidden tag prefix (_) ?
isHiddenTagName :: TagName -> Bool
isIncomeStatementAccountType :: AccountType -> Bool

-- | Compare two MixedAmounts, substituting 0 for the quantity of any
--   missing commodities in either.
maCompare :: MixedAmount -> MixedAmount -> Ordering

-- | Calculate the key for storing this Amount within a MixedAmount, from
--   its commodity and transacted cost (ignoring cost basis).
mixedAmountKey :: Amount -> MixedAmountKey
modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
nullaccountdeclarationinfo :: AccountDeclarationInfo
nullpayeedeclarationinfo :: PayeeDeclarationInfo
nullperiodictransaction :: PeriodicTransaction
nullsourcepos :: SourcePos
nullsourcepospair :: (SourcePos, SourcePos)
nulltagdeclarationinfo :: TagDeclarationInfo
nulltransactionmodifier :: TransactionModifier
showMarketPrice :: MarketPrice -> String
showMarketPrices :: [MarketPrice] -> [Char]

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTag :: Tag -> HiddenTag

-- | Add the _ prefix to a normal visible tag's name, making it a hidden
--   tag.
toHiddenTagName :: TagName -> TagName

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTag :: HiddenTag -> Tag

-- | Drop the _ prefix from a hidden tag's name, making it a normal visible
--   tag.
toVisibleTagName :: TagName -> TagName

-- | An account within a hierarchy, with references to its parent and
--   subaccounts if any, and with per-report-period data of type
--   <tt>a</tt>. Only the name is required; the other fields may or may not
--   be present.
data Account a
Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account a] -> Maybe (Account a) -> Bool -> PeriodData a -> Account a

-- | full name
[aname] :: Account a -> AccountName

-- | optional extra info from account directives relationships in the tree
[adeclarationinfo] :: Account a -> Maybe AccountDeclarationInfo

-- | subaccounts
[asubs] :: Account a -> [Account a]

-- | parent account
[aparent] :: Account a -> Maybe (Account a)

-- | used in some reports to indicate elidable accounts
[aboring] :: Account a -> Bool

-- | associated data per report period
[adata] :: Account a -> PeriodData a
data AccountAlias
BasicAlias :: AccountName -> AccountName -> AccountAlias
RegexAlias :: Regexp -> Replacement -> AccountAlias

-- | Extra information about an account that can be derived from its
--   account directive (and the other account directives).
data AccountDeclarationInfo
AccountDeclarationInfo :: Text -> [Tag] -> Int -> SourcePos -> AccountDeclarationInfo

-- | any comment lines following an account directive for this account
[adicomment] :: AccountDeclarationInfo -> Text

-- | tags extracted from the account comment, if any
[aditags] :: AccountDeclarationInfo -> [Tag]

-- | the order in which this account was declared, relative to other
--   account declarations, during parsing (1..)
[adideclarationorder] :: AccountDeclarationInfo -> Int

-- | source file and position
[adisourcepos] :: AccountDeclarationInfo -> SourcePos
type AccountName = Text
data AccountType
Asset :: AccountType
Liability :: AccountType
Equity :: AccountType
Revenue :: AccountType
Expense :: AccountType

-- | a subtype of Asset - liquid assets to show in cashflow report
Cash :: AccountType

-- | a subtype of Equity - account with which to balance commodity
--   conversions
Conversion :: AccountType

-- | a subtype of Revenue - realised capital gains/losses
Gain :: AccountType

-- | a subtype of Equity - accumulated unrealised capital gains/losses
UnrealisedGain :: AccountType

-- | a subtype of Equity - transactions' tolerated imbalances, shown by
--   --infer-imbalance
Imbalance :: AccountType
data Amount
Amount :: CommoditySymbol -> Quantity -> AmountStyle -> Maybe AmountCost -> Maybe CostBasis -> Amount
[acommodity] :: Amount -> CommoditySymbol
[aquantity] :: Amount -> Quantity
[astyle] :: Amount -> AmountStyle

-- | transacted exchange rate - the unit or total cost, in another
--   commodity, used for this amount within its transaction
[acost] :: Amount -> Maybe AmountCost

-- | the cost basis of an investment lot represented by this amount. Or, a
--   matcher to select such a lot from the available lots.
[acostbasis] :: Amount -> Maybe CostBasis

-- | An amount's per-unit or total cost/selling price in another commodity,
--   as recorded in the journal entry eg with <tt> or </tt>@. <a>Cost</a>,
--   formerly AKA "transaction price". The amount is always positive.
data AmountCost
UnitCost :: Amount -> AmountCost
TotalCost :: Amount -> AmountCost

-- | The "display precision" for a hledger amount, by which we mean the
--   number of decimal digits to display to the right of the decimal mark.
data AmountPrecision

-- | show this many decimal digits (0..255)
Precision :: Word8 -> AmountPrecision

-- | show all significant decimal digits stored internally
NaturalPrecision :: AmountPrecision

-- | Display styles for amounts - things which can be detected during
--   parsing, such as commodity side and spacing, digit group marks,
--   decimal mark, number of decimal digits etc. Every <a>Amount</a> has an
--   AmountStyle. After amounts are parsed from the input, for each
--   <a>Commodity</a> a standard style is inferred and then used when
--   displaying amounts in that commodity. Related to <a>AmountFormat</a>
--   but higher level.
--   
--   See also: - hledger manual &gt; Commodity styles - hledger manual &gt;
--   Amounts - hledger manual &gt; Commodity display style
data AmountStyle
AmountStyle :: Side -> Bool -> Maybe DigitGroupStyle -> Maybe Char -> AmountPrecision -> Rounding -> AmountStyle

-- | show the symbol on the left or the right ?
[ascommodityside] :: AmountStyle -> Side

-- | show a space between symbol and quantity ?
[ascommodityspaced] :: AmountStyle -> Bool

-- | show the integer part with these digit group marks, or not
[asdigitgroups] :: AmountStyle -> Maybe DigitGroupStyle

-- | show this character (should be . or ,) as decimal mark, or use the
--   default (.)
[asdecimalmark] :: AmountStyle -> Maybe Char

-- | "display precision" - show this number of digits after the decimal
--   point
[asprecision] :: AmountStyle -> AmountPrecision

-- | "rounding strategy" - kept here for convenience, for now: when
--   displaying an amount, it is ignored, but when applying this style to
--   another amount, it determines how hard we should try to adjust that
--   amount's display precision.
[asrounding] :: AmountStyle -> Rounding

-- | 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 :: AssertQuantifier -> Maybe (Interval, DateSpan) -> Text -> Text -> [DateSpan] -> Text -> SourcePos -> AssertDirective
[adQuantifier] :: AssertDirective -> AssertQuantifier

-- | the period expression, if any: the rule is checked in each of its
--   periods
[adPeriod] :: AssertDirective -> Maybe (Interval, DateSpan)

-- | the period expression as written, or empty
[adPeriodText] :: AssertDirective -> Text

-- | the query as written
[adQueryText] :: AssertDirective -> Text

-- | the periods of its skip subdirectives, whose checks are skipped
[adSkips] :: AssertDirective -> [DateSpan]

-- | the directive's lines as written (the assert line and any skip lines),
--   for error excerpts
[adSourceText] :: AssertDirective -> Text
[adSourcePos] :: AssertDirective -> SourcePos

-- | Which rows an assert directive's query must match: none, or at least
--   one.
data AssertQuantifier
AssertNone :: AssertQuantifier
AssertSome :: AssertQuantifier

-- | A balance assertion is a declaration about an account's expected
--   balance at a certain point (posting date and parse order). They
--   provide additional error checking and readability to a journal file.
--   
--   A balance assignments is an instruction to hledger to adjust an
--   account's balance to a certain amount at a certain point.
--   
--   The <a>BalanceAssertion</a> type is used for representing both of
--   these.
--   
--   hledger supports multiple kinds of balance assertions/assignments,
--   which differ in whether they refer to a single commodity or all
--   commodities, and the (subaccount-)inclusive or exclusive account
--   balance.
data BalanceAssertion
BalanceAssertion :: Amount -> Bool -> Bool -> SourcePos -> BalanceAssertion

-- | the expected balance in a particular commodity
[baamount] :: BalanceAssertion -> Amount

-- | disallow additional non-asserted commodities ?
[batotal] :: BalanceAssertion -> Bool

-- | include subaccounts when calculating the actual balance ?
[bainclusive] :: BalanceAssertion -> Bool

-- | the assertion's file position, for error reporting
[baposition] :: BalanceAssertion -> SourcePos

-- | Data that's useful in "balance" reports: subaccount-exclusive and
--   -inclusive amounts, typically representing either a balance change or
--   an end balance; and a count of postings.
data BalanceData
BalanceData :: MixedAmount -> MixedAmount -> Int -> BalanceData

-- | balance data excluding subaccounts
[bdexcludingsubs] :: BalanceData -> MixedAmount

-- | balance data including subaccounts
[bdincludingsubs] :: BalanceData -> MixedAmount

-- | the number of postings
[bdnumpostings] :: BalanceData -> Int
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Text -> [Tag] -> [(Amount, SourcePos)] -> SourcePos -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle

-- | any comment lines following the commodity directive
[ccomment] :: Commodity -> Text

-- | tags extracted from the comment, if any
[ctags] :: Commodity -> [Tag]

-- | 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
[caliases] :: Commodity -> [(Amount, SourcePos)]

-- | source position of the commodity directive
[csourcepos] :: Commodity -> SourcePos
type CommoditySymbol = Text

-- | The cost basis of an individual lot - some quantity of an asset
--   acquired at a given date and time. This can represent a definite cost
--   basis, which must have a cost and date; the label is optional. Or it
--   can represent a cost basis matcher for selecting lots. Note: cost is
--   always stored as a per-unit cost, even if the user specified total
--   cost with {{}}.
data CostBasis
CostBasis :: Maybe Day -> Maybe Text -> Maybe Amount -> CostBasis

-- | nominal acquisition date
[cbDate] :: CostBasis -> Maybe Day

-- | a short label to ensure uniqueness, correct intra-day order, or
--   memorability, if needed
[cbLabel] :: CostBasis -> Maybe Text

-- | nominal acquisition cost (per-unit)
[cbCost] :: CostBasis -> Maybe Amount

-- | A possibly open-ended span of time, from an optional inclusive start
--   date to an optional exclusive end date. Each date can be either exact
--   or flexible. An "exact date span" is a Datepan with exact start and
--   end dates.
data DateSpan
DateSpan :: Maybe EFDay -> Maybe EFDay -> DateSpan
type DateTag = (TagName, Day)

-- | One of the decimal marks we support: either period or comma.
type DecimalMark = Char
data DepthSpec
DepthSpec :: Maybe Int -> [(Regexp, Int)] -> DepthSpec
[dsFlatDepth] :: DepthSpec -> Maybe Int
[dsRegexpDepths] :: DepthSpec -> [(Regexp, Int)]

-- | A style for displaying digit groups in the integer part of a floating
--   point number. It consists of the character used to separate groups
--   (any of the digit group marks accepted when parsing: period, comma,
--   underscore, apostrophe, or one of several unicode spaces; see
--   isDigitSeparatorChar), and the size of each group, starting with the
--   one nearest the decimal point. The last group size is assumed to
--   repeat. Eg, comma between thousands is DigitGroups ',' [3].
data DigitGroupStyle
DigitGroups :: Char -> [Word8] -> DigitGroupStyle

-- | A date which is either exact or flexible. Flexible dates are allowed
--   to be adjusted in certain situations.
data EFDay
Exact :: Day -> EFDay
Flex :: Day -> EFDay

-- | 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 :: Int -> Int -> Int -> Int -> Map Text Int -> FastPathStats

-- | transactions parsed by the fast path
[fpsTxnsFast] :: FastPathStats -> Int

-- | transactions it declined, parsed by the general parser
[fpsTxnsGeneral] :: FastPathStats -> Int

-- | price directives parsed by the fast path
[fpsPricesFast] :: FastPathStats -> Int

-- | price directives it declined
[fpsPricesGeneral] :: FastPathStats -> Int

-- | the number of declines for each reason
[fpsDeclines] :: FastPathStats -> Map Text Int

-- | Types with this class have one or more amounts, which can have display
--   styles applied to them.
class HasAmounts a
styleAmounts :: HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
type HiddenTag = Tag
data Interval
NoInterval :: Interval
Days :: Int -> Interval
Weeks :: Int -> Interval
Months :: Int -> Interval
Quarters :: Int -> Interval
Years :: Int -> Interval
NthWeekdayOfMonth :: Int -> Int -> Interval
MonthDay :: Int -> Interval
MonthAndDay :: Int -> Int -> Interval
DaysOfWeek :: [Int] -> Interval

-- | A journal, containing general ledger transactions; also directives and
--   various other things. This is hledger's main data model.
--   
--   During parsing, it is used as the type alias <a>ParsedJournal</a>. The
--   jparse* fields are mainly used during parsing and included here for
--   convenience. The list fields described as "in parse order" are usually
--   reversed for efficiency during parsing. After parsing,
--   "journalFinalise" converts ParsedJournal to a finalised
--   <a>Journal</a>, which has all lists correctly ordered, and much data
--   inference and validation applied.
data Journal
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

-- | the current default year, specified by the most recent Y or apply year
--   directive (or current date)
[jparsedefaultyear] :: Journal -> 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.
[jparseapplyyears] :: Journal -> [Maybe Year]

-- | the current default commodity and its format, specified by the most
--   recent D directive
[jparsedefaultcommodity] :: Journal -> Maybe (CommoditySymbol, AmountStyle)

-- | the character to always parse as decimal point, if set by CsvReader's
--   decimal-mark (or a future journal directive)
[jparsedecimalmark] :: Journal -> Maybe DecimalMark

-- | the current stack of parent account names, specified by apply account
--   directives
[jparseparentaccounts] :: Journal -> [AccountName]

-- | 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.
[jparsealiases] :: Journal -> [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)
[jparseoptaliases] :: Journal -> [AccountAlias]

-- | timeclock sessions which have not been clocked out
[jparsetimeclockentries] :: Journal -> [TimeclockEntry]

-- | (absolute path, canonical path) of included files, most recent first
[jparseincludefilestack] :: Journal -> [(FilePath, FilePath)]

-- | the most recently calculated source position, if any, from which later
--   ones are calculated cheaply
[jparsepos] :: Journal -> Maybe ParsePos

-- | the distinct amount styles parsed so far, which parsed amounts share
--   to save memory
[jparseamountstyles] :: Journal -> Set AmountStyle

-- | the distinct account names and commodity symbols parsed so far, which
--   parsed items share to save memory
[jparsetexts] :: Journal -> Set Text

-- | how many entries the parser's fast path has accepted or declined so
--   far, and why (with --debug) principal data
[jparsefastpathstats] :: Journal -> FastPathStats

-- | Payees declared by payee directives, in parse order.
[jdeclaredpayees] :: Journal -> [(Payee, PayeeDeclarationInfo)]

-- | Tags declared by tag directives, in parse order.
[jdeclaredtags] :: Journal -> [(TagName, TagDeclarationInfo)]

-- | Accounts declared by account directives, in parse order.
[jdeclaredaccounts] :: Journal -> [(AccountName, AccountDeclarationInfo)]

-- | Accounts which were declared with tags, and those tags.
[jdeclaredaccounttags] :: Journal -> Map AccountName [Tag]

-- | Accounts which were declared with a type: tag, grouped by the type.
[jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName]

-- | All the account types known, from account declarations or account
--   names or parent accounts.
[jaccounttypes] :: Journal -> Map AccountName AccountType

-- | Commodities (and their display styles) declared by commodity
--   directives, in parse order.
[jdeclaredcommodities] :: Journal -> Map CommoditySymbol Commodity

-- | Commodities which were declared with tags, and those tags.
[jdeclaredcommoditytags] :: Journal -> Map CommoditySymbol [Tag]

-- | Commodity display styles inferred from amounts in the journal.
[jinferredcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | Commodity display styles declared by command line options (sometimes
--   augmented, see the import command).
[jglobalcommoditystyles] :: Journal -> Map CommoditySymbol AmountStyle

-- | P (market price) directives in the journal, in parse order.
[jpricedirectives] :: Journal -> [PriceDirective]

-- | Market prices inferred from transactions in the journal, in parse
--   order.
[jinferredmarketprices] :: Journal -> [MarketPrice]

-- | Auto posting rules declared in the journal.
[jtxnmodifiers] :: Journal -> [TransactionModifier]

-- | Periodic transaction rules declared in the journal.
[jperiodictxns] :: Journal -> [PeriodicTransaction]

-- | Assert directives declared in the journal, in parse order.
[jasserts] :: Journal -> [AssertDirective]

-- | Transactions recorded in the journal. The important bit.
[jtxns] :: Journal -> [Transaction]

-- | 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).
[jitems] :: Journal -> [JournalItem]

-- | the main and any included journal files. The main file is first,
--   followed by any included files in the order encountered.
[jfiles] :: Journal -> [JournalFile]

-- | 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.
[jauxfiles] :: Journal -> [(FilePath, [FilePath])]

-- | 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
[jlastreadtime] :: Journal -> POSIXTime

-- | One of the files a journal was read from.
data JournalFile
JournalFile :: FilePath -> Text -> Int -> JournalFile

-- | 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
[jfpath] :: JournalFile -> FilePath

-- | the file's raw text
[jftext] :: JournalFile -> Text

-- | the file's include depth: 0 for a main file, 1 for a file it includes,
--   and so on
[jfdepth] :: JournalFile -> Int

-- | 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

-- | a transaction: the one in jtxns whose tsourcepos starts here
JITransaction :: SourcePos -> JournalItem

-- | a single top-level comment line (starting with ; # or *)
JIComment :: Text -> JournalItem

-- | a comment ... end comment block
JICommentBlock :: Text -> JournalItem

-- | a directive which should be reproduced when exporting (including P, ~
--   and = rules), without any ! or @ prefix
JIDirective :: Text -> JournalItem

-- | 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
JINonExportedDirective :: Text -> JournalItem

-- | an include directive line; the included file's items follow it
JIInclude :: Text -> JournalItem

-- | one or more blank lines
JIBlank :: JournalItem

-- | A Ledger has the journal it derives from, and the accounts derived
--   from that. Accounts are accessible both list-wise and tree-wise, since
--   each one knows its parent and subs; the first account is the root of
--   the tree and always exists.
data Ledger
Ledger :: Journal -> [Account BalanceData] -> Ledger
[ljournal] :: Ledger -> Journal
[laccounts] :: Ledger -> [Account BalanceData]

-- | 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 :: Day -> Maybe Text -> LotId
[lotDate] :: LotId -> Day
[lotLabel] :: LotId -> Maybe Text

-- | A historical market price (exchange rate) from one commodity to
--   another. A more concise form of a PriceDirective, without the amount
--   display info.
data MarketPrice
MarketPrice :: Day -> CommoditySymbol -> CommoditySymbol -> Quantity -> MarketPrice

-- | Date on which this price becomes effective.
[mpdate] :: MarketPrice -> Day

-- | The commodity being converted from.
[mpfrom] :: MarketPrice -> CommoditySymbol

-- | The commodity being converted to.
[mpto] :: MarketPrice -> CommoditySymbol

-- | One unit of the "from" commodity is worth this quantity of the "to"
--   commodity.
[mprate] :: MarketPrice -> Quantity

-- | 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.
data MixedAmount

-- | amount commodity
pattern MixedAmountKeyNoCost :: () => CommoditySymbol -> MixedAmountKey
pattern MixedAmountKeyTotalCost :: () => CommoditySymbol -> CommoditySymbol -> MixedAmountKey
pattern MixedAmountKeyUnitCost :: () => CommoditySymbol -> CommoditySymbol -> Quantity -> MixedAmountKey
type Month = Int
type MonthDay = Int
type MonthWeek = Int

-- | Whether an account's balance is normally a positive number (in
--   accounting terms, a debit balance) or a negative number (credit
--   balance). Assets and expenses are normally positive (debit), while
--   liabilities, equity and income are normally negative (credit).
--   <a>https://en.wikipedia.org/wiki/Normal_balance</a>
data NormalSign
NormallyPositive :: NormalSign
NormallyNegative :: NormalSign

-- | 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 :: SourcePos -> Int -> Text -> ParsePos
[ppSourcePos] :: ParsePos -> SourcePos
[ppOffset] :: ParsePos -> Int
[ppInput] :: ParsePos -> Text

-- | 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
type Payee = Text

-- | Extra information found in a payee directive.
data PayeeDeclarationInfo
PayeeDeclarationInfo :: Text -> [Tag] -> PayeeDeclarationInfo

-- | any comment lines following the payee directive
[pdicomment] :: PayeeDeclarationInfo -> Text

-- | tags extracted from the comment, if any
[pditags] :: PayeeDeclarationInfo -> [Tag]
data Period
DayPeriod :: Day -> Period
WeekPeriod :: Day -> Period
MonthPeriod :: Year -> Month -> Period
QuarterPeriod :: Year -> Quarter -> Period
YearPeriod :: Year -> Period
PeriodBetween :: Day -> Day -> Period
PeriodFrom :: Day -> Period
PeriodTo :: Day -> Period
PeriodAll :: Period

-- | A general container for storing data values associated with zero or
--   more contiguous report (sub)periods, and with the (open ended)
--   pre-report period. The report periods are typically all the same
--   length, but need not be.
--   
--   Report periods are represented only by their start dates, used as the
--   keys of a Map.
data PeriodData a
PeriodData :: a -> Map Day a -> PeriodData a

-- | data for the period before the report
[pdpre] :: PeriodData a -> a

-- | data for each period within the report
[pdperiods] :: PeriodData a -> Map Day a

-- | A periodic transaction rule, describing a transaction that recurs.
data PeriodicTransaction
PeriodicTransaction :: Text -> Interval -> DateSpan -> (SourcePos, SourcePos) -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> PeriodicTransaction

-- | the period expression as written
[ptperiodexpr] :: PeriodicTransaction -> Text

-- | the interval at which this transaction recurs
[ptinterval] :: PeriodicTransaction -> Interval

-- | the (possibly unbounded) period during which this transaction recurs.
--   Contains a whole number of intervals.
[ptspan] :: PeriodicTransaction -> DateSpan

-- | the file position where the period expression starts, and where the
--   last posting ends
[ptsourcepos] :: PeriodicTransaction -> (SourcePos, SourcePos)

-- | some of Transaction's fields
[ptstatus] :: PeriodicTransaction -> Status
[ptcode] :: PeriodicTransaction -> Text
[ptdescription] :: PeriodicTransaction -> Text
[ptcomment] :: PeriodicTransaction -> Text
[pttags] :: PeriodicTransaction -> [Tag]
[ptpostings] :: PeriodicTransaction -> [Posting]
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingRealness -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting

-- | this posting's date, if different from the transaction's
[pdate] :: Posting -> Maybe Day

-- | this posting's secondary date, if different from the transaction's
[pdate2] :: Posting -> Maybe Day
[pstatus] :: Posting -> Status
[paccount] :: Posting -> AccountName
[pamount] :: Posting -> MixedAmount

-- | this posting's comment lines, as a single non-indented multi-line
--   string
[pcomment] :: Posting -> Text

-- | is this a normal balanced posting, or a virtual/unbalanced one ?
[preal] :: Posting -> PostingRealness

-- | tag names and values, extracted from the posting comment and (after
--   finalisation) the posting account's directive if any
[ptags] :: Posting -> [Tag]

-- | an expected balance in the account after this posting, in a single
--   commodity, excluding subaccounts.
[pbalanceassertion] :: Posting -> Maybe BalanceAssertion

-- | this posting's parent transaction (co-recursive types). Tying this
--   knot gets tedious, Maybe makes it easier/optional.
[ptransaction] :: Posting -> Maybe Transaction

-- | When this posting has been transformed in some way (eg its amount or
--   cost was inferred, or the account name was changed by a pivot or
--   budget report), this references the original untransformed posting
--   (which will have Nothing in this field).
[poriginal] :: Posting -> Maybe Posting
data PostingRealness
RealPosting :: PostingRealness
VirtualPosting :: PostingRealness
BalancedVirtualPosting :: PostingRealness

-- | A market price declaration made by the journal format's P directive.
--   It declares two things: a historical exchange rate between two
--   commodities, and an amount display style for the second commodity.
data PriceDirective
PriceDirective :: SourcePos -> Day -> CommoditySymbol -> Amount -> PriceDirective
[pdsourcepos] :: PriceDirective -> SourcePos
[pddate] :: PriceDirective -> Day
[pdcommodity] :: PriceDirective -> CommoditySymbol
[pdamount] :: PriceDirective -> Amount

-- | The basic numeric type used in amounts.
type Quantity = Decimal
type Quarter = Int

-- | The method used to select lots for disposal or transfer. Per-account
--   methods (scoped to the posting's account): FIFO<i>LIFO select
--   oldest</i>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<i>LIFOALL</i>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 :: ReductionMethod
LIFO :: ReductionMethod
HIFO :: ReductionMethod
AVERAGE :: ReductionMethod
SPECID :: ReductionMethod
FIFOALL :: ReductionMethod
LIFOALL :: ReductionMethod
HIFOALL :: ReductionMethod
AVERAGEALL :: ReductionMethod

-- | "Rounding strategy" - how to apply an AmountStyle's display precision
--   to a posting amount (and its cost, if any). Mainly used to customise
--   print's output, with --round=none|soft|hard|all.
data Rounding

-- | keep display precisions unchanged in amt and cost
NoRounding :: Rounding

-- | do soft rounding of amt and cost amounts (show more or fewer decimal
--   zeros to approximate the target precision, but don't hide significant
--   digits)
SoftRounding :: Rounding

-- | do hard rounding of amt (use the exact target precision, possibly
--   hiding significant digits), and soft rounding of cost
HardRounding :: Rounding

-- | do hard rounding of amt and cost
AllRounding :: Rounding

-- | One of the standard *-separated value file types known by hledger,
data SepFormat
Csv :: SepFormat
Tsv :: SepFormat
Ssv :: SepFormat
data Side
L :: Side
R :: Side

-- | A possibly incomplete year-month-day date provided by the user, to be
--   interpreted as either a date or a date span depending on context.
--   Missing parts "on the left" will be filled from the provided reference
--   date, e.g. if the year and month are missing, the reference date's
--   year and month are used. Missing parts "on the right" are assumed,
--   when interpreting as a date, to be 1, (e.g. if the year and month are
--   present but the day is missing, it means first day of that month); or
--   when interpreting as a date span, to be a wildcard (so it would mean
--   all days of that month). See the <tt>smartdate</tt> parser for more
--   examples.
--   
--   Or, one of the standard periods and a numeric offset relative to the
--   reference date: (last|this|next) (day|week|month|quarter|year), where
--   "this" means the period containing the reference date.
--   
--   Or, (last|this|next) weekdayname, where "this" "next".
--   
--   Or, (last|this|next) monthname, where "this" means the previous 1st if
--   in that month, otherwise the start of the next occurrence of that
--   month.
data SmartDate
SmartCompleteDate :: Day -> SmartDate
SmartAssumeStart :: Year -> Maybe Month -> SmartDate
SmartFromReference :: Maybe Month -> MonthDay -> SmartDate
SmartMonth :: Month -> SmartDate
SmartRelative :: Integer -> SmartInterval -> SmartDate

-- | EQ will be treated like GT
SmartRelativeMonth :: Ordering -> Month -> SmartDate
SmartRelativeWeekDay :: Ordering -> WeekDay -> SmartDate
data SmartInterval
Day :: SmartInterval
Week :: SmartInterval
Month :: SmartInterval
Quarter :: SmartInterval
Year :: SmartInterval

-- | The status of a transaction or posting, recorded with a status mark
--   (nothing, !, or *). What these mean is ultimately user defined.
data Status
Unmarked :: Status
Pending :: Status
Cleared :: Status

-- | The id of a data format understood by hledger, eg <tt>journal</tt> or
--   <tt>csv</tt>. The --output-format option selects one of these for
--   output.
data StorageFormat
Rules :: StorageFormat
Journal' :: StorageFormat
Ledger' :: StorageFormat
Timeclock :: StorageFormat
Timedot :: StorageFormat
Sep :: SepFormat -> StorageFormat

-- | A transaction modifier transformation, which adds an extra posting to
--   the matched posting's transaction. Can be like a regular posting, or
--   can have the tmprIsMultiplier flag set, indicating that it's a
--   multiplier for the matched posting's amount.
data TMPostingRule
TMPostingRule :: Posting -> Bool -> TMPostingRule
[tmprPosting] :: TMPostingRule -> Posting
[tmprIsMultiplier] :: TMPostingRule -> Bool
type Tag = (TagName, TagValue)

-- | Extra information found in a tag directive.
newtype TagDeclarationInfo
TagDeclarationInfo :: Text -> TagDeclarationInfo

-- | any comment lines following the tag directive. No tags allowed here.
[tdicomment] :: TagDeclarationInfo -> Text
type TagName = Text
type TagValue = Text
data TimeclockCode
SetBalance :: TimeclockCode
SetRequiredHours :: TimeclockCode
In :: TimeclockCode
Out :: TimeclockCode
FinalOut :: TimeclockCode
data TimeclockEntry
TimeclockEntry :: SourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> Text -> [Tag] -> TimeclockEntry
[tlsourcepos] :: TimeclockEntry -> SourcePos
[tlcode] :: TimeclockEntry -> TimeclockCode
[tldatetime] :: TimeclockEntry -> LocalTime
[tlaccount] :: TimeclockEntry -> AccountName
[tldescription] :: TimeclockEntry -> Text
[tlcomment] :: TimeclockEntry -> Text
[tltags] :: TimeclockEntry -> [Tag]
data Transaction
Transaction :: Integer -> Text -> (SourcePos, SourcePos) -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Transaction

-- | this transaction's 1-based position in the transaction stream, or 0
--   when not available
[tindex] :: Transaction -> Integer

-- | any comment lines immediately preceding this transaction
[tprecedingcomment] :: Transaction -> Text

-- | the file position where the date starts, and where the last posting
--   ends
[tsourcepos] :: Transaction -> (SourcePos, SourcePos)
[tdate] :: Transaction -> Day
[tdate2] :: Transaction -> Maybe Day
[tstatus] :: Transaction -> Status
[tcode] :: Transaction -> Text
[tdescription] :: Transaction -> Text

-- | this transaction's comment lines, as a single non-indented multi-line
--   string
[tcomment] :: Transaction -> Text

-- | tag names and values, extracted from the comment
[ttags] :: Transaction -> [Tag]

-- | this transaction's postings
[tpostings] :: Transaction -> [Posting]

-- | A transaction modifier rule. This has a query which matches postings
--   in the journal, and a list of transformations to apply to those
--   postings or their transactions. Currently there is one kind of
--   transformation: the TMPostingRule, which adds a posting ("auto
--   posting") to the transaction, optionally setting its amount to the
--   matched posting's amount multiplied by a constant.
data TransactionModifier
TransactionModifier :: Text -> [TMPostingRule] -> TransactionModifier
[tmquerytxt] :: TransactionModifier -> Text
[tmpostingrules] :: TransactionModifier -> [TMPostingRule]
type WeekDay = Int
data WhichDate
PrimaryDate :: WhichDate
SecondaryDate :: WhichDate
type YearDay = Int
type YearWeek = Int
type Year = Integer
tests_Data :: TestTree


-- | Options common to most hledger reports.
module Hledger.Reports.ReportOptions

-- | Standard options for customising report filtering and output. Most of
--   these correspond to standard hledger command-line options or query
--   arguments, but not all. Some are used only by certain commands, as
--   noted below.
data ReportOpts
ReportOpts :: 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
[period_] :: ReportOpts -> Period
[interval_] :: ReportOpts -> Interval

-- | Zero, one, or two statuses to be matched
[statuses_] :: ReportOpts -> [Status]

-- | Which operation should we apply to conversion transactions?
[conversionop_] :: ReportOpts -> Maybe ConversionOp

-- | What value should amounts be converted to ?
[value_] :: ReportOpts -> Maybe ValuationType

-- | Infer market prices from transactions ?
[infer_prices_] :: ReportOpts -> Bool

-- | <ul>
--   <li>-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.</li>
--   </ul>
[depth_] :: ReportOpts -> DepthSpec

-- | 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.
[fold_depth_] :: ReportOpts -> Maybe Int

-- | <ul>
--   <li>-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.</li>
--   </ul>
[no_elide_] :: ReportOpts -> Bool
[date2_] :: ReportOpts -> Bool
[empty_] :: ReportOpts -> Bool
[full_names_] :: ReportOpts -> Bool
[real_] :: ReportOpts -> Bool
[format_] :: ReportOpts -> StringFormat
[balance_base_url_] :: ReportOpts -> Maybe Text
[pretty_] :: ReportOpts -> Bool
[querystring_] :: ReportOpts -> [Text]
[average_] :: ReportOpts -> Bool
[related_] :: ReportOpts -> Bool
[sortspec_] :: ReportOpts -> SortSpec
[txn_dates_] :: ReportOpts -> Bool

-- | What to calculate in balance report cells
[balancecalc_] :: ReportOpts -> BalanceCalculation

-- | How to accumulate balance report values over time
[balanceaccum_] :: ReportOpts -> BalanceAccumulation

-- | A case-insensitive description substring to select periodic
--   transactions for budget reports. (Not a regexp, nor a full hledger
--   query, for now.)
[budgetpat_] :: ReportOpts -> Maybe Text
[accountlistmode_] :: ReportOpts -> AccountListMode
[drop_] :: ReportOpts -> Int

-- | Include accounts declared but not yet posted to ?
[declared_] :: ReportOpts -> Bool
[row_total_] :: ReportOpts -> Bool
[no_total_] :: ReportOpts -> Bool
[summary_only_] :: ReportOpts -> Bool

-- | Show costs for reports which normally don't show them ?
[show_costs_] :: ReportOpts -> Bool
[sort_amount_] :: ReportOpts -> Bool
[percent_] :: ReportOpts -> Bool

-- | Flip all amount signs in reports ?
[invert_] :: ReportOpts -> Bool

-- | This can be set when running balance reports on a set of accounts with
--   the same normal balance type (eg all assets, or all incomes). - It
--   helps --sort-amount know how to sort negative numbers (eg in the
--   income section of an income statement) - It helps compound balance
--   report commands (is, bs etc.) do sign normalisation, converting
--   normally negative subreports to normally positive for a more
--   conventional display.
[normalbalance_] :: ReportOpts -> Maybe NormalSign

-- | Whether to use ANSI color codes in text output. Influenced by the
--   --color/colour flag (cf CliOptions), whether stdout is an interactive
--   terminal, and the value of TERM and existence of NO_COLOR environment
--   variables.
[color_] :: ReportOpts -> Bool
[transpose_] :: ReportOpts -> Bool
[layout_] :: ReportOpts -> Layout
[period_titles_] :: ReportOpts -> 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_] :: ReportOpts -> Maybe 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_] :: ReportOpts -> Maybe Text

-- | Translations for the report's structural text (titles, headings, month
--   names), selected by --lang. English by default.
[translations_] :: ReportOpts -> Translations

-- | Lenses for ReportOpts.
class HasReportOptsNoUpdate c
reportOptsNoUpdate :: HasReportOptsNoUpdate c => Lens' c ReportOpts
accountlistmode :: HasReportOptsNoUpdate c => Lens' c AccountListMode
average :: HasReportOptsNoUpdate c => Lens' c Bool
balance_base_url :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
balanceaccum :: HasReportOptsNoUpdate c => Lens' c BalanceAccumulation
balancecalc :: HasReportOptsNoUpdate c => Lens' c BalanceCalculation
budgetpat :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
color__ :: HasReportOptsNoUpdate c => Lens' c Bool
conversionop :: HasReportOptsNoUpdate c => Lens' c (Maybe ConversionOp)
date2NoUpdate :: HasReportOptsNoUpdate c => Lens' c Bool
declared :: HasReportOptsNoUpdate c => Lens' c Bool
depthNoUpdate :: HasReportOptsNoUpdate c => Lens' c DepthSpec
drop__ :: HasReportOptsNoUpdate c => Lens' c Int
empty__ :: HasReportOptsNoUpdate c => Lens' c Bool
fold_depth :: HasReportOptsNoUpdate c => Lens' c (Maybe Int)
format :: HasReportOptsNoUpdate c => Lens' c StringFormat
full_names :: HasReportOptsNoUpdate c => Lens' c Bool
infer_prices :: HasReportOptsNoUpdate c => Lens' c Bool
interval :: HasReportOptsNoUpdate c => Lens' c Interval
invert :: HasReportOptsNoUpdate c => Lens' c Bool
layout :: HasReportOptsNoUpdate c => Lens' c Layout
no_elide :: HasReportOptsNoUpdate c => Lens' c Bool
no_total :: HasReportOptsNoUpdate c => Lens' c Bool
normalbalance :: HasReportOptsNoUpdate c => Lens' c (Maybe NormalSign)
percent :: HasReportOptsNoUpdate c => Lens' c Bool
periodNoUpdate :: HasReportOptsNoUpdate c => Lens' c Period
period_titles :: HasReportOptsNoUpdate c => Lens' c PeriodTitles
pretty :: HasReportOptsNoUpdate c => Lens' c Bool
querystringNoUpdate :: HasReportOptsNoUpdate c => Lens' c [Text]
realNoUpdate :: HasReportOptsNoUpdate c => Lens' c Bool
related :: HasReportOptsNoUpdate c => Lens' c Bool
row_total :: HasReportOptsNoUpdate c => Lens' c Bool
show_costs :: HasReportOptsNoUpdate c => Lens' c Bool
sort_amount :: HasReportOptsNoUpdate c => Lens' c Bool
sortspec :: HasReportOptsNoUpdate c => Lens' c SortSpec
statusesNoUpdate :: HasReportOptsNoUpdate c => Lens' c [Status]
subreport_titles :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
summary_only :: HasReportOptsNoUpdate c => Lens' c Bool
title__ :: HasReportOptsNoUpdate c => Lens' c (Maybe Text)
translations :: HasReportOptsNoUpdate c => Lens' c Translations
transpose__ :: HasReportOptsNoUpdate c => Lens' c Bool
txn_dates :: HasReportOptsNoUpdate c => Lens' c Bool
value :: HasReportOptsNoUpdate c => Lens' c (Maybe ValuationType)

-- | Special lenses for ReportOpts which also update the Query and
--   QueryOpts in ReportSpec. Note that these are not true lenses, as they
--   have a further restriction on the functor. This will work as a normal
--   lens for all common uses, but since they don't obey the lens laws for
--   some fancy cases, they may fail in some exotic circumstances.
--   
--   Note that setEither/overEither should only be necessary with
--   querystring and reportOpts: the other lenses should never fail.
--   
--   <h3>Examples:</h3>
--   
--   <pre>
--   &gt;&gt;&gt; import Lens.Micro (set)
--   
--   &gt;&gt;&gt; _rsQuery &lt;$&gt; setEither querystring ["assets"] defreportspec
--   Right (Acct (RegexpCI "assets"))
--   
--   &gt;&gt;&gt; _rsQuery &lt;$&gt; setEither querystring ["(assets"] defreportspec
--   Left "This regular expression is invalid or unsupported, please correct it: (assets"
--   
--   &gt;&gt;&gt; _rsQuery $ set querystring ["assets"] defreportspec
--   Acct (RegexpCI "assets")
--   
--   &gt;&gt;&gt; _rsQuery $ set period (MonthPeriod 2021 08) defreportspec
--   Date DateSpan 2021-08
--   </pre>
--   
--   XXX testing error output isn't working since adding color to it: &gt;
--   import System.Environment &gt; setEnv <a>NO_COLOR</a> "1" &gt;&gt;
--   return (_rsQuery $ set querystring ["(assets"] defreportspec) ***
--   Exception: Error: Updating ReportSpec failed: try using overEither
--   instead of over or setEither instead of set
class HasReportOptsNoUpdate a => HasReportOpts a
reportOpts :: HasReportOpts a => ReportableLens' a ReportOpts
period :: HasReportOpts a => ReportableLens' a Period
statuses :: HasReportOpts a => ReportableLens' a [Status]
depth :: HasReportOpts a => ReportableLens' a DepthSpec
date2 :: HasReportOpts a => ReportableLens' a Bool
real :: HasReportOpts a => ReportableLens' a Bool
querystring :: HasReportOpts a => ReportableLens' a [Text]

-- | A fully-determined set of report parameters (report options with all
--   partial values made total, eg the begin and end dates are known,
--   avoiding date/regex errors; plus the reporting date), and the query
--   successfully calculated from them.
--   
--   If you change the report options or date in one of these, you should
--   use <tt>reportOptsToSpec</tt> to regenerate the whole thing, avoiding
--   inconsistency.
data ReportSpec
ReportSpec :: ReportOpts -> Day -> Query -> Query -> [QueryOpt] -> ReportSpec

-- | The underlying ReportOpts used to generate this ReportSpec
[_rsReportOpts] :: ReportSpec -> ReportOpts

-- | The Day this ReportSpec is generated for
[_rsDay] :: ReportSpec -> Day

-- | The generated Query for the given day, except for any change:/balance:
--   terms
[_rsQuery] :: ReportSpec -> 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 <a>querySplitRowTerms</a>.
[_rsRowQuery] :: ReportSpec -> Query

-- | A list of QueryOpts for the given day
[_rsQueryOpts] :: ReportSpec -> [QueryOpt]
class HasReportSpec c
reportSpec :: HasReportSpec c => Lens' c ReportSpec
rsDay :: HasReportSpec c => Lens' c Day
rsQuery :: HasReportSpec c => Lens' c Query
rsQueryOpts :: HasReportSpec c => Lens' c [QueryOpt]
rsReportOpts :: HasReportSpec c => Lens' c ReportOpts
rsRowQuery :: HasReportSpec c => Lens' c Query
data SortField
AbsAmount' :: Bool -> SortField
Account' :: Bool -> SortField
Amount' :: Bool -> SortField
Date' :: Bool -> SortField
Description' :: Bool -> SortField
type SortSpec = [SortField]
sortKeysDescription :: [Char]

-- | Apply a function over a lens, but report on failure.
overEither :: ((a -> Either e b) -> s -> Either e t) -> (a -> b) -> s -> Either e t

-- | Set a field using a lens, but report on failure.
setEither :: ((a -> Either e b) -> s -> Either e t) -> b -> s -> Either e t

-- | What to calculate for each cell in a balance report. "Balance report
--   types -&gt; Calculation type" in the hledger manual.
data BalanceCalculation

-- | Sum of posting amounts in the period.
CalcChange :: BalanceCalculation

-- | Sum of posting amounts and the goal for the period.
CalcBudget :: BalanceCalculation

-- | Change from previous period's historical end value to this period's
--   historical end value.
CalcValueChange :: BalanceCalculation

-- | Change from previous period's gain, i.e. valuation minus cost basis.
CalcGain :: BalanceCalculation

-- | Number of postings in the period.
CalcPostingsCount :: BalanceCalculation

-- | Number of transactions in the period (exact only for a single account
--   row, eg at depth 0).
CalcTransactionsCount :: BalanceCalculation

-- | Does this calculation count postings or transactions, rather than
--   summing amounts ?
balanceCalcIsCount :: BalanceCalculation -> Bool

-- | How to accumulate calculated values across periods (columns) in a
--   balance report. "Balance report types -&gt; Accumulation type" in the
--   hledger manual.
data BalanceAccumulation

-- | No accumulation. Eg, shows the change of balance in each period.
PerPeriod :: BalanceAccumulation

-- | Accumulate changes across periods, starting from zero at report start.
Cumulative :: BalanceAccumulation

-- | Accumulate changes across periods, including any from before report
--   start. Eg, shows the historical end balance of each period.
Historical :: BalanceAccumulation

-- | Should accounts be displayed: in the command's default style,
--   hierarchically, or as a flat list ?
data AccountListMode
ALFlat :: AccountListMode
ALTree :: AccountListMode

-- | What kind of value conversion should be done on amounts ? CLI:
--   --value=then|end|now|DATE[,COMM]
data ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at each posting's date
AtThen :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   at period end(s)
AtEnd :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using current market
--   prices
AtNow :: Maybe CommoditySymbol -> ValuationType

-- | convert to default or given valuation commodity, using market prices
--   on some date
AtDate :: Day -> Maybe CommoditySymbol -> ValuationType
data Layout
LayoutWide :: Maybe Int -> Layout
LayoutTall :: Layout
LayoutBare :: Layout
LayoutBareWide :: Layout
LayoutTidy :: Layout

-- | How to render period column headings in periodic reports.
data PeriodTitles
PTCompact :: PeriodTitles
PTDates :: PeriodTitles

-- | 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 -> Text -> Text
defreportopts :: ReportOpts

-- | Generate a ReportOpts from raw command-line input, given a day and
--   whether to use ANSI colour/styles in standard output. This will fail
--   with a usage error if it is passed - an invalid --format argument, -
--   an invalid --value argument, - if --valuechange is called with a
--   valuation type other than -V/--value=end. - an invalid --pretty
--   argument,
rawOptsToReportOpts :: Day -> Bool -> RawOpts -> ReportOpts
defreportspec :: ReportSpec
defsortspec :: SortSpec

-- | Set the default ConversionOp.
setDefaultConversionOp :: ConversionOp -> ReportSpec -> ReportSpec

-- | Generate a ReportSpec from a set of ReportOpts on a given day.
reportOptsToSpec :: Day -> ReportOpts -> Either String ReportSpec

-- | Update the ReportOpts and the fields derived from it in a ReportSpec,
--   or return an error message if there is a problem such as missing or
--   unparseable options data. This is the safe way to change a ReportSpec,
--   ensuring that all fields (_rsQuery, _rsReportOpts, querystring_, etc.)
--   are in sync.
updateReportSpec :: ReportOpts -> ReportSpec -> Either String ReportSpec

-- | Like updateReportSpec, but takes a ReportOpts-modifying function.
updateReportSpecWith :: (ReportOpts -> ReportOpts) -> ReportSpec -> Either String ReportSpec

-- | Generate a ReportSpec from RawOpts and a provided day, or return an
--   error string if there are regular expression errors.
rawOptsToReportSpec :: Day -> Bool -> RawOpts -> Either String ReportSpec
balanceAccumulationOverride :: RawOpts -> Maybe BalanceAccumulation
flat_ :: ReportOpts -> Bool

-- | Legacy-compatible convenience aliases for accountlistmode_.
tree_ :: ReportOpts -> Bool

-- | Add/remove this status from the status list. Used by hledger-ui.
reportOptsToggleStatus :: Status -> ReportOpts -> ReportOpts

-- | Reduce a list of statuses to just one of each status, and if all
--   statuses are present return the empty list.
simplifyStatuses :: Ord a => [a] -> [a]

-- | Report which date we will report on based on --date2.
whichDate :: ReportOpts -> WhichDate

-- | Convert a <a>Journal'</a>s amounts to cost and/or to value (see
--   <a>journalApplyValuationFromOpts</a>), and filter by the
--   <a>ReportSpec</a> <a>Query</a>.
--   
--   We make sure to first filter by amt: and cur: terms, then value the
--   <a>Journal</a>, then filter by the remaining terms.
journalValueAndFilterPostings :: ReportSpec -> Journal -> Journal

-- | Like <a>journalValueAndFilterPostings</a>, but takes a
--   <a>PriceOracle</a> as an argument.
journalValueAndFilterPostingsWith :: ReportSpec -> Journal -> PriceOracle -> Journal

-- | Convert this journal's postings' amounts to cost and/or to value, if
--   specified by options (-B<i>--cost</i>-V<i>-X</i>--value etc.). Strip
--   prices if not needed. This should be the main stop for performing
--   costing and valuation. The exception is whenever you need to perform
--   valuation _after_ summing up amounts, as in a historical balance
--   report with --value=end. valuationAfterSum will check for this
--   condition.
journalApplyValuationFromOpts :: ReportSpec -> Journal -> Journal

-- | Like journalApplyValuationFromOpts, but takes PriceOracle as an
--   argument.
journalApplyValuationFromOptsWith :: ReportSpec -> Journal -> PriceOracle -> Journal

-- | Select the Account valuation functions required for performing
--   valuation after summing amounts. Used in MultiBalanceReport to value
--   historical and similar reports.
mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle -> Day -> MixedAmount -> MixedAmount

-- | If the ReportOpts specify that we are performing valuation after
--   summing amounts, return Just of the commodity symbol we're converting
--   to, Just Nothing for the default, and otherwise return Nothing. Used
--   for example with historical reports with --value=end.
valuationAfterSum :: ReportOpts -> Maybe (Maybe CommoditySymbol)

-- | If the ReportOpts specify that we will need to consider historical
--   postings, either because this is a historical report, or because the
--   valuation strategy requires historical amounts.
requiresHistorical :: ReportOpts -> Bool

-- | Get the report interval, if any, specified by the last of -p/--period,
--   -D<i>--daily, -W</i>--weekly, -M/--monthly etc. options. An interval
--   from --period counts only if it is explicitly defined.
intervalFromRawOpts :: RawOpts -> Interval

-- | Get the last interval specified in query opts, if any. date: queries
--   can specify a reporting interval.
intervalFromQueryOpts :: [QueryOpt] -> Maybe Interval

-- | Convert report options to a query, ignoring any non-flag command line
--   arguments.
queryFromFlags :: ReportOpts -> Query

-- | Select the Transaction date accessor based on --date2.
transactionDateFn :: ReportOpts -> Transaction -> Day

-- | Select the Posting date accessor based on --date2.
postingDateFn :: ReportOpts -> Posting -> Day

-- | The effective report span is the start and end dates requested by
--   options or queries. If the start date is unspecified, the earliest
--   transaction or posting date is used. If the end date is unspecified,
--   the latest transaction or posting date (or non-future market price
--   date, when doing an end value report) is used. If none of these things
--   are present, the null date span is returned. The report sub-periods
--   caused by a report interval, if any, are also returned.
reportSpan :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)

-- | Like reportSpan, but considers both primary and secondary dates, not
--   just one or the other.
reportSpanBothDates :: Journal -> ReportSpec -> (DateSpan, Maybe DayPartition)

-- | Like <a>reportSpan</a>, but returns the report periods as a lazily
--   generated list of <a>DateSpan</a>s rather than a <a>DayPartition</a>,
--   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
--   <a>maybeDayPartitionToDateSpans</a>.
reportSpanLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])

-- | Like <a>reportSpanLazy</a>, but considers both primary and secondary
--   dates. Used by the postings report.
reportSpanBothDatesLazy :: Journal -> ReportSpec -> (DateSpan, [DateSpan])
reportStartDate :: Journal -> ReportSpec -> Maybe Day
reportEndDate :: Journal -> ReportSpec -> Maybe Day
reportPeriodStart :: ReportSpec -> Maybe Day
reportPeriodOrJournalStart :: ReportSpec -> Journal -> Maybe Day
reportPeriodLastDay :: ReportSpec -> Maybe Day
reportPeriodOrJournalLastDay :: ReportSpec -> Journal -> Maybe Day

-- | Make a name for the given period in a multiperiod report, given the
--   type of balance being reported and the full set of report periods.
--   This will be used as a column heading (or row heading, in a register
--   summary report). We try to pick a useful name as follows:
--   
--   <ul>
--   <li>ending-balance reports: the period's end date</li>
--   <li>balance change reports where the periods are months and all in the
--   same year: the short month name, translated according to --lang</li>
--   <li>all other balance change reports: a description of the datespan,
--   abbreviated to compact form if possible (see showDateSpan).</li>
--   </ul>
reportPeriodName :: ReportOpts -> [DateSpan] -> DateSpan -> Text
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.AccountListMode
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.BalanceAccumulation
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.BalanceCalculation
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.PeriodTitles
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.ReportOpts
instance Data.Default.Internal.Default Hledger.Reports.ReportOptions.ReportSpec
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.BalanceAccumulation
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.BalanceCalculation
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.Layout
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.PeriodTitles
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportOptions.SortField
instance Hledger.Reports.ReportOptions.HasReportOptsNoUpdate Hledger.Reports.ReportOptions.ReportOpts
instance Hledger.Reports.ReportOptions.HasReportOptsNoUpdate Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.HasReportOpts Hledger.Reports.ReportOptions.ReportOpts
instance Hledger.Reports.ReportOptions.HasReportOpts Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.HasReportSpec Hledger.Reports.ReportOptions.ReportSpec
instance Hledger.Reports.ReportOptions.Reportable (GHC.Internal.Data.Functor.Const.Const r) e
instance (e GHC.Internal.Types.~ a) => Hledger.Reports.ReportOptions.Reportable (GHC.Internal.Data.Either.Either a) e
instance Hledger.Reports.ReportOptions.Reportable GHC.Internal.Data.Functor.Identity.Identity e
instance Hledger.Reports.ReportOptions.Reportable GHC.Internal.Maybe.Maybe e
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.BalanceAccumulation
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.BalanceCalculation
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.Layout
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.PeriodTitles
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.ReportOpts
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.ReportSpec
instance GHC.Internal.Show.Show Hledger.Reports.ReportOptions.SortField


-- | New common report types, used by the BudgetReport for now, perhaps all
--   reports later.
module Hledger.Reports.ReportTypes

-- | A periodic report is a generic tabular report, where each row
--   corresponds to some label (usually an account name) and each column to
--   a date period. The column periods are usually consecutive subperiods
--   formed by splitting the overall report period by some report interval
--   (daily, weekly, etc.). It has:
--   
--   <ol>
--   <li>a list of each column's period (date span)</li>
--   <li>a list of rows, each containing:</li>
--   </ol>
--   
--   <ul>
--   <li>an account label</li>
--   <li>the account's depth</li>
--   <li>A list of amounts, one for each column. Depending on the value
--   type, these can represent balance changes, ending balances, budget
--   performance, etc. (for example, see <tt>BalanceAccumulation</tt> and
--   <a>Hledger.Cli.Commands.Balance</a>).</li>
--   <li>the total of the row's amounts for a periodic report, or zero for
--   cumulative/historical reports (since summing end balances generally
--   doesn't make sense).</li>
--   <li>the average of the row's amounts</li>
--   </ul>
--   
--   <ol>
--   <li>the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.</li>
--   </ol>
data PeriodicReport a b
PeriodicReport :: [DateSpan] -> [PeriodicReportRow a b] -> PeriodicReportRow () b -> PeriodicReport a b
[prDates] :: PeriodicReport a b -> [DateSpan]
[prRows] :: PeriodicReport a b -> [PeriodicReportRow a b]
[prTotals] :: PeriodicReport a b -> PeriodicReportRow () b
data PeriodicReportRow a b
PeriodicReportRow :: a -> [b] -> b -> b -> PeriodicReportRow a b
[prrName] :: PeriodicReportRow a b -> a
[prrAmounts] :: PeriodicReportRow a b -> [b]
[prrTotal] :: PeriodicReportRow a b -> b
[prrAverage] :: PeriodicReportRow a b -> b
type Percentage = Decimal
type Change = MixedAmount
type Balance = MixedAmount
type Total = MixedAmount
type Average = MixedAmount

-- | Figure out the overall date span of a PeriodicReport
periodicReportSpan :: PeriodicReport a b -> DateSpan

-- | Map a function over the row names.
prMapName :: (a -> b) -> PeriodicReport a c -> PeriodicReport b c

-- | Map a function over the row names, possibly discarding some.
prMapMaybeName :: (a -> Maybe b) -> PeriodicReport a c -> PeriodicReport b c

-- | A compound balance report has:
--   
--   <ul>
--   <li>an overall title</li>
--   <li>the period (date span) of each column</li>
--   <li>one or more named, normal-positive multi balance reports, with
--   columns corresponding to the above, and a flag indicating whether they
--   increased or decreased the overall totals</li>
--   <li>a list of overall totals for each column, and their grand total
--   and average</li>
--   </ul>
--   
--   It is used in compound balance report commands like balancesheet,
--   cashflow and incomestatement.
data CompoundPeriodicReport a b
CompoundPeriodicReport :: Text -> [DateSpan] -> [(Text, PeriodicReport a b, Bool)] -> PeriodicReportRow () b -> CompoundPeriodicReport a b
[cbrTitle] :: CompoundPeriodicReport a b -> Text
[cbrDates] :: CompoundPeriodicReport a b -> [DateSpan]
[cbrSubreports] :: CompoundPeriodicReport a b -> [(Text, PeriodicReport a b, Bool)]
[cbrTotals] :: CompoundPeriodicReport a b -> PeriodicReportRow () b

-- | Description of one subreport within a compound balance report. Part of
--   a <a>CompoundBalanceCommandSpec</a>, but also used in hledger-lib.
data CBCSubreportSpec a
CBCSubreportSpec :: Text -> Query -> (ReportOpts -> ReportOpts) -> (PeriodicReport DisplayName MixedAmount -> PeriodicReport a MixedAmount) -> Bool -> CBCSubreportSpec a

-- | The title to use for the subreport
[cbcsubreporttitle] :: CBCSubreportSpec a -> Text

-- | The Query to use for the subreport
[cbcsubreportquery] :: CBCSubreportSpec a -> Query

-- | A function to transform the ReportOpts used to produce the subreport
[cbcsubreportoptions] :: CBCSubreportSpec a -> ReportOpts -> ReportOpts

-- | A function to transform the result of the subreport
[cbcsubreporttransform] :: CBCSubreportSpec a -> PeriodicReport DisplayName MixedAmount -> PeriodicReport a MixedAmount

-- | Whether the subreport and overall report total are of the same sign
--   (e.g. Assets are normally positive in a balance sheet report, as is
--   the overall total. Liabilities are normally of the opposite sign.)
[cbcsubreportincreasestotal] :: CBCSubreportSpec a -> Bool

-- | A full name, display name, and indent level for an account.
data DisplayName
DisplayName :: AccountName -> AccountName -> NumberOfIndents -> DisplayName
[displayFull] :: DisplayName -> AccountName
[displayName] :: DisplayName -> AccountName
[displayIndent] :: DisplayName -> NumberOfIndents

-- | Construct a display name for a list report, where full names are shown
--   unindented.
flatDisplayName :: AccountName -> DisplayName

-- | Construct a display name for a tree report, where leaf names (possibly
--   prefixed by boring parents) are shown indented).
treeDisplayName :: AccountName -> DisplayName
prrShowDebug :: PeriodicReportRow DisplayName MixedAmount -> String

-- | Get the full canonical account name from a PeriodicReportRow
--   containing a DisplayName.
prrFullName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the account display name from a PeriodicReportRow containing a
--   DisplayName.
prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the indent level from a PeriodicReportRow containing a
--   DisplayName.
prrIndent :: PeriodicReportRow DisplayName a -> Int

-- | Add two <tt>PeriodicReportRows</tt>, preserving the name of the first.
prrAdd :: Semigroup b => PeriodicReportRow a b -> PeriodicReportRow a b -> PeriodicReportRow a b
instance Data.Bifunctor.Bifunctor Hledger.Reports.ReportTypes.PeriodicReport
instance Data.Bifunctor.Bifunctor Hledger.Reports.ReportTypes.PeriodicReportRow
instance GHC.Internal.Classes.Eq Hledger.Reports.ReportTypes.DisplayName
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.CompoundPeriodicReport a)
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReport a)
instance GHC.Internal.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReportRow a)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance GHC.Internal.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance Hledger.Data.Types.HasAmounts b => Hledger.Data.Types.HasAmounts (Data.Text.Internal.Text, Hledger.Reports.ReportTypes.PeriodicReport a b, GHC.Internal.Types.Bool)
instance GHC.Internal.Classes.Ord Hledger.Reports.ReportTypes.DisplayName
instance GHC.Internal.Base.Semigroup b => GHC.Internal.Base.Semigroup (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance GHC.Internal.Show.Show Hledger.Reports.ReportTypes.DisplayName
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance (Data.Aeson.Types.ToJSON.ToJSON b, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Reports.ReportTypes.DisplayName
instance (Data.Aeson.Types.ToJSON.ToJSON b, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance (Data.Aeson.Types.ToJSON.ToJSON a, Data.Aeson.Types.ToJSON.ToJSON b) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReportRow a b)


-- | Postings report, used by the register command.
module Hledger.Reports.PostingsReport

-- | A postings report is a list of postings with a running total, and a
--   little extra transaction info to help with rendering. This is used eg
--   for the register command.
type PostingsReport = [PostingsReportItem]
type PostingsReportItem = (Maybe Day, Maybe Period, Maybe Text, Posting, MixedAmount)

-- | Select postings from the journal and add running balance and other
--   information to make a postings report. Used by eg hledger's register
--   command.
postingsReport :: ReportSpec -> Journal -> PostingsReport

-- | 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 -> Map AccountName MixedAmount

-- | Generate one postings report line item, containing the posting, the
--   current running balance, and optionally the posting date and/or the
--   transaction description.
mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Period -> Posting -> MixedAmount -> PostingsReportItem

-- | Based on the given report options, return a function that does the
--   appropriate running calculation for the register report, ie a running
--   average or running total. This function will take the item number,
--   previous average/total, and new posting amount, and return the new
--   average/total.
registerRunningCalculationFn :: ReportOpts -> Int -> MixedAmount -> MixedAmount -> MixedAmount
type SortSpec = [SortField]
defsortspec :: SortSpec
tests_PostingsReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.PostingsReport.PostingsReportItem


-- | Multi-column balance reports, used by the balance command.
module Hledger.Reports.MultiBalanceReport

-- | A multi balance report is a kind of periodic report, where the amounts
--   correspond to balance changes or ending balances in a given period. It
--   has:
--   
--   <ol>
--   <li>a list of each column's period (date span)</li>
--   <li>a list of rows, each containing:</li>
--   </ol>
--   
--   <ul>
--   <li>the full account name, display name, and display depth</li>
--   <li>A list of amounts, one for each column.</li>
--   <li>the total of the row's amounts for a periodic report</li>
--   <li>the average of the row's amounts</li>
--   </ul>
--   
--   <ol>
--   <li>the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.</li>
--   </ol>
type MultiBalanceReport = PeriodicReport DisplayName MixedAmount
type MultiBalanceReportRow = PeriodicReportRow DisplayName MixedAmount

-- | Generate a multicolumn balance report for the matched accounts,
--   showing the change of balance, accumulated balance, or historical
--   balance in each of the specified periods. If the normalbalance_ option
--   is set, it adjusts the sorting and sign of amounts (see ReportOpts and
--   CompoundBalanceCommand). hledger's most powerful and useful report,
--   used by the balance command (in multiperiod mode) and (via
--   compoundBalanceReport) by the bs<i>cf</i>is commands.
multiBalanceReport :: ReportSpec -> Journal -> MultiBalanceReport

-- | A helper for multiBalanceReport. This one takes some extra arguments,
--   a <a>PriceOracle</a> to be used for looking up market prices, and a
--   set of <a>AccountName</a>s which should not be elided. Commands which
--   run multiple reports (bs etc.) can generate the price oracle just once
--   for efficiency, passing it to each report by calling this function
--   directly.
multiBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> MultiBalanceReport

-- | Generate a compound balance report from a list of CBCSubreportSpec.
--   This shares postings between the subreports.
compoundBalanceReport :: ReportSpec -> Journal -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount

-- | A helper for compoundBalanceReport, similar to multiBalanceReportWith.
compoundBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount

-- | Remove any date queries and insert queries from the report span. The
--   user's query expanded to the report span if there is one (otherwise
--   any date queries are left as-is, which handles the hledger-ui+future
--   txns case above).
makeReportQuery :: ReportSpec -> DateSpan -> ReportSpec

-- | 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 -> Map CommoditySymbol AmountStyle

-- | Gather postings matching the query within the report period.
getPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting]

-- | 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
--   <a>getPostings</a>); 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] -> Map AccountName (MixedAmount, MixedAmount)

-- | Generate the <a>Account</a> for the requested multi-balance report
--   from a list of <a>Posting</a>s.
generateMultiBalanceAccount :: ReportSpec -> Journal -> PriceOracle -> Maybe DayPartition -> [Posting] -> Account BalanceData

-- | Lay out a set of postings grouped by date span into a regular matrix
--   with rows given by AccountName and columns by DateSpan, then generate
--   a MultiBalanceReport from the columns.
generatePeriodicReport :: Show c => (forall a. () => ReportOpts -> (BalanceData -> MixedAmount) -> a -> Account b -> PeriodicReportRow a c) -> (b -> MixedAmount) -> (c -> MixedAmount) -> ReportOpts -> Maybe DayPartition -> Account b -> PeriodicReport DisplayName c

-- | Build a report row.
--   
--   Calculate the column totals. These are always the sum of column
--   amounts.
makePeriodicReportRow :: c -> (Map Day c -> (c, c)) -> ReportOpts -> (b -> c) -> a -> Account b -> PeriodicReportRow a c

-- | 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 -> Map Day c -> c
tests_MultiBalanceReport :: TestTree
instance GHC.Internal.Base.Semigroup Hledger.Reports.MultiBalanceReport.RowAmounts


-- | Journal entries report, used by the print command.
module Hledger.Reports.EntriesReport

-- | A journal entries report is a list of whole transactions as originally
--   entered in the journal (mostly). This is used by eg hledger's print
--   command and hledger-web's journal entries view.
type EntriesReport = [EntriesReportItem]
type EntriesReportItem = Transaction

-- | Select transactions for an entries report, sorted by date.
entriesReport :: ReportSpec -> Journal -> EntriesReport

-- | 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
--   <a>transactionBalancingSum</a>), regardless of valuation and --invert.
entriesReportUnsorted :: ReportSpec -> Journal -> EntriesReport
tests_EntriesReport :: TestTree

module Hledger.Reports.BudgetReport
type BudgetGoal = Change
type BudgetTotal = Total
type BudgetAverage = Average

-- | A budget report tracks expected and actual changes per account and
--   subperiod. Each table cell has an actual change amount and/or a budget
--   goal amount.
type BudgetCell = (Maybe Change, Maybe BudgetGoal)

-- | A row in a budget report table - account name and data cells.
type BudgetReportRow = PeriodicReportRow DisplayName BudgetCell

-- | A full budget report table.
type BudgetReport = PeriodicReport DisplayName BudgetCell

-- | Calculate per-account, per-period budget (balance change) goals from
--   all periodic transactions, calculate actual balance changes from the
--   regular transactions, and compare these to get a <a>BudgetReport</a>.
--   Unbudgeted accounts may be hidden or renamed (see
--   journalWithBudgetAccountNames).
budgetReport :: ReportSpec -> BalancingOpts -> DateSpan -> Journal -> BudgetReport
tests_BudgetReport :: TestTree


-- | Balance report, used by the balance command.
module Hledger.Reports.BalanceReport

-- | A simple balance report. It has:
--   
--   <ol>
--   <li>a list of items, one per account, each containing:</li>
--   </ol>
--   
--   <ul>
--   <li>the full account name</li>
--   <li>the Ledger-style elided short account name (the leaf account name,
--   prefixed by any boring parents immediately above); or with --flat, the
--   full account name again</li>
--   <li>the number of indentation steps for rendering a Ledger-style
--   account tree, taking into account elided boring parents, --no-elide
--   and --flat</li>
--   <li>an amount</li>
--   </ul>
--   
--   <ol>
--   <li>the total of all amounts</li>
--   </ol>
type BalanceReport = ([BalanceReportItem], MixedAmount)
type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount)

-- | Enabling this makes balance --flat --empty also show parent accounts
--   without postings, in addition to those with postings and a zero
--   balance. Disabling it shows only the latter. No longer supported, but
--   leave this here for a bit. flatShowsPostinglessAccounts = True
--   
--   Generate a simple balance report, containing the matched accounts and
--   their balances (change of balance) during the specified period. If the
--   normalbalance_ option is set, it adjusts the sorting and sign of
--   amounts (see ReportOpts and CompoundBalanceCommand).
balanceReport :: ReportSpec -> Journal -> BalanceReport

-- | When true (the default), this makes balance --flat reports and their
--   implementation clearer. Single/multi-col balance reports currently
--   aren't all correct if this is false.
flatShowsExclusiveBalance :: Bool
tests_BalanceReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.BalanceReport.BalanceReportItem


-- | An account-centric transactions report.
module Hledger.Reports.AccountTransactionsReport

-- | An account transactions report represents transactions affecting a
--   particular account (or possibly several accounts, but we don't use
--   that). It is used eg by hledger-ui's and hledger-web's register view,
--   and hledger's aregister report, where we want to show one row per
--   transaction, in the context of the current account. Report items
--   consist of:
--   
--   <ul>
--   <li>the transaction, unmodified</li>
--   <li>the transaction as seen in the context of the current account and
--   query, which means:</li>
--   <li>the transaction date is set to the "transaction context date": the
--   earliest of the transaction date and any other posting dates of
--   postings to the current account (matched by the report query).</li>
--   <li>the transaction's postings are filtered, excluding any which are
--   not matched by the report query</li>
--   <li>a text description of the other account(s) posted to/from</li>
--   <li>a flag indicating whether there's more than one other account
--   involved</li>
--   <li>the total increase/decrease to the current account</li>
--   <li>the report transactions' running total after this transaction; or
--   if historical balance is requested (-H), the historical running total;
--   or if average is requested (-A), the running average change per
--   transaction (also including transactions before the report start date,
--   with -H). The historical running total includes transactions from
--   before the report start date if one is specified, filtered by the
--   report query. The historical running total may or may not be the
--   account's historical running balance, depending on the report
--   query.</li>
--   </ul>
--   
--   Items are sorted by transaction register date (the earliest date the
--   transaction posts to the current account), most recent first.
--   Reporting intervals are currently ignored.
type AccountTransactionsReport = [AccountTransactionsReportItem]
type AccountTransactionsReportItem = (Transaction, Transaction, Bool, [AccountName], MixedAmount, MixedAmount)
accountTransactionsReport :: ReportSpec -> Journal -> Query -> AccountTransactionsReport

-- | 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)

-- | Generate transactions report items from a list of transactions, using
--   the provided user-specified report query, the report query's
--   change:/balance: terms (selecting items by their change to the
--   account, or the account's real balance after them; hidden items still
--   count in the running total), a query specifying which account to use
--   as the focus, a running calculation function (see
--   registerRunningCalculationFn), the starting item number, the running
--   total/average and the real balance before the first item, and a
--   sign-setting function. Each transaction is accompanied by the date
--   that should be shown for it in the report. This is not necessarily the
--   transaction date - see transactionRegisterDate.
accountTransactionsReportItems :: Query -> Query -> Query -> (Int -> MixedAmount -> MixedAmount -> MixedAmount) -> Int -> MixedAmount -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem]

-- | What date should be shown for a transaction in an account register
--   report ? This will be in context of a particular account (the "this
--   account" query) and any additional report query. It could be:
--   
--   <ul>
--   <li>if postings are matched by both thisacctq and reportq, the
--   earliest of those matched postings' dates (or their secondary dates if
--   --date2 was used)</li>
--   <li>the transaction date, or its secondary date if --date2 was
--   used.</li>
--   </ul>
transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day

-- | Like <a>transactionRegisterDate</a>, 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
triOrigTransaction :: (a, b, c, d, e, f) -> a
triDate :: (a, Transaction, c, d, e, f) -> Day
triAmount :: (a, b, c, d, e, f) -> e
triBalance :: (a, b, c, d, e, f) -> f
triCommodityAmount :: CommoditySymbol -> (a, b, c, d, MixedAmount, f) -> MixedAmount
triCommodityBalance :: CommoditySymbol -> (a, b, c, d, e, MixedAmount) -> MixedAmount

-- | Split an account transactions report whose items may involve several
--   commodities, into one or more single-commodity account transactions
--   reports.
accountTransactionsReportByCommodity :: AccountTransactionsReport -> [(CommoditySymbol, AccountTransactionsReport)]

-- | Remove account transaction report items and item amount (and running
--   balance amount) components that don't involve the specified commodity.
--   Other item fields such as the transaction are left unchanged.
filterAccountTransactionsReportByCommodity :: CommoditySymbol -> AccountTransactionsReport -> AccountTransactionsReport
tests_AccountTransactionsReport :: TestTree
instance Hledger.Data.Types.HasAmounts Hledger.Reports.AccountTransactionsReport.AccountTransactionsReportItem


-- | Generate several common kinds of report from a journal, as "*Report" -
--   simple intermediate data structures intended to be easily rendered as
--   text, html, json, csv etc. by hledger commands, hamlet templates,
--   javascript, or whatever.
module Hledger.Reports
tests_Reports :: TestTree


-- | File reading/parsing utilities used by multiple readers, and a good
--   amount of the parsers for journal format, to avoid import cycles when
--   JournalReader imports other readers.
--   
--   Some of these might belong in Hledger.Read.JournalReader or
--   Hledger.Read.
module Hledger.Read.Common

-- | 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 :: Type -> Type)
Reader :: StorageFormat -> [String] -> (InputOpts -> FilePath -> Handle -> ExceptT String IO Journal) -> (MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal) -> Reader (m :: Type -> Type)
[rFormat] :: Reader (m :: Type -> Type) -> StorageFormat
[rExtensions] :: Reader (m :: Type -> Type) -> [String]
[rReadFn] :: Reader (m :: Type -> Type) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
[rParser] :: Reader (m :: Type -> Type) -> MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal

-- | 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 :: forall (m :: Type -> Type). Reader m -> Bool

-- | 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 <a>accountNameApplyModifiers</a>). Any error,
--   including an IO error, is rethrown as a final parse error showing the
--   include file stack.
includeFileParser :: forall (m :: Type -> Type). MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal

-- | 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
data InputOpts
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

-- | a file/storage format to try, unless overridden by a filename prefix.
--   Nothing means try all.
[mformat_] :: InputOpts -> Maybe StorageFormat

-- | a conversion rules file to use (when reading CSV)
[mrules_file_] :: InputOpts -> Maybe FilePath

-- | account name aliases to apply
[aliases_] :: InputOpts -> [String]

-- | do light obfuscation of the data ? Now corresponds to --obfuscate, not
--   the old --anon flag.
[anon_] :: InputOpts -> Bool

-- | read only new transactions since this file was last read ?
[new_] :: InputOpts -> Bool

-- | save latest new transactions state for next time ?
[new_save_] :: InputOpts -> Bool

-- | use the given field's value as the account name
[pivot_] :: InputOpts -> String

-- | span in which to generate forecast transactions
[forecast_] :: InputOpts -> Maybe DateSpan

-- | add user-visible tags when generating/modifying transactions &amp;
--   postings ?
[verbose_tags_] :: InputOpts -> Bool

-- | a dirty hack keeping the query dates in InputOpts. This rightfully
--   lives in ReportSpec, but is duplicated here.
[reportspan_] :: InputOpts -> DateSpan

-- | generate extra postings according to auto posting rules ?
[auto_] :: InputOpts -> Bool

-- | infer equity conversion postings from costs ?
[infer_equity_] :: InputOpts -> Bool

-- | infer costs from equity conversion postings ? distinct from
--   BalancingOpts{infer_balancing_costs_}
[infer_costs_] :: InputOpts -> Bool

-- | skip lot tracking and its checks, silencing lot errors ? (basic lot
--   inference still runs, leniently, so lot entries balance)
[ignore_lots_] :: InputOpts -> Bool

-- | options for transaction balancing
[balancingopts_] :: InputOpts -> BalancingOpts

-- | do extra correctness checks ?
[strict_] :: InputOpts -> Bool

-- | internal flag: postpone checks, because we are processing multiple
--   files ?
[_defer] :: InputOpts -> Bool

-- | internal flag: is this the <tt>import</tt> command reading its data
--   files ? Enables the CSV rules reader's import-specific behaviour:
--   preferring the oldest file matched by a <tt>source</tt> glob, and
--   honouring the <tt>archive</tt> rule. Set by <tt>importcmd</tt>; other
--   reads should leave it off.
[_importing] :: InputOpts -> Bool

-- | internal flag: is this a <tt>import --dry-run</tt> command ? If set,
--   the CSV rules reader will never archive or remove a data file.
[_dryrun] :: InputOpts -> 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.
[_scanfiles] :: InputOpts -> 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.
[_forecastOnlyForDisplay] :: InputOpts -> Bool

-- | today's date, for use with forecast transactions XXX this duplicates
--   _rsDay, and should eventually be removed when it's not needed anymore.
[_ioDay] :: InputOpts -> Day

-- | parse with the old timeclock pairing rules?
[_oldtimeclock] :: InputOpts -> Bool

-- | The main journal file's directory. Used eg by the CSV rules reader to
--   locate the journal's <tt>data/</tt> directory. Set by the CLI entry
--   points <tt>withJournal</tt>, <tt>withPossibleJournal</tt>, and
--   <tt>journalReload</tt>. If you do a further <tt>readJournalFile</tt> /
--   <tt>readJournalFiles</tt> call after a journal has been loaded (eg as
--   <tt>import</tt> does), apply <a>inputOptsSetJournalDir</a> to its
--   <a>InputOpts</a> so the CSV rules reader can find the right
--   <tt>data/</tt>. Otherwise, the CSV rules reader falls back to the
--   rules file's own directory.
[_journaldir] :: InputOpts -> Maybe FilePath

-- | internal: replacement content for some files, keyed by canonical path
--   (see <a>canonicalizePath</a>), 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 <tt>journalCheckChange</tt>
--   in hledger's Hledger.Cli.Utils).
[_fileoverrides] :: InputOpts -> Map FilePath Text
class HasInputOpts c
inputOpts :: HasInputOpts c => Lens' c InputOpts
aliases :: HasInputOpts c => Lens' c [String]
anon__ :: HasInputOpts c => Lens' c Bool
auto__ :: HasInputOpts c => Lens' c Bool
balancingopts :: HasInputOpts c => Lens' c BalancingOpts
defer :: HasInputOpts c => Lens' c Bool
dryrun :: HasInputOpts c => Lens' c Bool
fileoverrides :: HasInputOpts c => Lens' c (Map FilePath Text)
forecast :: HasInputOpts c => Lens' c (Maybe DateSpan)
forecastOnlyForDisplay :: HasInputOpts c => Lens' c Bool
ignore_lots :: HasInputOpts c => Lens' c Bool
importing :: HasInputOpts c => Lens' c Bool
infer_costs :: HasInputOpts c => Lens' c Bool
infer_equity :: HasInputOpts c => Lens' c Bool
ioDay :: HasInputOpts c => Lens' c Day
journaldir :: HasInputOpts c => Lens' c (Maybe FilePath)
mformat :: HasInputOpts c => Lens' c (Maybe StorageFormat)
mrules_file :: HasInputOpts c => Lens' c (Maybe FilePath)
new__ :: HasInputOpts c => Lens' c Bool
new_save :: HasInputOpts c => Lens' c Bool
oldtimeclock :: HasInputOpts c => Lens' c Bool
pivot :: HasInputOpts c => Lens' c String
reportspan :: HasInputOpts c => Lens' c DateSpan
scanfiles :: HasInputOpts c => Lens' c Bool
strict :: HasInputOpts c => Lens' c Bool
verbose_tags :: HasInputOpts c => Lens' c Bool
definputopts :: InputOpts

-- | 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
handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal

-- | 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

-- | Given a parser to ParsedJournal, input options, file path and content:
--   run the parser on the content. This is all steps of
--   <a>parseAndFinaliseJournal</a> 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
journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal

-- | 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 &amp; end date for generated periodic transactions are
--   determined in a somewhat complicated way; see the hledger manual -&gt;
--   Periodic transactions.
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal

-- | 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

-- | 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 <a>_forecastOnlyForDisplay</a>). Also used by
--   hledger-ui to recheck the rules in memory.
journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()
setYear :: forall (m :: Type -> Type). Year -> JournalParser m ()
getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year)

-- | 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 <a>ParsePos</a>), 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' :: forall (m :: Type -> Type). JournalParser m SourcePos
setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m ()
getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle))

-- | Get amount style associated with default currency.
--   
--   Returns <a>AmountStyle</a> used to defined by a latest default
--   commodity directive prior to current position within this file or its
--   parents.
getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle)

-- | Get the <a>AmountStyle</a> 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 :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle)

-- | The amount style implied by a decimal-mark directive or CSV rule in
--   effect, if any.
journalDecimalMarkStyle :: Journal -> Maybe AmountStyle

-- | The <a>AmountStyle</a> 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

-- | 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 :: forall (m :: Type -> Type). Text -> JournalParser m Text

-- | 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 :: forall (m :: Type -> Type). AmountStyle -> JournalParser m AmountStyle
addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m ()
addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m ()
pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m ()
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName
addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
getAccountAliases :: MonadState Journal m => m [AccountAlias]
journalAddFile :: JournalFile -> Journal -> Journal
statusp :: forall (m :: Type -> Type). TextParser m Status
codep :: forall (m :: Type -> Type). TextParser m Text

-- | Parse possibly empty text until a semicolon or newline. Whitespace is
--   preserved (for now - perhaps helps preserve alignment of same-line
--   comments ?).
descriptionp :: forall (m :: Type -> Type). TextParser m Text

-- | 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 :: forall (m :: Type -> Type). JournalParser m Day

-- | 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 :: forall (m :: Type -> Type). JournalParser m LocalTime

-- | Parse a time of day (HH:MM[:SS]), and skip any time zone suffix (like
--   +0100) following it.
timeofdayp :: forall (m :: Type -> Type). TextParser m TimeOfDay
secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day

-- | 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
--   <a>accountNameApplyModifiers</a>, 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 :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName

-- | Parse an account name like modifiedaccountnamep, but apply only the
--   alias directives, not the parent account prefix or --alias options
--   (see <a>accountNameApplyModifiers</a>).
aliasedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName

-- | Add the parent account prefix to an account name (with alias
--   directives already applied), then apply the --alias options (see
--   <a>accountNameApplyModifiers</a>). This calls error if an --alias
--   option has an invalid regular expression.
applyParentAndOptionAliases :: forall (m :: Type -> Type). AccountName -> JournalParser m AccountName

-- | 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:
--   
--   <ol>
--   <li>alias directives and account directives' alias: tags (kept in
--   <a>jparsealiases</a>), 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.</li>
--   <li>the parent account from apply account directives
--   (<a>jparseparentaccounts</a>), prepended.</li>
--   <li>--alias options (<a>jparseoptaliases</a>), 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.</li>
--   </ol>
--   
--   The code is split up because of a few special cases:
--   
--   <ul>
--   <li>The parsers apply these in two parts: <a>aliasedaccountnamep</a>
--   does step 1, and <a>applyParentAndOptionAliases</a> does steps 2 and
--   3. Normally both are used (<a>modifiedaccountnamep</a>). 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.</li>
--   <li>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.</li>
--   <li>Entries from included CSV/rules files get steps 1 and 3, but not 2
--   (<a>includeFileParser</a>). (Included timeclock/timedot files are
--   parsed with <a>modifiedaccountnamep</a>, so they get all three.)</li>
--   <li>When a non-journal file is read directly, <a>jparseoptaliases</a>
--   is empty, and its reader applies step 3 itself after parsing.</li>
--   </ul>
accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName

-- | 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 :: forall (m :: Type -> Type). TextParser m AccountName
accountnamenosemicolonp :: forall (m :: Type -> Type). TextParser m AccountName

-- | 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 :: forall (m :: Type -> Type). TextParser m AccountName
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias

-- | Parse whitespace then an amount, or return the special "missing"
--   marker amount.
spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount

-- | 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
--   
--   <ul>
--   <li>AMT -- releasing an amount</li>
--   <li>AMT SELLPRICE -- releasing an amount at some selling price</li>
--   <li>AMT SELLPRICE COSTBASISSEL -- releasing a lot at some selling
--   price, selecting it by its cost basis</li>
--   <li>AMT COSTBASISSEL SELLPRICE -- like the above</li>
--   <li>AMT COSTBASISSEL -- like the above with selling price same as the
--   selected lot's cost basis amount</li>
--   </ul>
--   
--   COST/SELLPRICE can be <tt> UNITAMT, </tt><tt> TOTALAMT, (</tt>)
--   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:
--   
--   <ol>
--   <li>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</li>
--   <li>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)</li>
--   <li>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.)</li>
--   </ol>
amountp :: forall (m :: Type -> Type). JournalParser m Amount

-- | 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

-- | 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.
OrdinaryAmount :: AmountParseKind

-- | A multiplier in an auto posting rule (*AMT). The default commodity is
--   not applied to it. Otherwise it's parsed like an OrdinaryAmount.
MultiplierAmount :: AmountParseKind

-- | 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.
StyleAmount :: AmountParseKind
amountp' :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount

-- | 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 :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
simpleamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol

-- | Ledger-style cost notation: <tt> UNITAMT, </tt><tt> TOTALAMT, (</tt>)
--   UNITAMT, or (@@) TOTALAMT. The () are ignored. The amount can be an
--   amount expression (see amountexprp) (#2857).
costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost
balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion
lotcostp :: forall (m :: Type -> Type). Quantity -> JournalParser m CostBasis

-- | 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
--   <a>http://en.wikipedia.org/wiki/Decimal_separator</a> 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 :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)

-- | 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)

-- | 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.
--   
--   <pre>
--   &gt;&gt;&gt; parseTest rawnumberp "1,234,567.89"
--   Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
--   
--   &gt;&gt;&gt; parseTest rawnumberp "1,000"
--   Left (AmbiguousNumber "1" ',' "000")
--   
--   &gt;&gt;&gt; parseTest rawnumberp "1 000"
--   Right (WithSeparators ' ' ["1","000"] Nothing)
--   
--   &gt;&gt;&gt; parseTest rawnumberp "1'000"
--   Right (WithSeparators '\'' ["1","000"] Nothing)
--   
--   &gt;&gt;&gt; parseTest rawnumberp "1_000"
--   Right (WithSeparators '_' ["1","000"] Nothing)
--   </pre>
rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber)

-- | 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)

-- | Some kinds of number literal we might parse.
data RawNumber

-- | 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)
NoSeparators :: DigitGrp -> Maybe (Char, DigitGrp) -> RawNumber

-- | A number with identifiable digit group marks (eg 1,000,000 or 1,000.50
--   or 1 000)
WithSeparators :: Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber

-- | 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 -> AmbiguousNumber

-- | Description of a single digit group in a number literal.
--   <a>Thousands</a> is one well known digit grouping, but there are
--   others.
data DigitGrp
DigitGrp :: Word -> Integer -> DigitGrp

-- | The number of digits in this group. This is Word to avoid the need to
--   do overflow checking for the Semigroup instance of DigitGrp.
[digitGroupLength] :: DigitGrp -> Word

-- | The natural number formed by this group's digits. This should always
--   be positive.
[digitGroupNumber] :: DigitGrp -> Integer
isDigitSeparatorChar :: Char -> Bool

-- | Try to parse a single-commodity amount from a string
parseamount :: String -> Either HledgerParseErrors Amount

-- | 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 :: Map CommoditySymbol AmountStyle -> String -> Either HledgerParseErrors Amount

-- | Parse a single-commodity amount from a string, or get an error.
parseamount' :: String -> Amount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount' :: String -> MixedAmount

-- | Is this a character that, as the first non-whitespace on a line,
--   starts a comment line ?
isLineCommentStart :: Char -> Bool

-- | Is this a character that, appearing anywhere within a line, starts a
--   comment ?
isSameLineCommentStart :: Char -> Bool
multilinecommentp :: forall (m :: Type -> Type). TextParser m ()

-- | 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 :: forall (m :: Type -> Type). TextParser m ()

-- | 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 :: forall (m :: Type -> Type). [Char] -> TextParser m ()

-- | Parse a comment following a journal item, possibly continued on
--   multiple lines, and return the comment text.
--   
--   <pre>
--   &gt;&gt;&gt; rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   &gt;&gt;&gt; rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   &gt;&gt;&gt; rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   &gt;&gt;&gt; rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   &gt;&gt;&gt; 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"
--   </pre>
followingcommentp :: forall (m :: Type -> Type). TextParser m Text

-- | 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<i>1</i>1 ; a transaction comment starting on the same line ... ;
--   extending to the next line account1 $1 account2
--   
--   Tags are name-value pairs.
--   
--   <pre>
--   &gt;&gt;&gt; let getTags (_,tags) = tags
--   
--   &gt;&gt;&gt; let parseTags = fmap getTags . rtp transactioncommentp
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   </pre>
--   
--   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 :: forall (m :: Type -> Type). TextParser m (Text, [Tag])
commentlinetagsp :: forall (m :: Type -> Type). TextParser m [Tag]

-- | 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<i>1</i>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.
--   
--   <pre>
--   &gt;&gt;&gt; let getTags (_,tags,_,_) = tags
--   
--   &gt;&gt;&gt; let parseTags = fmap getTags . rtp (postingcommentp Nothing)
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   </pre>
--   
--   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.
--   
--   <pre>
--   &gt;&gt;&gt; let getDates (_,_,d1,d2) = (d1, d2)
--   
--   &gt;&gt;&gt; let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseDates "; date: 1/2, date2: 1999/12/31"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   
--   &gt;&gt;&gt; parseDates "; [1/2=1999/12/31]"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   </pre>
--   
--   Example: tags, date tags, and bracketed dates &gt;&gt;&gt; rtp
--   (postingcommentp (Just 2000)) "; a:b, date:3<i>4, [=5</i>6]" Right
--   ("a:b, date:3<i>4, [=5</i>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
--   &gt;&gt;&gt; rtp (postingcommentp (Just 2000)) "; date:3<i>4=5</i>6"
--   Right ("date:3<i>4=5</i>6n",[("date","3<i>4=5</i>6")],Just
--   2000-03-04,Nothing)
--   
--   Example: date tags with empty values set no date &gt;&gt;&gt; rtp
--   (postingcommentp (Just 2000)) "; date:, date2: , a:b" Right ("date:,
--   date2: , a:bn",[("date",""),("date2",""),("a","b")],Nothing,Nothing)
postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)

-- | 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.
--   
--   <pre>
--   &gt;&gt;&gt; either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
--   Right [("date",2016-01-02),("date2",2016-03-04)]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"
--   Left ...not a bracketed date...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"
--   Left ...1:2:...This is not a valid date...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; 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...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
--   Left ...1:13:...expecting month or day...
--   </pre>
bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)]

-- | Parse a single line of possibly empty text enclosed in double quotes.
doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse possibly empty text, including whitespace, until a comment start
--   (semicolon) or newline.
noncommenttextp :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty text, including whitespace, until a comment start
--   (semicolon) or newline.
noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, until a double space or newline.
singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, until a comment start (semicolon), double space, or
--   newline.
singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text

-- | Parse non-empty, single-spaced text starting and ending with
--   non-whitespace, where all characters satisfy the given predicate.
singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text

-- | 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 :: forall (m :: Type -> Type). TextParser m ()
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()

-- | 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]
tests_Common :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Read.Common.AmbiguousNumber
instance GHC.Internal.Classes.Eq Hledger.Read.Common.AmountParseKind
instance GHC.Internal.Classes.Eq Hledger.Read.Common.DigitGrp
instance GHC.Internal.Classes.Eq Hledger.Read.Common.RawNumber
instance GHC.Internal.Base.Monoid Hledger.Read.Common.DigitGrp
instance GHC.Internal.Base.Semigroup Hledger.Read.Common.DigitGrp
instance GHC.Internal.Show.Show Hledger.Read.Common.AmbiguousNumber
instance GHC.Internal.Show.Show Hledger.Read.Common.AmountParseKind
instance GHC.Internal.Show.Show Hledger.Read.Common.DigitGrp
instance GHC.Internal.Show.Show Hledger.Read.Common.RawNumber
instance GHC.Internal.Show.Show (Hledger.Read.Common.Reader m)


-- | A reader for the "timedot" file format. Example:
--   
--   <pre>
--   ;DATE
--   ;ACCT  DOTS  # Each dot represents 15m, spaces are ignored
--   ;ACCT  8    # numbers with or without a following h represent hours
--   ;ACCT  5m   # numbers followed by m represent minutes
--   
--   ; on 2/1, 1h was spent on FOSS haskell work, 0.25h on research, etc.
--   2/1
--   fos.haskell   .... ..
--   biz.research  .
--   inc.client1   .... .... .... .... .... ....
--   
--   2/2
--   biz.research  .
--   inc.client1   .... .... ..
--   </pre>
module Hledger.Read.TimedotReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m
timedotfilep :: forall {m :: Type -> Type}. InputOpts -> JournalParser m ParsedJournal


-- | A reader for the timeclock file format.
--   
--   What exactly is this format ? It was introduced in timeclock.el
--   (<a>http://www.emacswiki.org/emacs/TimeClock</a>). The old
--   specification in timeclock.el 2.6 was:
--   
--   <pre>
--   A timeclock contains data in the form of a single entry per line.
--   Each entry has the form:
--   
--     CODE YYYY<i>MM</i>DD HH:MM:SS [COMMENT]
--   
--   CODE is one of: b, h, i, o or O.  COMMENT is optional when the code is
--   i, o or O.  The meanings of the codes are:
--   
--     b  Set the current time balance, or "time debt".  Useful when
--        archiving old log data, when a debt must be carried forward.
--        The COMMENT here is the number of seconds of debt.
--   
--     h  Set the required working time for the given day.  This must
--        be the first entry for that day.  The COMMENT in this case is
--        the number of hours in this workday.  Floating point amounts
--        are allowed.
--   
--     i  Clock in.  The COMMENT in this case should be the name of the
--        project worked on.
--   
--     o  Clock out.  COMMENT is unnecessary, but can be used to provide
--        a description of how the period went, for example.
--   
--     O  Final clock out.  Whatever project was being worked on, it is
--        now finished.  Useful for creating summary reports.
--   </pre>
--   
--   Ledger's timeclock format is different, and hledger's timeclock format
--   is different again. For example: in a clock-in entry, after the time,
--   
--   <ul>
--   <li>timeclock.el's timeclock has 0-1 fields: [COMMENT]</li>
--   <li>Ledger's timeclock has 0-2 fields: [ACCOUNT[ PAYEE]]</li>
--   <li>hledger's timeclock has 1-3 fields: ACCOUNT[
--   DESCRIPTION[;COMMENT]]</li>
--   </ul>
--   
--   hledger's timeclock format is:
--   
--   <pre>
--   # Comment lines like these, and blank lines, are ignored:
--   # comment line
--   ; comment line
--   * comment line
--   
--   # Lines beginning with b, h, or capital O are also ignored, for compatibility:
--   b SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   h SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   O SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]
--   
--   # Lines beginning with i or o are are clock-in / clock-out entries:
--   i SIMPLEDATE HH:MM[:SS][+-ZZZZ] ACCOUNT[  DESCRIPTION][;COMMENT]]
--   o SIMPLEDATE HH:MM[:SS][+-ZZZZ][ ACCOUNT][;COMMENT]
--   </pre>
--   
--   The date is a hledger <a>simple date</a> (YYYY-MM-DD or similar). The
--   time parts must use two digits. The seconds are optional. A + or -
--   four-digit time zone is accepted for compatibility, but currently
--   ignored; times are always interpreted as a local time.
--   
--   In clock-in entries (<tt>i</tt>), the account name is required. A
--   transaction description, separated from the account name by 2+ spaces,
--   is optional. A transaction comment, beginning with `;`, is also
--   optional.
--   
--   In clock-out entries (<tt>o</tt>) have no description, but can have a
--   comment if you wish. A clock-in and clock-out pair form a
--   "transaction" posting some number of hours to an account - also known
--   as a session. Eg:
--   
--   ```timeclock i 2015<i>03</i>30 09:00:00 session1 o 2015<i>03</i>30
--   10:00:00 ```
--   
--   ```cli $ hledger -f a.timeclock print 2015-03-30 * 09:00-10:00
--   (session1) 1.00h ```
--   
--   Clock-ins and clock-outs are matched by their account/session name. If
--   a clock-outs does not specify a name, the most recent unclosed
--   clock-in is closed. Also, sessions spanning more than one day are
--   automatically split at day boundaries. Eg, the following time log:
--   
--   ```timeclock i 2015<i>03</i>30 09:00:00 some account optional
--   description after 2 spaces ; optional comment, tags: o 2015<i>03</i>30
--   09:20:00 i 2015<i>03</i>31 22:21:45 another:account o 2015<i>04</i>01
--   02:00:34 i 2015<i>04</i>02 12:00:00 another:account ; this
--   demonstrates multple sessions being clocked in i 2015<i>04</i>02
--   13:00:00 some account o 2015<i>04</i>02 14:00:00 o 2015<i>04</i>02
--   15:00:00 another:account ```
--   
--   generates these transactions:
--   
--   ```cli $ hledger -f t.timeclock print 2015-03-30 * optional
--   description after 2 spaces ; optional comment, tags: (some account)
--   0.33h
--   
--   2015-03-31 * 22:21-23:59 (another:account) 1.64h
--   
--   2015-04-01 * 00:00-02:00 (another:account) 2.01h
--   
--   2015-04-02 * 12:00-15:00 ; this demonstrates multiple sessions being
--   clocked in (another:account) 3.00h
--   
--   2015-04-02 * 13:00-14:00 (some account) 1.00h
--   
--   ```
module Hledger.Read.TimeclockReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m
timeclockfilep :: forall (m :: Type -> Type). MonadIO m => InputOpts -> JournalParser m ParsedJournal


-- | A reader for a CSV rules file. This reads the actual data from a file
--   specified by a <tt>source</tt> rule or from a similarly-named file in
--   the same directory.
--   
--   Most of the code for reading rules files and csv files is in this
--   module.
module Hledger.Read.RulesReader
reader :: forall (m :: Type -> Type). MonadIO m => Reader m

-- | Given a rules file path, what would be the corresponding data file ?
--   (Remove a .rules extension.)
dataFileFor :: FilePath -> Maybe FilePath

-- | Given a csv file path, what would be the corresponding rules file ?
--   (Add a .rules extension.)
rulesFileFor :: FilePath -> FilePath

-- | 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

-- | 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])

-- | Read the encoding specified by the <tt>encoding</tt> rule, if any. Or
--   throw an error if an unrecognised encoding is specified.
rulesEncoding :: FilePath -> CsvRules -> ExceptT String IO (Maybe DynEncoding)

-- | Read a Journal from the given CSV data (and filename, used for error
--   messages), or return an error. Proceed as follows:
--   
--   <ol>
--   <li>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.</li>
--   <li>Parse the CSV data using the rules, or throw an error.</li>
--   <li>Convert the CSV records to hledger transactions using the
--   rules.</li>
--   <li>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.</li>
--   </ol>
readJournalFromCsv :: FilePath -> CsvRules -> FilePath -> Text -> Maybe SepFormat -> ExceptT String IO (Journal, String -> String)

-- | Like <a>readJournalFromCsv</a>, but returns an unfinalised journal
--   ready for <a>journalFinalise</a>: 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)

-- | 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)
tests_RulesReader :: TestTree
instance GHC.Internal.Classes.Eq Hledger.Read.RulesReader.ConditionalBlock
instance GHC.Internal.Classes.Eq Hledger.Read.RulesReader.CsvRules
instance GHC.Internal.Classes.Eq Hledger.Read.RulesReader.FieldAssignment
instance GHC.Internal.Classes.Eq Hledger.Read.RulesReader.Matcher
instance GHC.Internal.Classes.Eq Hledger.Read.RulesReader.MatcherPrefix
instance Text.Megaparsec.Error.ShowErrorComponent GHC.Internal.Base.String
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.ConditionalBlock
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.CsvRules
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.FieldAssignment
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.Matcher
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.MatcherPrefix
instance GHC.Internal.Show.Show Hledger.Read.RulesReader.TemplateExpr


-- | A reader for CSV (character-separated) data. This also reads a rules
--   file to help interpret the CSV data.
module Hledger.Read.CsvReader
reader :: forall (m :: Type -> Type). MonadIO m => SepFormat -> Reader m
tests_CsvReader :: TestTree


-- | A reader for hledger's journal file format
--   (<a>http://hledger.org/hledger.html#the-journal-file</a>). hledger's
--   journal format is a compatible subset of c++ ledger's
--   (<a>http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format</a>), so
--   this reader should handle many ledger files as well. Example:
--   
--   <pre>
--   2012/3/24 gift
--       expenses:gifts  $10
--       assets:cash
--   </pre>
--   
--   Journal format supports the include directive which can read files in
--   other formats, so the other file format readers need to be importable
--   and invocable here.
--   
--   Some important parts of journal parsing are therefore kept in
--   Hledger.Read.Common, to avoid import cycles.
module Hledger.Read.JournalReader

-- | <pre>
--   findReader mformat mpath
--   </pre>
--   
--   Find the reader named by <tt>mformat</tt>, 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 :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | Separate a file path and its reader prefix, if any.
--   
--   <pre>
--   &gt;&gt;&gt; splitReaderPrefix "csv:-"
--   (Just csv,"-")
--   </pre>
splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)
reader :: forall (m :: Type -> Type). MonadIO m => Reader m

-- | 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

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)

-- | Run a journal parser in some monad. See also: parseWithState.
rjp :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
runErroringJournalParser :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either HledgerParseErrors a))

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName

-- | A journal parser. Accumulates and returns a <a>ParsedJournal</a>,
--   which should be finalised/validated before use.
--   
--   <pre>
--   &gt;&gt;&gt; rejp (journalp definputopts &lt;* eof) "2015/1/1\n a  0\n"
--   Right (Right Journal (unknown) with 1 transactions, 1 accounts)
--   </pre>
journalp :: forall (m :: Type -> Type). MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal

-- | Parse any journal directive and update the parse state accordingly,
--   and record it as a journal item (exported or not by print --export).
--   Cf <a>http://hledger.org/hledger.html#directives</a>,
--   <a>http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives</a>
directivep :: forall (m :: Type -> Type). MonadIO m => InputOpts -> ErroringJournalParser m ()
defaultyeardirectivep :: forall (m :: Type -> Type). JournalParser m ()
marketpricedirectivep :: forall (m :: Type -> Type). JournalParser m PriceDirective

-- | 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 :: forall (m :: Type -> Type). JournalParser m LocalTime

-- | 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 :: forall (m :: Type -> Type). JournalParser m Day

-- | 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
--   <a>accountNameApplyModifiers</a>, 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 :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName
tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule
statusp :: forall (m :: Type -> Type). TextParser m Status

-- | 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 :: forall (m :: Type -> Type). TextParser m ()

-- | Parse a comment following a journal item, possibly continued on
--   multiple lines, and return the comment text.
--   
--   <pre>
--   &gt;&gt;&gt; rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   &gt;&gt;&gt; rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   &gt;&gt;&gt; rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   &gt;&gt;&gt; rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   &gt;&gt;&gt; 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"
--   </pre>
followingcommentp :: forall (m :: Type -> Type). TextParser m Text
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias

-- | 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
tests_JournalReader :: TestTree


-- | This is the entry point to hledger's reading system, which can read
--   Journals from various data formats. Use this module if you want to
--   parse journal data or read journal files. Generally it should not be
--   necessary to import modules below this one.
--   
--   <h2>Journal reading</h2>
--   
--   Reading an input file (in journal, csv, timedot, or timeclock
--   format..) involves these steps:
--   
--   <ul>
--   <li>select an appropriate file format "reader" based on filename
--   extension<i>file path prefix</i>function parameter. A reader contains
--   a parser and a finaliser (usually <tt>journalFinalise</tt>).</li>
--   <li>run the parser to get a ParsedJournal (this may run additional
--   sub-parsers to parse included files)</li>
--   <li>run the finaliser to get a complete Journal, which passes standard
--   checks</li>
--   <li>if reading multiple files: merge the per-file Journals into one
--   overall Journal</li>
--   <li>if using -s/--strict: run additional strict checks</li>
--   <li>if running print --new: save .latest files for each input file.
--   (import also does this, as its final step.)</li>
--   </ul>
--   
--   <h2>Journal merging</h2>
--   
--   Journal implements the Semigroup class, so two Journals can be merged
--   into one Journal with <tt>j1 &lt;&gt; j2</tt>. This is implemented by
--   the <tt>journalConcat</tt> function, whose documentation explains what
--   merging Journals means exactly.
--   
--   <h2>Journal finalising</h2>
--   
--   This is post-processing done after parsing an input file, such as
--   inferring missing information, normalising amount styles, checking for
--   errors and so on - a delicate and influential stage of data
--   processing. In hledger it is done by <tt>journalFinalise</tt>, which
--   converts a preliminary ParsedJournal to a validated, ready-to-use
--   Journal. This is called immediately after the parsing of each input
--   file. It is not called when Journals are merged.
--   
--   <h2>Journal reading API</h2>
--   
--   There are three main Journal-reading functions:
--   
--   <ul>
--   <li>readJournal to read from a Text value. Selects a reader and calls
--   its parser and finaliser, then does strict checking if needed.</li>
--   <li>readJournalFile to read one file, or stdin if the file path is
--   <tt>-</tt>. Uses the file path/file name to help select the reader,
--   calls readJournal, then writes .latest files if needed.</li>
--   <li>readJournalFiles to read multiple files. Calls readJournalFile for
--   each file (without strict checking or .latest file writing) then
--   merges the Journals into one, then does strict checking and .latest
--   file writing at the end if needed.</li>
--   </ul>
--   
--   Each of these also has an easier variant with ' suffix, which uses
--   default options and has a simpler type signature.
--   
--   One more variant, <tt>readJournalFilesAndLatestDates</tt>, is like
--   readJournalFiles but exposing the latest transaction date (and how
--   many on the same day) seen for each file. This is used by the import
--   command.
module Hledger.Read

-- | Read the default journal file specified by the environment, with
--   default input options, or raise an error.
defaultJournal :: IO Journal

-- | Like defaultJournal, but return an error message instead of raising an
--   error.
defaultJournalSafely :: IO (Either String Journal)

-- | Like defaultJournal, but use the given input options.
defaultJournalWith :: InputOpts -> IO Journal

-- | Like defaultJournalWith, but return an error message instead of
--   raising an error.
defaultJournalWithSafely :: InputOpts -> IO (Either String Journal)

-- | Get the default journal file path - either $LEDGER_FILE or
--   $HOME/.hledger.journal file.
--   
--   This looks for the LEDGER_FILE environment variable, like Ledger. The
--   value should be a file path, possibly with ~ at the start meaning the
--   current user's home directory. Or the value can be a glob pattern
--   (containing *, ?, [ or {) ), in which case the first matching file
--   path is used. When it's a glob pattern that matches no existing files,
--   an error is raised.
--   
--   If LEDGER_FILE is unset or set to the empty string, this returns a
--   default file path: <tt>.hledger.journal</tt> in the user's home
--   directory, or if we can't find the user's home directory, in the
--   current directory.
--   
--   The referenced file can be nonexistent.
defaultJournalPath :: IO String

-- | Like defaultJournalPath, but return an error message instead of
--   raising an error.
defaultJournalPathSafely :: IO (Either String String)

-- | Like defaultJournalPath, but also checks that the file exists, and
--   raises an error if it doesn't.
defaultExistingJournalPath :: IO String

-- | Like defaultExistingJournalPath, but returns an error message instead
--   of raising an error.
defaultExistingJournalPathSafely :: IO (Either String String)

-- | If the specified journal file does not exist (and is not "-"), call
--   error with an informative message. (Using "journal file" generically
--   here; it could be in any of hledger's supported formats.)
requireJournalFileExists :: FilePath -> IO ()

-- | Ensure there is a journal file at the given path, creating an empty
--   one if needed. On Windows, also ensure that the path contains no
--   trailing dots which could cause data loss (see
--   <a>isWindowsUnsafeDotPath</a>).
ensureJournalFileExists :: FilePath -> IO ()
journalEnvVar :: String
journalDefaultFilename :: FilePath
runExceptT :: ExceptT e m a -> m (Either e a)

-- | <pre>
--   readJournal iopts mfile txt
--   </pre>
--   
--   Read a Journal from some handle, with strict checks if enabled, or
--   return an error message.
--   
--   The reader (data format) is chosen based on, in this order:
--   
--   <ul>
--   <li>a reader name provided in <tt>iopts</tt></li>
--   <li>a reader prefix in the <tt>mfile</tt> path</li>
--   <li>a file extension in <tt>mfile</tt></li>
--   </ul>
--   
--   If none of these is available, or if the reader name is unrecognised,
--   the journal reader is used.
--   
--   If a file path is not provided, "-" is assumed (and may appear in
--   error messages, <tt>files</tt> output etc, where it will be a slight
--   lie: it will mean "not from a file", not necessarily "from standard
--   input".
readJournal :: InputOpts -> Maybe FilePath -> Handle -> ExceptT String IO Journal

-- | Read a Journal from this file, or from stdin if the file path is -,
--   with strict checks if enabled, or return an error message. XXX or,
--   calls error if the file does not exist.
--   
--   (Note strict checks are disabled temporarily here when this is called
--   by readJournalFiles). The file path can have a READER: prefix.
--   
--   The reader (data format) to use is determined from (in priority
--   order): the <tt>mformat_</tt> specified in the input options, if any;
--   the file path's READER: prefix, if any; a recognised file name
--   extension. if none of these identify a known reader, the journal
--   reader is used.
--   
--   The input options can also configure balance assertion checking,
--   automated posting generation, a rules file for converting CSV data,
--   etc.
--   
--   If using --new, and if latest-file writing is enabled in input
--   options, and not deferred by readJournalFiles, and after passing
--   strict checks if enabled, a .latest.FILE file will be created/updated
--   (for the main file only, not for included files), to remember the
--   latest transaction date processed.
readJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal

-- | Like readJournalFile, but if the file does not exist, returns an empty
--   journal with the file path set. This is useful for commands like add
--   and import that need to work with a potentially non-existent journal
--   file.
readPossibleJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal

-- | Like readJournalFiles, but if the first file does not exist, provides
--   an empty journal with that file path set. Other files must exist as
--   normal. This is useful for commands like add and import that write to
--   the first file, which might not exist yet, while also reading other
--   files for completions etc.
readPossibleJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal

-- | Read a Journal from each specified file path (using
--   <tt>readJournalFile</tt>) and combine them into one; or return the
--   first error message.
--   
--   Combining Journals means concatenating them, basically. The parse
--   state resets at the start of each file, which means that directives
--   &amp; aliases do not affect subsequent sibling or parent files. They
--   do affect included child files though. Also the final parse state
--   saved in the Journal does span all files.
--   
--   Strict checks, if enabled, are temporarily deferred until all files
--   are read, to ensure they see the whole journal, and/or to avoid
--   redundant work. (Some checks, like assertions and ordereddates, might
--   still be doing redundant work ?)
--   
--   Writing .latest files, if enabled, is also deferred till the end, and
--   is done only if strict checks pass.
readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal
readJournalFilesAndLatestDates :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO (Journal, [LatestDatesForFile])

-- | An easy version of <a>readJournal</a> which assumes default options,
--   and fails in the IO monad.
readJournal' :: Handle -> IO Journal

-- | An even easier version of readJournal' which takes a <a>Text</a>
--   instead of a <a>Handle</a>.
readJournal'' :: Text -> IO Journal

-- | An easy version of <a>readJournalFile</a> which assumes default
--   options, and fails in the IO monad.
readJournalFile' :: PrefixedFilePath -> IO Journal

-- | An easy version of <a>readJournalFiles'</a> which assumes default
--   options, and fails in the IO monad.
readJournalFiles' :: [PrefixedFilePath] -> IO Journal

-- | Extract ExceptT to the IO monad, failing with an error message if
--   necessary.
orDieTrying :: MonadIO m => ExceptT String m a -> m a

-- | Does any part of this path contain non-. characters and end with a . ?
--   Such paths are not safe to use on Windows (cf #1056).
isWindowsUnsafeDotPath :: FilePath -> Bool
tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule

-- | 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

-- | <pre>
--   findReader mformat mpath
--   </pre>
--   
--   Find the reader named by <tt>mformat</tt>, 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 :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | Separate a file path and its reader prefix, if any.
--   
--   <pre>
--   &gt;&gt;&gt; splitReaderPrefix "csv:-"
--   (Just csv,"-")
--   </pre>
splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)
tests_Read :: TestTree


-- | This is the root of the <tt>hledger-lib</tt> package and the
--   <tt>Hledger.*</tt> module hierarchy. hledger-lib is the core engine
--   used by various hledger UIs and tools, providing the main data types,
--   file format parsers, reporting logic, and utilities.
--   
--   SPDX-License-Identifier: GPL-3.0-or-later Copyright (c) 2007-2025
--   (each year in this range) Simon Michael <a>simon@joyful.com</a> and
--   contributors.
--   
--   This program is free software: you can redistribute it and/or modify
--   it under the terms of the GNU General Public License as published by
--   the Free Software Foundation, either version 3 of the License, or (at
--   your option) any later version.
--   
--   This program is distributed in the hope that it will be useful, but
--   WITHOUT ANY WARRANTY; without even the implied warranty of
--   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
--   General Public License for more details. You should have received a
--   copy of the GNU General Public License along with this program. If
--   not, see <a>https://www.gnu.org/licenses/</a>.
module Hledger
tests_Hledger :: TestTree
