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

-- | A reusable library providing the core functionality of hledger
--   
--   A reusable library containing hledger's core functionality. This is
--   used by most hledger* packages so that they support the same common
--   file formats, command line options, reports etc.
--   
--   hledger is a robust, cross-platform set of tools for tracking money,
--   time, or any other commodity, using double-entry accounting and a
--   simple, editable file format, with command-line, terminal and web
--   interfaces. It is a Haskell rewrite of Ledger, and one of the leading
--   implementations of Plain Text Accounting. Read more at:
--   https://hledger.org
@package hledger-lib
@version 1.19.1

-- | Basic color helpers for prettifying console output.
module Hledger.Utils.Color

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

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

-- | ANSI's eight standard colors. They come in two intensities, which are
--   controlled by ColorIntensity. Many terminals allow the colors
--   of the standard palette to be customised, so that, for example,
--   setSGR [ SetColor Foreground Vivid Green ] may not result in
--   bright green characters.
data Color
Black :: Color
Red :: Color
Green :: Color
Yellow :: Color
Blue :: Color
Magenta :: Color
Cyan :: Color
White :: Color

-- | ANSI's standard colors come in two intensities
data ColorIntensity
Dull :: ColorIntensity
Vivid :: ColorIntensity

module Hledger.Utils.Tree

-- | An efficient-to-build tree suggested by Cale Gibbard, probably better
--   than accountNameTreeFrom.
newtype FastTree a
T :: Map a (FastTree a) -> FastTree a
treeFromPaths :: Ord a => [[a]] -> FastTree a
instance GHC.Classes.Ord a => GHC.Classes.Ord (Hledger.Utils.Tree.FastTree a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Hledger.Utils.Tree.FastTree a)
instance GHC.Show.Show a => GHC.Show.Show (Hledger.Utils.Tree.FastTree a)

-- | UTF-8 aware string IO functions that will work across multiple
--   platforms and GHC versions. Includes code from Text.Pandoc.UTF8 ((C)
--   2010 John MacFarlane).
--   
--   Example usage:
--   
--   import Prelude hiding
--   (readFile,writeFile,appendFile,getContents,putStr,putStrLn) import
--   UTF8IOCompat
--   (readFile,writeFile,appendFile,getContents,putStr,putStrLn) import
--   UTF8IOCompat
--   (SystemString,fromSystemString,toSystemString,error',userError')
--   
--   2013410 update: we now trust that current GHC versions &
--   platforms do the right thing, so this file is a no-op and on its way
--   to being removed. Not carefully tested.
--   
--   20191020 update: all packages have base>=4.9 which
--   corresponds to GHC v8.0.1 and higher. Tear this file apart!
module Hledger.Utils.UTF8IOCompat

-- | The readFile function reads a file and returns the contents of
--   the file as a string. The file is read lazily, on demand, as with
--   getContents.
readFile :: FilePath -> IO String

-- | The computation writeFile file str function writes the
--   string str, to the file file.
writeFile :: FilePath -> String -> IO ()

-- | The computation appendFile file str function appends
--   the string str, to the file file.
--   
--   Note that writeFile and appendFile write a literal
--   string to a file. To write a value of any printable type, as with
--   print, use the show function to convert the value to a
--   string first.
--   
--   
--   main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
--   
appendFile :: FilePath -> String -> IO ()

-- | The getContents operation returns all user input as a single
--   string, which is read lazily as it is needed (same as
--   hGetContents stdin).
getContents :: IO String

-- | Computation hGetContents hdl returns the list of
--   characters corresponding to the unread portion of the channel or file
--   managed by hdl, which is put into an intermediate state,
--   semi-closed. In this state, hdl is effectively closed,
--   but items are read from hdl on demand and accumulated in a
--   special list returned by hGetContents hdl.
--   
--   Any operation that fails because a handle is closed, also fails if a
--   handle is semi-closed. The only exception is hClose. A
--   semi-closed handle becomes closed:
--   
--   
--   
- if hClose is applied to it;
--   
- if an I/O error occurs when reading an item from the handle;
--   
- or once the entire contents of the handle has been read.
--   
--   
--   Once a semi-closed handle becomes closed, the contents of the
--   associated list becomes fixed. The contents of this final list is only
--   partially specified: it will contain at least all the items of the
--   stream that were evaluated prior to the handle becoming closed.
--   
--   Any I/O errors encountered while a handle is semi-closed are simply
--   discarded.
--   
--   This operation may fail with:
--   
--   
--   
- isEOFError if the end of file has been reached.
--   
hGetContents :: Handle -> IO String

-- | Write a string to the standard output device (same as hPutStr
--   stdout).
putStr :: String -> IO ()

-- | The same as putStr, but adds a newline character.
putStrLn :: String -> IO ()

-- | Computation hPutStr hdl s writes the string s
--   to the file or channel managed by hdl.
--   
--   This operation may fail with:
--   
--   
--   
- isFullError if the device is full; or
--   
- isPermissionError if another system resource limit would be
--   exceeded.
--   
hPutStr :: Handle -> String -> IO ()

-- | The same as hPutStr, but adds a newline character.
hPutStrLn :: Handle -> String -> IO ()

-- | A SystemString-aware version of error.
error' :: String -> a

-- | A SystemString-aware version of userError.
userError' :: String -> IOError

-- | A SystemString-aware version of error that adds a usage hint.
usageError :: String -> a

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

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

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

-- | An regular expression compilation/processing error message.
type RegexError = String

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

-- | A memoising version of regexReplace. Caches the result for each search
--   pattern, replacement pattern, target string tuple.
regexReplace :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String
regexReplaceAllBy :: Regexp -> (String -> String) -> String -> String
instance GHC.Classes.Eq Hledger.Utils.Regex.Regexp
instance GHC.Classes.Ord Hledger.Utils.Regex.Regexp
instance GHC.Show.Show Hledger.Utils.Regex.Regexp
instance GHC.Read.Read Hledger.Utils.Regex.Regexp
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Utils.Regex.Regexp
instance Text.Regex.Base.RegexLike.RegexLike Hledger.Utils.Regex.Regexp GHC.Base.String
instance Text.Regex.Base.RegexLike.RegexContext Hledger.Utils.Regex.Regexp GHC.Base.String GHC.Base.String

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

-- | A possibly incomplete year-month-day date provided by the user, to be
--   interpreted as either a date or a date span depending on context.
--   Missing parts "on the left" will be filled from the provided reference
--   date, e.g. if the year and month are missing, the reference date's
--   year and month are used. Missing parts "on the right" are assumed,
--   when interpreting as a date, to be 1, (e.g. if the year and month are
--   present but the day is missing, it means first day of that month); or
--   when interpreting as a date span, to be a wildcard (so it would mean
--   all days of that month). See the smartdate parser for more
--   examples.
--   
--   Or, one of the standard periods and an offset relative to the
--   reference date: (last|this|next) (day|week|month|quarter|year), where
--   "this" means the period containing the reference date.
data SmartDate
SmartAssumeStart :: Year -> Maybe (Month, Maybe MonthDay) -> SmartDate
SmartFromReference :: Maybe Month -> MonthDay -> SmartDate
SmartMonth :: Month -> SmartDate
SmartRelative :: SmartSequence -> SmartInterval -> SmartDate
data SmartSequence
Last :: SmartSequence
This :: SmartSequence
Next :: SmartSequence
data SmartInterval
Day :: SmartInterval
Week :: SmartInterval
Month :: SmartInterval
Quarter :: SmartInterval
Year :: SmartInterval
data WhichDate
PrimaryDate :: WhichDate
SecondaryDate :: WhichDate
data DateSpan
DateSpan :: Maybe Day -> Maybe Day -> DateSpan
type Year = Integer
type Month = Int
type Quarter = Int
type YearWeek = Int
type MonthWeek = Int
type YearDay = Int
type MonthDay = Int
type WeekDay = Int
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
data Interval
NoInterval :: Interval
Days :: Int -> Interval
Weeks :: Int -> Interval
Months :: Int -> Interval
Quarters :: Int -> Interval
Years :: Int -> Interval
DayOfMonth :: Int -> Interval
WeekdayOfMonth :: Int -> Int -> Interval
DayOfWeek :: Int -> Interval
DayOfYear :: Int -> Int -> Interval
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
data AccountAlias
BasicAlias :: AccountName -> AccountName -> AccountAlias
RegexAlias :: Regexp -> Replacement -> AccountAlias
data Side
L :: Side
R :: Side

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

-- | An amount's per-unit or total cost/selling price in another commodity,
--   as recorded in the journal entry eg with  or @. Docs call
--   this "transaction price". The amount is always positive.
data AmountPrice
UnitPrice :: Amount -> AmountPrice
TotalPrice :: Amount -> AmountPrice

-- | Display style for an amount.
data AmountStyle
AmountStyle :: Side -> Bool -> !AmountPrecision -> Maybe Char -> Maybe DigitGroupStyle -> AmountStyle

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

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

-- | number of digits displayed after the decimal point
[asprecision] :: AmountStyle -> !AmountPrecision

-- | character used as decimal point: period or comma. Nothing means
--   "unspecified, use default"
[asdecimalpoint] :: AmountStyle -> Maybe Char

-- | style for displaying digit groups, if any
[asdigitgroups] :: AmountStyle -> Maybe DigitGroupStyle
data AmountPrecision
Precision :: !Word8 -> AmountPrecision
NaturalPrecision :: AmountPrecision

-- | A style for displaying digit groups in the integer part of a floating
--   point number. It consists of the character used to separate groups
--   (comma or period, whichever is not used as decimal point), and the
--   size of each group, starting with the one nearest the decimal point.
--   The last group size is assumed to repeat. Eg, comma between thousands
--   is DigitGroups ',' [3].
data DigitGroupStyle
DigitGroups :: Char -> [Word8] -> DigitGroupStyle
type CommoditySymbol = Text
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle
data Amount
Amount :: CommoditySymbol -> Quantity -> Bool -> AmountStyle -> Maybe AmountPrice -> Amount
[acommodity] :: Amount -> CommoditySymbol
[aquantity] :: Amount -> Quantity

-- | kludge: a flag marking this amount and posting as a multiplier in a
--   TMPostingRule. In a regular Posting, should always be false.
[aismultiplier] :: Amount -> Bool
[astyle] :: Amount -> AmountStyle

-- | the (fixed, transaction-specific) price for this amount, if any
[aprice] :: Amount -> Maybe AmountPrice
newtype MixedAmount
Mixed :: [Amount] -> MixedAmount
data PostingType
RegularPosting :: PostingType
VirtualPosting :: PostingType
BalancedVirtualPosting :: PostingType
type TagName = Text
type TagValue = Text
type Tag = (TagName, TagValue) " A tag name and (possibly empty) value."
type DateTag = (TagName, Day)

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

-- | 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.
--   
--   The BalanceAssertion type is also used to represent balance
--   assignments, which instruct hledger what an account's balance should
--   become at a certain point.
--   
--   Different kinds of balance assertions are discussed eg on #290.
--   Variables include:
--   
--   
--   
- which postings are to be summed (realvirtual;
--   unmarkedpendingcleared; this accountthis account including
--   subs)
--   
- which commodities within the balance are to be checked
--   
- whether to do a partial or a total check (disallowing other
--   commodities)
--   
--   
--   I suspect we want:
--   
--   
--   
- partial, subaccount-exclusive, Ledger-compatible assertions.
--   Because they're what we've always had, and removing them would break
--   some journals unnecessarily. Implemented with = syntax.
--   
- total assertions. Because otherwise assertions are a bit leaky.
--   Implemented with == syntax.
--   
- subaccount-inclusive assertions. Because that's something folks
--   need. Not implemented.
--   
- flexible assertions allowing custom criteria (perhaps arbitrary
--   queries). Because power users have diverse needs and want to try out
--   different schemes (assert cleared balances, assert balance from real
--   or virtual postings, etc.). Not implemented.
--   
- multicommodity assertions, asserting the balance of multiple
--   commodities at once. Not implemented, requires #934.
--   
data BalanceAssertion
BalanceAssertion :: Amount -> Bool -> Bool -> GenericSourcePos -> 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 -> GenericSourcePos
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [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
[ptype] :: Posting -> PostingType

-- | tag names and values, extracted from the comment
[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
--   price 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

-- | The position of parse errors (eg), like parsec's SourcePos but
--   generic.
data GenericSourcePos

-- | file path, 1-based line number and 1-based column number.
GenericSourcePos :: FilePath -> Int -> Int -> GenericSourcePos

-- | file path, inclusive range of 1-based line numbers (first, last).
JournalSourcePos :: FilePath -> (Int, Int) -> GenericSourcePos
data Transaction
Transaction :: Integer -> Text -> GenericSourcePos -> 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
[tsourcepos] :: Transaction -> GenericSourcePos
[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]
nulltransactionmodifier :: TransactionModifier

-- | A transaction modifier transformation, which adds an extra posting to
--   the matched posting's transaction. Can be like a regular posting, or
--   the amount can have the aismultiplier flag set, indicating that it's a
--   multiplier for the matched posting's amount.
type TMPostingRule = Posting

-- | A periodic transaction rule, describing a transaction that recurs.
data PeriodicTransaction
PeriodicTransaction :: Text -> Interval -> DateSpan -> 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

-- | some of Transaction's fields
[ptstatus] :: PeriodicTransaction -> Status
[ptcode] :: PeriodicTransaction -> Text
[ptdescription] :: PeriodicTransaction -> Text
[ptcomment] :: PeriodicTransaction -> Text
[pttags] :: PeriodicTransaction -> [Tag]
[ptpostings] :: PeriodicTransaction -> [Posting]
nullperiodictransaction :: PeriodicTransaction
data TimeclockCode
SetBalance :: TimeclockCode
SetRequiredHours :: TimeclockCode
In :: TimeclockCode
Out :: TimeclockCode
FinalOut :: TimeclockCode
data TimeclockEntry
TimeclockEntry :: GenericSourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> TimeclockEntry
[tlsourcepos] :: TimeclockEntry -> GenericSourcePos
[tlcode] :: TimeclockEntry -> TimeclockCode
[tldatetime] :: TimeclockEntry -> LocalTime
[tlaccount] :: TimeclockEntry -> AccountName
[tldescription] :: TimeclockEntry -> Text

-- | 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 :: Day -> CommoditySymbol -> Amount -> PriceDirective
[pddate] :: PriceDirective -> Day
[pdcommodity] :: PriceDirective -> CommoditySymbol
[pdamount] :: PriceDirective -> Amount

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

-- | A Journal, containing transactions and various other things. The basic
--   data model for hledger.
--   
--   This is used during parsing (as the type alias ParsedJournal), and
--   then finalised/validated for use as a Journal. Some extra
--   parsing-related fields are included for convenience, at least for now.
--   In a ParsedJournal these are updated as parsing proceeds, in a Journal
--   they represent the final state at end of parsing (used eg by the add
--   command).
data Journal
Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [FilePath] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountType [AccountName] -> Map CommoditySymbol Commodity -> Map CommoditySymbol AmountStyle -> [PriceDirective] -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> ClockTime -> Journal

-- | the current default year, specified by the most recent Y directive (or
--   current date)
[jparsedefaultyear] :: Journal -> Maybe Year

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

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

-- | the current account name aliases in effect, specified by alias
--   directives (& options ?) ,jparsetransactioncount :: Integer -- ^
--   the current count of transactions parsed so far (only journal format
--   txns, currently)
[jparsealiases] :: Journal -> [AccountAlias]

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

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

-- | Accounts whose type has been declared in account directives (usually 5
--   top-level accounts)
[jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName]

-- | commodities and formats declared by commodity directives
[jcommodities] :: Journal -> Map CommoditySymbol Commodity

-- | commodities and formats inferred from journal amounts TODO misnamed,
--   should be eg jusedstyles
[jinferredcommodities] :: Journal -> Map CommoditySymbol AmountStyle

-- | Declarations of market prices by P directives, in parse order (after
--   journal finalisation)
[jpricedirectives] :: Journal -> [PriceDirective]

-- | Market prices implied by transactions, in parse order (after journal
--   finalisation)
[jinferredmarketprices] :: Journal -> [MarketPrice]
[jtxnmodifiers] :: Journal -> [TransactionModifier]
[jperiodictxns] :: Journal -> [PeriodicTransaction]
[jtxns] :: Journal -> [Transaction]

-- | any final trailing comments in the (main) journal file
[jfinalcommentlines] :: Journal -> Text

-- | the file path and raw text of the main and any included journal files.
--   The main file is first, followed by any included files in the order
--   encountered.
[jfiles] :: Journal -> [(FilePath, Text)]

-- | when this journal was last read from its file(s)
[jlastreadtime] :: Journal -> ClockTime

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

-- | The id of a data format understood by hledger, eg journal or
--   csv. The --output-format option selects one of these for
--   output.
type StorageFormat = String

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

-- | An account, with its balances, parent/subaccount relationships, etc.
--   Only the name is required; the other fields are added when needed.
data Account
Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account] -> Maybe Account -> Bool -> Int -> MixedAmount -> MixedAmount -> Account

-- | this account's full name
[aname] :: Account -> AccountName

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

-- | this account's sub-accounts
[asubs] :: Account -> [Account]

-- | parent account
[aparent] :: Account -> Maybe Account

-- | used in the accounts report to label elidable parents balance
--   information
[aboring] :: Account -> Bool

-- | the number of postings to this account
[anumpostings] :: Account -> Int

-- | this account's balance, excluding subaccounts
[aebalance] :: Account -> MixedAmount

-- | this account's balance, including subaccounts
[aibalance] :: Account -> MixedAmount

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

-- | 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] -> Ledger
[ljournal] :: Ledger -> Journal
[laccounts] :: Ledger -> [Account]
instance GHC.Classes.Eq Hledger.Data.Types.NormalSign
instance GHC.Show.Show Hledger.Data.Types.NormalSign
instance GHC.Generics.Generic Hledger.Data.Types.Account
instance GHC.Generics.Generic Hledger.Data.Types.Journal
instance GHC.Classes.Eq Hledger.Data.Types.Journal
instance GHC.Generics.Generic Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Show.Show Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Classes.Eq Hledger.Data.Types.AccountDeclarationInfo
instance GHC.Generics.Generic Hledger.Data.Types.MarketPrice
instance GHC.Classes.Ord Hledger.Data.Types.MarketPrice
instance GHC.Classes.Eq Hledger.Data.Types.MarketPrice
instance GHC.Show.Show Hledger.Data.Types.PriceDirective
instance GHC.Generics.Generic Hledger.Data.Types.PriceDirective
instance GHC.Classes.Ord Hledger.Data.Types.PriceDirective
instance GHC.Classes.Eq Hledger.Data.Types.PriceDirective
instance GHC.Generics.Generic Hledger.Data.Types.TimeclockEntry
instance GHC.Classes.Ord Hledger.Data.Types.TimeclockEntry
instance GHC.Classes.Eq Hledger.Data.Types.TimeclockEntry
instance GHC.Generics.Generic Hledger.Data.Types.TimeclockCode
instance GHC.Classes.Ord Hledger.Data.Types.TimeclockCode
instance GHC.Classes.Eq Hledger.Data.Types.TimeclockCode
instance GHC.Generics.Generic Hledger.Data.Types.PeriodicTransaction
instance GHC.Classes.Eq Hledger.Data.Types.PeriodicTransaction
instance GHC.Show.Show Hledger.Data.Types.TransactionModifier
instance GHC.Generics.Generic Hledger.Data.Types.TransactionModifier
instance GHC.Classes.Eq Hledger.Data.Types.TransactionModifier
instance GHC.Generics.Generic Hledger.Data.Types.Posting
instance GHC.Show.Show Hledger.Data.Types.Transaction
instance GHC.Generics.Generic Hledger.Data.Types.Transaction
instance GHC.Classes.Eq Hledger.Data.Types.Transaction
instance GHC.Show.Show Hledger.Data.Types.BalanceAssertion
instance GHC.Generics.Generic Hledger.Data.Types.BalanceAssertion
instance GHC.Classes.Eq Hledger.Data.Types.BalanceAssertion
instance GHC.Generics.Generic Hledger.Data.Types.GenericSourcePos
instance GHC.Classes.Ord Hledger.Data.Types.GenericSourcePos
instance GHC.Show.Show Hledger.Data.Types.GenericSourcePos
instance GHC.Read.Read Hledger.Data.Types.GenericSourcePos
instance GHC.Classes.Eq Hledger.Data.Types.GenericSourcePos
instance GHC.Generics.Generic Hledger.Data.Types.Status
instance GHC.Enum.Enum Hledger.Data.Types.Status
instance GHC.Enum.Bounded Hledger.Data.Types.Status
instance GHC.Classes.Ord Hledger.Data.Types.Status
instance GHC.Classes.Eq Hledger.Data.Types.Status
instance GHC.Generics.Generic Hledger.Data.Types.PostingType
instance GHC.Show.Show Hledger.Data.Types.PostingType
instance GHC.Classes.Eq Hledger.Data.Types.PostingType
instance GHC.Show.Show Hledger.Data.Types.MixedAmount
instance GHC.Generics.Generic Hledger.Data.Types.MixedAmount
instance GHC.Classes.Ord Hledger.Data.Types.MixedAmount
instance GHC.Classes.Eq Hledger.Data.Types.MixedAmount
instance GHC.Show.Show Hledger.Data.Types.AmountPrice
instance GHC.Generics.Generic Hledger.Data.Types.AmountPrice
instance GHC.Classes.Ord Hledger.Data.Types.AmountPrice
instance GHC.Classes.Eq Hledger.Data.Types.AmountPrice
instance GHC.Show.Show Hledger.Data.Types.Amount
instance GHC.Generics.Generic Hledger.Data.Types.Amount
instance GHC.Classes.Ord Hledger.Data.Types.Amount
instance GHC.Classes.Eq Hledger.Data.Types.Amount
instance GHC.Generics.Generic Hledger.Data.Types.Commodity
instance GHC.Classes.Eq Hledger.Data.Types.Commodity
instance GHC.Show.Show Hledger.Data.Types.Commodity
instance GHC.Generics.Generic Hledger.Data.Types.AmountStyle
instance GHC.Read.Read Hledger.Data.Types.AmountStyle
instance GHC.Classes.Ord Hledger.Data.Types.AmountStyle
instance GHC.Classes.Eq Hledger.Data.Types.AmountStyle
instance GHC.Generics.Generic Hledger.Data.Types.DigitGroupStyle
instance GHC.Show.Show Hledger.Data.Types.DigitGroupStyle
instance GHC.Read.Read Hledger.Data.Types.DigitGroupStyle
instance GHC.Classes.Ord Hledger.Data.Types.DigitGroupStyle
instance GHC.Classes.Eq Hledger.Data.Types.DigitGroupStyle
instance GHC.Generics.Generic Hledger.Data.Types.AmountPrecision
instance GHC.Show.Show Hledger.Data.Types.AmountPrecision
instance GHC.Read.Read Hledger.Data.Types.AmountPrecision
instance GHC.Classes.Ord Hledger.Data.Types.AmountPrecision
instance GHC.Classes.Eq Hledger.Data.Types.AmountPrecision
instance GHC.Generics.Generic Hledger.Data.Types.Side
instance GHC.Classes.Ord Hledger.Data.Types.Side
instance GHC.Read.Read Hledger.Data.Types.Side
instance GHC.Show.Show Hledger.Data.Types.Side
instance GHC.Classes.Eq Hledger.Data.Types.Side
instance GHC.Generics.Generic Hledger.Data.Types.AccountAlias
instance GHC.Classes.Ord Hledger.Data.Types.AccountAlias
instance GHC.Show.Show Hledger.Data.Types.AccountAlias
instance GHC.Read.Read Hledger.Data.Types.AccountAlias
instance GHC.Classes.Eq Hledger.Data.Types.AccountAlias
instance GHC.Generics.Generic Hledger.Data.Types.AccountType
instance GHC.Classes.Ord Hledger.Data.Types.AccountType
instance GHC.Classes.Eq Hledger.Data.Types.AccountType
instance GHC.Show.Show Hledger.Data.Types.AccountType
instance GHC.Generics.Generic Hledger.Data.Types.Interval
instance GHC.Classes.Ord Hledger.Data.Types.Interval
instance GHC.Show.Show Hledger.Data.Types.Interval
instance GHC.Classes.Eq Hledger.Data.Types.Interval
instance GHC.Generics.Generic Hledger.Data.Types.Period
instance GHC.Show.Show Hledger.Data.Types.Period
instance GHC.Classes.Ord Hledger.Data.Types.Period
instance GHC.Classes.Eq Hledger.Data.Types.Period
instance GHC.Show.Show Hledger.Data.Types.SmartDate
instance GHC.Generics.Generic Hledger.Data.Types.DateSpan
instance GHC.Classes.Ord Hledger.Data.Types.DateSpan
instance GHC.Classes.Eq Hledger.Data.Types.DateSpan
instance GHC.Show.Show Hledger.Data.Types.WhichDate
instance GHC.Classes.Eq Hledger.Data.Types.WhichDate
instance GHC.Show.Show Hledger.Data.Types.SmartInterval
instance GHC.Show.Show Hledger.Data.Types.SmartSequence
instance GHC.Generics.Generic System.Time.ClockTime
instance GHC.Classes.Eq Hledger.Data.Types.Posting
instance GHC.Show.Show Hledger.Data.Types.Posting
instance GHC.Show.Show Hledger.Data.Types.Status
instance GHC.Show.Show Hledger.Data.Types.AmountStyle
instance Text.Blaze.ToMarkup Hledger.Data.Types.Quantity
instance Data.Default.Class.Default Hledger.Data.Types.Interval
instance Data.Default.Class.Default Hledger.Data.Types.Period
instance Data.Default.Class.Default Hledger.Data.Types.DateSpan

-- | 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 DateSpans.
--   
--   
--   >>> periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1)
--   True
--   
periodAsDateSpan :: Period -> DateSpan

-- | Convert DateSpans to Periods.
--   
--   
--   >>> dateSpanAsPeriod $ DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1)
--   MonthPeriod 2000 1
--   
dateSpanAsPeriod :: DateSpan -> Period

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

-- | Render a period as a compact display string suitable for user output.
--   
--   
--   >>> showPeriod (WeekPeriod (fromGregorian 2016 7 25))
--   "2016-07-25W30"
--   
showPeriod :: Period -> String

-- | Like showPeriod, but if it's a month period show just the 3 letter
--   month name abbreviation for the current locale.
showPeriodMonthAbbrev :: Period -> String
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) -> current
--   year -> current quarter if it's in selected year, otherwise first
--   quarter of selected year -> current month if it's in selected
--   quarter, otherwise first month of selected quarter -> current week
--   if it's in selected month, otherwise first week of selected month
--   -> today if it's in selected week, otherwise first day of selected
--   week, unless that's in previous month, in which case first day of
--   month containing selected week. Shrinking a day has no effect.
periodShrink :: Day -> Period -> Period
mondayBefore :: Day -> Day
yearMonthContainingWeekStarting :: Day -> (Integer, Int)
quarterContainingMonth :: Integral a => a -> a
firstMonthOfQuarter :: Num a => a -> a
startOfFirstWeekInMonth :: Integer -> Int -> Day

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 GHC.Generics.Generic Hledger.Data.Types.Ledger
instance GHC.Generics.Generic (Data.Decimal.DecimalRaw a)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.GenericSourcePos
instance Data.Aeson.Types.ToJSON.ToJSON Data.Decimal.Decimal
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AmountPrice
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PostingType
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.TransactionModifier
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PeriodicTransaction
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.PriceDirective
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.DateSpan
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Interval
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountAlias
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSONKey Hledger.Data.Types.AccountType
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Commodity
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 System.Time.ClockTime
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Journal
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Account
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Data.Types.Ledger
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Status
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.GenericSourcePos
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Amount
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountPrecision
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Side
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.DigitGroupStyle
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MixedAmount
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.BalanceAssertion
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AmountPrice
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.MarketPrice
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.PostingType
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Posting
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Transaction
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.AccountDeclarationInfo
instance Data.Aeson.Types.FromJSON.FromJSON Hledger.Data.Types.Account
instance Data.Aeson.Types.FromJSON.FromJSON (Data.Decimal.DecimalRaw GHC.Integer.Type.Integer)

module Hledger.Utils.Parse

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

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

-- | A parser of text that runs in some monad.
type TextParser m a = ParsecT CustomErr Text m a

-- | A parser of text that runs in some monad, keeping a Journal as state.
type JournalParser m a = StateT Journal (ParsecT CustomErr Text m) a

-- | A parser of text that runs in some monad, keeping a Journal as state,
--   that can throw an exception to end parsing, preventing further parser
--   backtracking.
type ErroringJournalParser m a = StateT Journal (ParsecT CustomErr Text (ExceptT FinalParseError m)) a

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

-- | Backtracking choice, use this when alternatives share a prefix.
--   Consumes no input if all choices fail.
choiceInState :: [StateT s (ParsecT CustomErr Text m) a] -> StateT s (ParsecT CustomErr Text m) a
surroundedBy :: Applicative m => m openclose -> m a -> m a
parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) 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 CustomErr Text m) a -> Text -> m (Either (ParseErrorBundle Text CustomErr) 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
showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String
nonspace :: TextParser m Char
isNonNewlineSpace :: Char -> Bool
restofline :: TextParser m String
eolof :: TextParser m ()
spacenonewline :: (Stream s, Char ~ Token s) => ParsecT CustomErr s m Char
skipNonNewlineSpaces :: (Stream s, Token s ~ Char) => ParsecT CustomErr s m ()
skipNonNewlineSpaces1 :: (Stream s, Token s ~ Char) => ParsecT CustomErr s m ()
skipNonNewlineSpaces' :: (Stream s, Token s ~ Char) => ParsecT CustomErr s m Bool

-- | A custom error type for the parser. The type is specialized to parsers
--   of Text streams.
data CustomErr

-- | 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]
lowercase :: String -> String
uppercase :: String -> String
underline :: String -> String
stripbrackets :: String -> String
unbracket :: 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.
--   No good for strings containing single quotes.
singleQuoteIfNeeded :: String -> String

-- | Quote-aware version of words - don't split on spaces which are inside
--   quotes. NB correctly handles "a'b" but not "'a'". Can raise
--   an error if parsing fails.
words' :: String -> [String]

-- | Quote-aware version of unwords - single-quote strings which contain
--   whitespace
unwords' :: [String] -> String

-- | Strip ANSI escape sequences from a string.
--   
--   
--   >>> stripAnsi "\ESC[31m-1\ESC[m"
--   "-1"
--   
stripAnsi :: String -> String

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

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

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

-- | Remove trailing newlines/carriage returns.
chomp :: 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 & maximum width, andor
--   leftright justify it. Works on multi-line strings too (but will
--   rewrite non-unix line endings).
formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String

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

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

-- | Join multi-line strings horizontally, after compressing each of them
--   to a single line with a comma and space between each original line.
concatOneLine :: [String] -> String

-- | Join strings vertically, left-aligned and right-padded.
vConcatLeftAligned :: [String] -> String

-- | Join strings vertically, right-aligned and left-padded.
vConcatRightAligned :: [String] -> String

-- | Convert a multi-line string to a rectangular string top-padded to the
--   specified height.
padtop :: Int -> String -> String

-- | Convert a multi-line string to a rectangular string bottom-padded to
--   the specified height.
padbottom :: Int -> String -> String

-- | Convert a multi-line string to a rectangular string left-padded to the
--   specified width. Treats wide characters as double width.
padleft :: Int -> String -> String

-- | Convert a multi-line string to a rectangular string right-padded to
--   the specified width. Treats wide characters as double width.
padright :: Int -> String -> String

-- | Clip a multi-line string to the specified width and height from the
--   top left.
cliptopleft :: Int -> Int -> String -> String

-- | Clip and pad a multi-line string to fill the specified width and
--   height.
fitto :: Int -> Int -> String -> String

-- | Get the designated render width of a character: 0 for a combining
--   character, 1 for a regular character, 2 for a wide character. (Wide
--   characters are rendered as exactly double width in apps and fonts that
--   support it.) (From Pandoc.)
charWidth :: Char -> Int

-- | Calculate the render width of a string, considering wide characters
--   (counted as double width), ANSI escape codes (not counted), and line
--   breaks (in a multi-line string, the longest line determines the
--   width).
strWidth :: 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

-- | General-purpose wide-char-aware single-line string 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.
fitString :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String

-- | A version of fitString that works on multi-line strings, separate for
--   now to avoid breakage. This will rewrite any line endings to unix
--   newlines.
fitStringMulti :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String

-- | Left-pad a string to the specified width. Treats wide characters as
--   double width. Works on multi-line strings too (but will rewrite
--   non-unix line endings).
padLeftWide :: Int -> String -> String

-- | Right-pad a string to the specified width. Treats wide characters as
--   double width. Works on multi-line strings too (but will rewrite
--   non-unix line endings).
padRightWide :: Int -> String -> String

-- | Debugging helpers.
--   
--   You can enable increasingly verbose debug output by adding --debug
--   [1-9] to a hledger command line. --debug with no argument means
--   --debug 1. This is implemented by calling dbgN or similar helpers,
--   defined below. These calls can be found throughout hledger code; they
--   have been added organically where it seemed likely they would be
--   needed again. The choice of debug level has not been very systematic.
--   202006 Here's a start at some guidelines, not yet applied
--   project-wide:
--   
--   Debug level: What to show: ------------
--   --------------------------------------------------------- 0 normal
--   command output only (no warnings, eg) 1 (--debug) useful warnings,
--   most common troubleshooting info, eg valuation 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
--   
--   Tip: when debugging with GHCI, the first run after loading Debug.hs
--   sets the debug level. If you need to change it, you must touch
--   Debug.hs, :reload in GHCI, then run the command with a new --debug
--   value. Or, often it's more convenient to add a temporary dbg0 and
--   :reload (dbg0 always prints).
module Hledger.Utils.Debug

-- | Pretty print. Easier alias for pretty-show's pPrint.
pprint :: Show a => a -> IO ()

-- | Pretty show. Easier alias for pretty-show's ppShow.
pshow :: Show a => a -> String

-- | Pretty trace. Easier alias for traceShowId + ppShow.
ptrace :: Show a => a -> a

-- | Like traceShowId, but uses a custom show function to render the value.
--   traceShowIdWith was too much of a mouthful.
traceWith :: Show a => (a -> String) -> a -> a

-- | Trace (print to stderr) a string if the global debug level is at or
--   above the specified level. At level 0, always prints. Otherwise, uses
--   unsafePerformIO.
traceAt :: Int -> String -> a -> a

-- | Trace (print to stderr) a showable value using a custom show function.
traceAtWith :: (a -> String) -> a -> a

-- | Global debug level, which controls the verbosity of debug output on
--   the console. The default is 0 meaning no debug output. The
--   --debug command line flag sets it to 1, or --debug=N
--   sets it to a higher value (note: not --debug N for some
--   reason). This uses unsafePerformIO and can be accessed from anywhere
--   and before normal command-line processing. When running with :main in
--   GHCI, you must touch and reload this module to see the effect of a new
--   --debug option. After command-line processing, it is also available as
--   the debug_ field of CliOpts. {--} {--}
debugLevel :: Int

-- | Pretty-print a label and a showable value to the console if the global
--   debug level is at or above the specified level. At level 0, always
--   prints. Otherwise, uses unsafePerformIO.
ptraceAt :: Show a => Int -> String -> a -> a

-- | Like ptraceAt, but takes a custom show function instead of a label.
ptraceAtWith :: Show a => Int -> (a -> String) -> a -> a

-- | Pretty-print a label and the showable value to the console, then
--   return it.
dbg0 :: Show a => String -> a -> a

-- | Pretty-print a label and the showable value to the console when the
--   global debug level is >= 1, then return it. Uses unsafePerformIO.
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 dbg0, but takes a custom show function instead of a label.
dbg0With :: Show a => (a -> String) -> a -> a
dbg1With :: Show a => (a -> String) -> a -> a
dbg2With :: Show a => (a -> String) -> a -> a
dbg3With :: Show a => (a -> String) -> a -> a
dbg4With :: Show a => (a -> String) -> a -> a
dbg5With :: Show a => (a -> String) -> a -> a
dbg6With :: Show a => (a -> String) -> a -> a
dbg7With :: Show a => (a -> String) -> a -> a
dbg8With :: Show a => (a -> String) -> a -> a
dbg9With :: Show a => (a -> String) -> a -> a

-- | Like dbg0, but also exit the program. Uses unsafePerformIO.
dbgExit :: Show a => String -> a -> a

-- | Like ptraceAt, but convenient to insert in an IO monad and enforces
--   monadic sequencing (plus convenience aliases). XXX These have a bug;
--   they should use traceIO, not trace, otherwise GHC can occasionally
--   over-optimise (cf lpaste a few days ago where it killed/blocked a
--   child thread).
ptraceAtIO :: (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 ()

-- | Log a label and a pretty-printed showable value to ./debug.log, then
--   return it. Can fail, see plogAt.
plog :: Show a => String -> a -> a

-- | Log a label and a pretty-printed showable value to ./debug.log, if the
--   global debug level is at or above the specified level. At level 0,
--   always logs. Otherwise, uses unsafePerformIO. Tends to fail if called
--   more than once, at least when built with -threaded (Exception:
--   debug.log: openFile: resource busy (file is locked)).
plogAt :: Show a => Int -> String -> a -> a

-- | Print the provided label (if non-null) and current parser state
--   (position and next input) to the console. (See also megaparsec's dbg.)
traceParse :: String -> TextParser m ()

-- | Convenience alias for traceParseAt
dbgparse :: Int -> String -> TextParser m ()

module Hledger.Utils.Test

-- | Acquire the resource to run this test (sub)tree and release it
--   afterwards
withResource :: IO a -> (a -> IO ()) -> (IO a -> TestTree) -> TestTree

-- | Customize the test tree based on the run-time options
askOption :: IsOption v => (v -> TestTree) -> TestTree

-- | Locally set the option value for the given test subtree
localOption :: IsOption v => v -> TestTree -> TestTree

-- | Locally adjust the option value for the given test subtree
adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree

-- | List of the default ingredients. This is what defaultMain uses.
--   
--   At the moment it consists of listingTests and
--   consoleTestReporter.
defaultIngredients :: [Ingredient]

-- | Parse the command line arguments and run the tests using the provided
--   ingredient list.
--   
--   When the tests finish, this function calls exitWith with the
--   exit code that indicates whether any tests have failed. See
--   defaultMain for details.
defaultMainWithIngredients :: [Ingredient] -> TestTree -> IO ()

-- | This ingredient doesn't do anything apart from registering additional
--   options.
--   
--   The option values can be accessed using askOption.
includingOptions :: [OptionDescription] -> Ingredient

-- | The after combinator declares dependencies between tests.
--   
--   If a TestTree is wrapped in after, the tests in this
--   tree will not run until certain other tests («dependencies») have
--   finished. These dependencies are specified using an AWK pattern (see
--   the «Patterns» section in the README).
--   
--   Moreover, if the DependencyType argument is set to
--   AllSucceed and at least one dependency has failed, this test
--   tree will not run at all.
--   
--   Tasty does not check that the pattern matches any tests (let alone the
--   correct set of tests), so it is on you to supply the right pattern.
--   
--   
Examples
--   
--   The following test will be executed only after all tests that contain
--   Foo anywhere in their path finish.
--   
--   
--   after AllFinish "Foo" $
--      testCase "A test that depends on Foo.Bar" $ ...
--   
--   
--   Note, however, that our test also happens to contain Foo as
--   part of its name, so it also matches the pattern and becomes a
--   dependency of itself. This will result in a DependencyLoop
--   exception. To avoid this, either change the test name so that it
--   doesn't mention Foo or make the pattern more specific.
--   
--   You can use AWK patterns, for instance, to specify the full path to
--   the dependency.
--   
--   
--   after AllFinish "$0 == \"Tests.Foo.Bar\"" $
--      testCase "A test that depends on Foo.Bar" $ ...
--   
--   
--   Or only specify the dependency's own name, ignoring the group names:
--   
--   
--   after AllFinish "$NF == \"Bar\"" $
--      testCase "A test that depends on Foo.Bar" $ ...
--   
after :: DependencyType -> String -> TestTree -> TestTree

-- | Like after, but accepts the pattern as a syntax tree instead of
--   a string. Useful for generating a test tree programmatically.
--   
--   
Examples
--   
--   Only match on the test's own name, ignoring the group names:
--   
--   
--   after_ AllFinish (EQ (Field NF) (StringLit "Bar")) $
--      testCase "A test that depends on Foo.Bar" $ ...
--   
after_ :: DependencyType -> Expr -> TestTree -> TestTree

-- | Create a named group of test cases or other groups
testGroup :: TestName -> [TestTree] -> TestTree

-- | The name of a test or a group of tests
type TestName = String

-- | These are the two ways in which one test may depend on the others.
--   
--   This is the same distinction as the hard vs soft dependencies in
--   TestNG.
data DependencyType

-- | The current test tree will be executed after its dependencies finish,
--   and only if all of the dependencies succeed.
AllSucceed :: DependencyType

-- | The current test tree will be executed after its dependencies finish,
--   regardless of whether they succeed or not.
AllFinish :: DependencyType

-- | The main data structure defining a test suite.
--   
--   It consists of individual test cases and properties, organized in
--   named groups which form a tree-like hierarchy.
--   
--   There is no generic way to create a test case. Instead, every test
--   provider (tasty-hunit, tasty-smallcheck etc.) provides a function to
--   turn a test case into a TestTree.
--   
--   Groups can be created using testGroup.
data TestTree

-- | A shortcut for creating Timeout values
mkTimeout :: Integer -> Timeout

-- | Timeout to be applied to individual tests
data Timeout

-- | String is the original representation of the timeout (such as
--   "0.5m"), so that we can print it back. Integer is the
--   number of microseconds.
Timeout :: Integer -> String -> Timeout
NoTimeout :: Timeout

-- | Name and group a list of tests. Shorter alias for
--   Test.Tasty.HUnit.testGroup.
tests :: String -> [TestTree] -> TestTree

-- | Name an assertion or sequence of assertions. Shorter alias for
--   Test.Tasty.HUnit.testCase.
test :: String -> Assertion -> TestTree

-- | 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, Eq a, Show a, Default st) => StateT st (ParsecT CustomErr Text IO) a -> Text -> Assertion

-- | Assert a parser produces an expected value.
assertParseEq :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT CustomErr 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 CustomErr 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 CustomErr Text IO) a -> String -> String -> Assertion

-- | These E variants of the above are suitable for hledger's
--   ErroringJournalParser parsers.
assertParseE :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT CustomErr Text (ExceptT FinalParseError IO)) a -> Text -> Assertion
assertParseEqE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT CustomErr Text (ExceptT FinalParseError IO)) a -> Text -> a -> Assertion
assertParseErrorE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT CustomErr 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 CustomErr Text IO) a -> Text -> (st -> b) -> b -> Assertion

-- | Text formatting helpers, ported from String as needed. There may be
--   better alternatives out there.
module Hledger.Utils.Text
textUnbracket :: 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
textQuoteIfNeeded :: Text -> Text
escapeDoubleQuotes :: Text -> Text

-- | Strip one matching pair of single or double quotes on the ends of a
--   string.
stripquotes :: Text -> Text
textElideRight :: 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

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

-- | Calculate the designated render width of a string, taking into account
--   wide characters and line breaks (the longest line within a multi-line
--   string determines the width ).
textWidth :: Text -> Int

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

-- | Left-pad a text to the specified width. Treats wide characters as
--   double width. Works on multi-line texts too (but will rewrite non-unix
--   line endings).
textPadLeftWide :: Int -> Text -> Text

-- | Right-pad a string to the specified width. Treats wide characters as
--   double width. Works on multi-line strings too (but will rewrite
--   non-unix line endings).
textPadRightWide :: Int -> Text -> Text

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

-- | Standard imports and utilities which are useful everywhere, or needed
--   low in the module hierarchy. This is the bottom of hledger's module
--   graph.
module Hledger.Utils
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
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
splitAtElement :: Eq a => a -> [a] -> [[a]]
getCurrentLocalTime :: IO LocalTime
getCurrentZonedTime :: IO ZonedTime

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

-- | Convert a possibly relative, possibly tilde-containing file path to an
--   absolute one, given the current directory. ~username is not supported.
--   Leave "-" unchanged. Can raise an error.
expandPath :: FilePath -> FilePath -> IO FilePath

-- | Expand user home path indicated by tilde prefix
expandHomePath :: FilePath -> IO FilePath

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

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

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

-- | Strict version of sum that doesn’t leak space
sumStrict :: Num 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

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

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

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

-- | A SystemString-aware version of error.
error' :: String -> a

-- | A SystemString-aware version of userError.
userError' :: String -> IOError

-- | A SystemString-aware version of error that adds a usage hint.
usageError :: String -> a
instance Data.Default.Class.Default GHC.Types.Bool

-- | 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
setopt :: String -> String -> RawOpts -> RawOpts
setboolopt :: String -> RawOpts -> RawOpts

-- | Is the named option present ?
inRawOpts :: String -> RawOpts -> Bool
boolopt :: 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...
--   
--   
--   >>> import Safe (readMay)
--   
--   >>> choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])
--   Just "c"
--   
--   >>> choiceopt (const Nothing) (RawOpts [("a","")])
--   Nothing
--   
--   >>> choiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe Ordering
--   Just EQ
--   
choiceopt :: (String -> Maybe a) -> RawOpts -> Maybe a

-- | Collects processed and filtered list of options preserving their order
--   
--   
--   >>> collectopts (const Nothing) (RawOpts [("x","")])
--   []
--   
--   >>> collectopts Just (RawOpts [("a",""),("b","")])
--   [("a",""),("b","")]
--   
collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]
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
instance GHC.Show.Show Hledger.Data.RawOptions.RawOpts
instance Data.Default.Class.Default Hledger.Data.RawOptions.RawOpts

-- | A Commodity is a symbol representing a currency or some other
--   kind of thing we are tracking, and some display preferences that tell
--   how to display Amounts of the commodity - is the symbol on the
--   left or right, are thousands separated by comma, significant decimal
--   places and so on.
module Hledger.Data.Commodity
isNonsimpleCommodityChar :: Char -> Bool
quoteCommoditySymbolIfNeeded :: Text -> Text
commodity :: [Char]
commoditysymbols :: [(String, CommoditySymbol)]

-- | Look up one of the sample commodities' symbol by name.
comm :: String -> CommoditySymbol

-- | Find the conversion rate between two commodities. Currently returns 1.
conversionRate :: CommoditySymbol -> CommoditySymbol -> Double

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

-- | The empty simple amount.
amount :: Amount

-- | The empty simple amount.
nullamt :: Amount

-- | A temporary value for parsed transactions which had no amount
--   specified.
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 assigned prices and assuming an exchange rate of 1.
amountWithCommodity :: CommoditySymbol -> Amount -> Amount

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

-- | Is this amount exactly zero, ignoring its display precision ?
amountIsZero :: Amount -> Bool

-- | Does mixed amount appear to be zero when rendered with its display
--   precision ?
amountLooksZero :: Amount -> Bool

-- | Divide an amount's quantity by a constant.
divideAmount :: Quantity -> Amount -> Amount

-- | Multiply an amount's quantity by a constant.
multiplyAmount :: Quantity -> Amount -> Amount

-- | Divide an amount's quantity (and its total price, if it has one) by a
--   constant. The total price will be kept positive regardless of the
--   multiplier's sign.
divideAmountAndPrice :: Quantity -> Amount -> Amount

-- | Multiply an amount's quantity (and its total price, if it has one) by
--   a constant. The total price will be kept positive regardless of the
--   multiplier's sign.
multiplyAmountAndPrice :: Quantity -> Amount -> Amount

-- | Replace an amount's TotalPrice, if it has one, with an equivalent
--   UnitPrice. Has no effect on amounts without one. Also increases the
--   unit price's display precision to show one extra decimal place, to
--   help keep transaction amounts balancing. Does Decimal division, might
--   be some rounding/irrational number issues.
amountTotalPriceToUnitPrice :: Amount -> Amount

-- | Default amount style
amountstyle :: AmountStyle

-- | Given a map of standard commodity display styles, apply the
--   appropriate one to this amount. If there's no standard style for this
--   amount's commodity, return the amount unchanged.
styleAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Like styleAmount, but keep the number of decimal places unchanged.
styleAmountExceptPrecision :: Map CommoditySymbol AmountStyle -> Amount -> Amount

-- | Get the string representation of an amount, based on its commodity's
--   display settings. String representations equivalent to zero are
--   converted to just "0". The special "missing" amount is displayed as
--   the empty string.
showAmount :: Amount -> String

-- | Colour version. For a negative amount, adds ANSI codes to change the
--   colour, currently to hard-coded red.
cshowAmount :: Amount -> String

-- | Like showAmount, but show a zero amount's commodity if it has one.
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 @ price. With
--   a True argument, adds ANSI codes to show negative amounts in red.
showAmountWithoutPrice :: Bool -> Amount -> String

-- | Set an amount's display precision.
setAmountPrecision :: AmountPrecision -> 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,
--   excluding trailing zeros).
setFullPrecision :: Amount -> Amount

-- | Set an amount's internal precision, ie rounds the Decimal representing
--   the amount's quantity to some 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)". Does not change the amount's display precision. Intended
--   only for internal use, eg when comparing amounts in tests.
setAmountInternalPrecision :: Word8 -> Amount -> Amount

-- | Set an amount's internal precision, flipped. Intended only for
--   internal use, eg when comparing amounts in tests.
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

-- | Canonicalise an amount's display style using the provided commodity
--   style map.
canonicaliseAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount

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

-- | A temporary value for parsed transactions which had no amount
--   specified.
missingmixedamt :: MixedAmount

-- | Convert amounts in various commodities into a normalised MixedAmount.
mixed :: [Amount] -> MixedAmount

-- | Get a mixed amount's component amounts.
amounts :: MixedAmount -> [Amount]

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

-- | Return an unnormalised MixedAmount containing exactly one Amount with
--   the specified commodity and the quantity of that commodity found in
--   the original. NB if Amount's quantity is zero it will be discarded
--   next time the MixedAmount gets normalised.
filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount

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

-- | Like normaliseMixedAmount, but combine each commodity's amounts into
--   just one by throwing away all prices except the first. This is only
--   used as a rendering helper, and could show a misleading price.
normaliseMixedAmountSquashPricesForDisplay :: MixedAmount -> MixedAmount

-- | Simplify a mixed amount's component amounts:
--   
--   
--   
- amounts in the same commodity are combined unless they have
--   different prices or total prices
--   
- multiple zero amounts, all with the same non-null commodity, are
--   replaced by just the last of them, preserving the commodity and amount
--   style (all but the last zero amount are discarded)
--   
- multiple zero amounts with multiple commodities, or no
--   commodities, are replaced by one commodity-less zero amount
--   
- an empty amount list is replaced by one commodity-less zero
--   amount
--   
- the special "missing" mixed amount remains unchanged
--   
normaliseMixedAmount :: MixedAmount -> MixedAmount

-- | Unify a MixedAmount to a single commodity value if possible. Like
--   normaliseMixedAmount, 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
mixedAmountStripPrices :: MixedAmount -> MixedAmount

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

-- | Divide a mixed amount's quantities by a constant.
divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount

-- | Multiply a mixed amount's quantities by a constant.
multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount

-- | Divide a mixed amount's quantities (and total prices, if any) by a
--   constant. The total prices will be kept positive regardless of the
--   multiplier's sign.
divideMixedAmountAndPrice :: Quantity -> MixedAmount -> MixedAmount

-- | Multiply a mixed amount's quantities (and total prices, if any) by a
--   constant. The total prices will be kept positive regardless of the
--   multiplier's sign.
multiplyMixedAmountAndPrice :: Quantity -> MixedAmount -> MixedAmount

-- | Calculate the average of some mixed amounts.
averageMixedAmounts :: [MixedAmount] -> MixedAmount

-- | Is this amount negative ? The price 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

-- | Is this mixed amount exactly zero, ignoring display precisions ?
mixedAmountIsZero :: MixedAmount -> Bool

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

-- | Replace each component amount's TotalPrice, if it has one, with an
--   equivalent UnitPrice. Has no effect on amounts without one. Does
--   Decimal division, might be some rounding/irrational number issues.
mixedAmountTotalPriceToUnitPrice :: MixedAmount -> MixedAmount

-- | Given a map of standard commodity display styles, apply the
--   appropriate one to each individual amount.
styleMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Get the string representation of a mixed amount, after normalising it
--   to one amount per commodity. Assumes amounts have no or similar
--   prices, otherwise this can show misleading prices.
showMixedAmount :: MixedAmount -> String

-- | Get the one-line string representation of a mixed amount.
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
--   transaction prices. With a True argument, adds ANSI codes to show
--   negative amounts in red.
showMixedAmountWithoutPrice :: Bool -> MixedAmount -> String

-- | Get the one-line string representation of a mixed amount, but without
--   any @ prices. With a True argument, adds ANSI codes to show negative
--   amounts in red.
showMixedAmountOneLineWithoutPrice :: Bool -> MixedAmount -> String

-- | Like showMixedAmountOneLineWithoutPrice, but show at most two
--   commodities, with a elision indicator if there are more. With a True
--   argument, adds ANSI codes to show negative amounts in red.
showMixedAmountElided :: Bool -> MixedAmount -> String

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

-- | Get the string representation of a mixed amount, showing each of its
--   component amounts with the specified precision, ignoring their
--   commoditys' display precision settings.
showMixedAmountWithPrecision :: AmountPrecision -> MixedAmount -> String

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

-- | Canonicalise a mixed amount's display styles using the provided
--   commodity style map.
canonicaliseMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount

-- | Compact labelled trace of a mixed amount, for debugging.
ltraceamount :: String -> MixedAmount -> MixedAmount
tests_Amount :: TestTree
instance GHC.Show.Show Hledger.Data.Types.MarketPrice
instance GHC.Num.Num Hledger.Data.Types.Amount
instance GHC.Num.Num Hledger.Data.Types.MixedAmount

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

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

-- | convert to cost commodity using transaction prices, then optionally to
--   given commodity using market prices at posting date
AtCost :: Maybe CommoditySymbol -> 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

-- | works like AtNow in single period reports, like AtEnd in multiperiod
--   reports
AtDefault :: 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.
journalPriceOracle :: Bool -> Journal -> PriceOracle

-- | Standard error message for a report not supporting --value=then.
unsupportedValueThenError :: String

-- | Apply a specified valuation to this mixed amount, using the provided
--   price oracle, commodity styles, reference dates, and whether this is
--   for a multiperiod report or not. See amountApplyValuation.
mixedAmountApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Maybe Day -> Day -> Bool -> 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
marketPriceReverse :: MarketPrice -> MarketPrice
priceDirectiveToMarketPrice :: PriceDirective -> MarketPrice
tests_Valuation :: TestTree
instance GHC.Generics.Generic Hledger.Data.Valuation.PriceGraph
instance GHC.Show.Show Hledger.Data.Valuation.PriceGraph
instance GHC.Classes.Eq Hledger.Data.Valuation.ValuationType
instance GHC.Show.Show Hledger.Data.Valuation.ValuationType

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

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

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

-- | Keep only the first n components of an account name, where n is a
--   positive integer. If n is Just 0, returns the empty string, if n is
--   Nothing, return the full name.
clipAccountName :: Maybe Int -> AccountName -> AccountName

-- | Keep only the first n components of an account name, where n is a
--   positive integer. If n is Just 0, returns "...", if n is Nothing,
--   return the full name.
clipOrEllipsifyAccountName :: Maybe Int -> AccountName -> AccountName

-- | Elide an account name to fit in the specified width. From the ledger
--   2.6 news:
--   
--   
--   What Ledger now does is that if an account name is too long, it will
--   start abbreviating the first parts of the account name down to two
--   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       ; Expenses was abbreviated to fit
--     Ex:We:Afternoon:Cash    ; Expenses and Wednesday abbreviated
--     ; Expenses:Wednesday:Afternoon:Lunch:Snack:Candy:Chocolate:Cash
--     ..:Af:Lu:Sn:Ca:Ch:Cash  ; Abbreviated and elided!
--   
elideAccountName :: Int -> AccountName -> AccountName

-- | Escape an AccountName for use within a regular expression.
--   >>> putStr $ escapeName "First?!*? %)*!#" First?!#$*?$(*)
--   !^
escapeName :: AccountName -> String

-- | "a:b:c" -> ["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"]
--   -> ["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
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]

-- | 
--   
- "a:b:c","d:e" -> ["a","d"]
--   
topAccountNames :: [AccountName] -> [AccountName]

-- | A top-level account prefixed to some accounts in budget reports.
--   Defined here so it can be ignored by accountNameDrop.
unbudgetedAccountName :: Text
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 :: String -> 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 :: String -> StringFormatComponent

-- | A data field to be formatted and interpolated. Parameters:
--   
--   
--   
- Left justify ? Right justified if false
--   
- Minimum width ? Will be space-padded if narrower than this
--   
- Maximum width ? Will be clipped if wider than this
--   
- Which of the standard hledger report item fields to
--   interpolate
--   
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
tests_StringFormat :: TestTree
instance GHC.Classes.Eq Hledger.Data.StringFormat.StringFormat
instance GHC.Show.Show Hledger.Data.StringFormat.StringFormat
instance GHC.Classes.Eq Hledger.Data.StringFormat.StringFormatComponent
instance GHC.Show.Show Hledger.Data.StringFormat.StringFormatComponent
instance GHC.Classes.Eq Hledger.Data.StringFormat.ReportItemField
instance GHC.Show.Show Hledger.Data.StringFormat.ReportItemField

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

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

-- | Try to parse a couple of date string formats: `YYYY-MM-DD`,
--   `YYYY<i>MM</i>DD` or DD, with leading zeros required. For
--   internal use, not quite the same as the journal's "simple dates".
--   >>> parsedateM "20080203" Just 2008-02-03 >>>
--   parsedateM "20080203/" Nothing >>> parsedateM
--   "20080230" Nothing
parsedateM :: String -> Maybe Day
showDate :: Day -> String

-- | Render a datespan as a display string, abbreviating into a compact
--   form if possible.
showDateSpan :: DateSpan -> String

-- | Like showDateSpan, but show month spans as just the abbreviated month
--   name in the current locale.
showDateSpanMonthAbbrev :: DateSpan -> String
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).
--   
--   
--   >>> let p = parsePeriodExpr (fromGregorian 2008 11 26)
--   
--   >>> p "from Aug to Oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   >>> p "aug to oct"
--   Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
--   
--   >>> p "2009q2"
--   Right (NoInterval,DateSpan 2009Q2)
--   
--   >>> p "Q3"
--   Right (NoInterval,DateSpan 2008Q3)
--   
--   >>> p "every 3 days in Aug"
--   Right (Days 3,DateSpan 2008-08)
--   
--   >>> p "daily from aug"
--   Right (Days 1,DateSpan 2008-08-01..)
--   
--   >>> p "every week to 2009"
--   Right (Weeks 1,DateSpan ..2008-12-31)
--   
--   >>> p "every 2nd day of month"
--   Right (DayOfMonth 2,DateSpan ..)
--   
--   >>> p "every 2nd day"
--   Right (DayOfMonth 2,DateSpan ..)
--   
--   >>> p "every 2nd day 2009.."
--   Right (DayOfMonth 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd day 2009-"
--   Right (DayOfMonth 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 29th Nov"
--   Right (DayOfYear 11 29,DateSpan ..)
--   
--   >>> p "every 29th nov ..2009"
--   Right (DayOfYear 11 29,DateSpan ..2008-12-31)
--   
--   >>> p "every nov 29th"
--   Right (DayOfYear 11 29,DateSpan ..)
--   
--   >>> p "every Nov 29th 2009.."
--   Right (DayOfYear 11 29,DateSpan 2009-01-01..)
--   
--   >>> p "every 11/29 from 2009"
--   Right (DayOfYear 11 29,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd Thursday of month to 2009"
--   Right (WeekdayOfMonth 2 4,DateSpan ..2008-12-31)
--   
--   >>> p "every 1st monday of month to 2009"
--   Right (WeekdayOfMonth 1 1,DateSpan ..2008-12-31)
--   
--   >>> p "every tue"
--   Right (DayOfWeek 2,DateSpan ..)
--   
--   >>> p "every 2nd day of week"
--   Right (DayOfWeek 2,DateSpan ..)
--   
--   >>> p "every 2nd day of month"
--   Right (DayOfMonth 2,DateSpan ..)
--   
--   >>> p "every 2nd day"
--   Right (DayOfMonth 2,DateSpan ..)
--   
--   >>> p "every 2nd day 2009.."
--   Right (DayOfMonth 2,DateSpan 2009-01-01..)
--   
--   >>> p "every 2nd day of month 2009.."
--   Right (DayOfMonth 2,DateSpan 2009-01-01..)
--   
periodexprp :: Day -> TextParser m (Interval, DateSpan)

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

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

-- | A datespan of zero length, that matches no date.
emptydatespan :: DateSpan
datesepchar :: 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.
spansSpan :: [DateSpan] -> DateSpan

-- | Calculate the intersection of two datespans.
--   
--   For non-intersecting spans, gives an empty span beginning on the
--   second's start date: >>> DateSpan (Just $ fromGregorian 2018
--   01 01) (Just $ fromGregorian 2018 01 03) spanIntersect DateSpan
--   (Just $ fromGregorian 2018 01 03) (Just $ 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. Sort of a one-way spanIntersect.
spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan

-- | Calculate the union of two datespans.
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:
--   
--   
--   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)
--   20181201                                    (8 digit YYYYMMDD with valid year month and day)
--   201812                                      (6 digit YYYYMM with valid year and month)
--   
--   
--   Note malformed digit sequences might give surprising results:
--   
--   
--   201813                                      (6 digits with an invalid month is parsed as start of 6-digit year)
--   20181301                                    (8 digits with an invalid month is parsed as start of 8-digit year)
--   20181232                                    (8 digits with an invalid day gives an error)
--   201801012                                   (9+ digits beginning with a valid YYYYMMDD gives an error)
--   
--   
--   Eg:
--   
--   YYYYMMDD is parsed as year-month-date if those parts are valid (>=4
--   digits, 1-12, and 1-31 respectively): >>> parsewith
--   (smartdate <* eof) "20181201" Right (SmartAssumeStart 2018 (Just
--   (12,Just 1)))
--   
--   YYYYMM is parsed as year-month-01 if year and month are valid:
--   >>> parsewith (smartdate <* eof) "201804" Right
--   (SmartAssumeStart 2018 (Just (4,Nothing)))
--   
--   With an invalid month, it's parsed as a year: >>> parsewith
--   (smartdate <* eof) "201813" Right (SmartAssumeStart 201813 Nothing)
--   
--   A 9+ digit number beginning with valid YYYYMMDD gives an error:
--   >>> parsewith (smartdate <* eof) "201801012" Left (...)
--   
--   Big numbers not beginning with a valid YYYYMMDD are parsed as a year:
--   >>> parsewith (smartdate <* eof) "201813012" Right
--   (SmartAssumeStart 201813012 Nothing)
smartdate :: TextParser m SmartDate

-- | Split a DateSpan into consecutive whole spans of the specified
--   interval which fully encompass the original span (and a little more
--   when necessary). If no interval is specified, the original span is
--   returned. If the original span is the null date span, ie unbounded,
--   the null date span is returned. If the original span is empty, eg if
--   the end date is <= the start date, no spans are returned.
--   
--   
Examples:
--   
--   
--   >>> let t i y1 m1 d1 y2 m2 d2 = splitSpan i $ DateSpan (Just $ fromGregorian y1 m1 d1) (Just $ fromGregorian y2 m2 d2)
--   
--   >>> t NoInterval 2008 01 01 2009 01 01
--   [DateSpan 2008]
--   
--   >>> t (Quarters 1) 2008 01 01 2009 01 01
--   [DateSpan 2008Q1,DateSpan 2008Q2,DateSpan 2008Q3,DateSpan 2008Q4]
--   
--   >>> splitSpan (Quarters 1) nulldatespan
--   [DateSpan ..]
--   
--   >>> t (Days 1) 2008 01 01 2008 01 01  -- an empty datespan
--   []
--   
--   >>> t (Quarters 1) 2008 01 01 2008 01 01
--   []
--   
--   >>> t (Months 1) 2008 01 01 2008 04 01
--   [DateSpan 2008-01,DateSpan 2008-02,DateSpan 2008-03]
--   
--   >>> t (Months 2) 2008 01 01 2008 04 01
--   [DateSpan 2008-01-01..2008-02-29,DateSpan 2008-03-01..2008-04-30]
--   
--   >>> t (Weeks 1) 2008 01 01 2008 01 15
--   [DateSpan 2007-12-31W01,DateSpan 2008-01-07W02,DateSpan 2008-01-14W03]
--   
--   >>> t (Weeks 2) 2008 01 01 2008 01 15
--   [DateSpan 2007-12-31..2008-01-13,DateSpan 2008-01-14..2008-01-27]
--   
--   >>> t (DayOfMonth 2) 2008 01 01 2008 04 01
--   [DateSpan 2007-12-02..2008-01-01,DateSpan 2008-01-02..2008-02-01,DateSpan 2008-02-02..2008-03-01,DateSpan 2008-03-02..2008-04-01]
--   
--   >>> t (WeekdayOfMonth 2 4) 2011 01 01 2011 02 15
--   [DateSpan 2010-12-09..2011-01-12,DateSpan 2011-01-13..2011-02-09,DateSpan 2011-02-10..2011-03-09]
--   
--   >>> t (DayOfWeek 2) 2011 01 01 2011 01 15
--   [DateSpan 2010-12-28..2011-01-03,DateSpan 2011-01-04..2011-01-10,DateSpan 2011-01-11..2011-01-17]
--   
--   >>> t (DayOfYear 11 29) 2011 10 01 2011 10 15
--   [DateSpan 2010-11-29..2011-11-28]
--   
--   >>> t (DayOfYear 11 29) 2011 12 01 2012 12 15
--   [DateSpan 2011-11-29..2012-11-28,DateSpan 2012-11-29..2013-11-28]
--   
splitSpan :: Interval -> DateSpan -> [DateSpan]

-- | Convert a SmartDate to an absolute date using the provided reference
--   date.
--   
--   
Examples:
--   
--   
--   >>> :set -XOverloadedStrings
--   
--   >>> let t = fixSmartDateStr (fromGregorian 2008 11 26)
--   
--   >>> t "0000-01-01"
--   "0000-01-01"
--   
--   >>> t "1999-12-02"
--   "1999-12-02"
--   
--   >>> t "1999.12.02"
--   "1999-12-02"
--   
--   >>> t "1999/3/2"
--   "1999-03-02"
--   
--   >>> t "19990302"
--   "1999-03-02"
--   
--   >>> t "2008/2"
--   "2008-02-01"
--   
--   >>> t "0020/2"
--   "0020-02-01"
--   
--   >>> t "1000"
--   "1000-01-01"
--   
--   >>> t "4/2"
--   "2008-04-02"
--   
--   >>> t "2"
--   "2008-11-02"
--   
--   >>> t "January"
--   "2008-01-01"
--   
--   >>> t "feb"
--   "2008-02-01"
--   
--   >>> t "today"
--   "2008-11-26"
--   
--   >>> t "yesterday"
--   "2008-11-25"
--   
--   >>> t "tomorrow"
--   "2008-11-27"
--   
--   >>> t "this day"
--   "2008-11-26"
--   
--   >>> t "last day"
--   "2008-11-25"
--   
--   >>> t "next day"
--   "2008-11-27"
--   
--   >>> t "this week"  -- last monday
--   "2008-11-24"
--   
--   >>> t "last week"  -- previous monday
--   "2008-11-17"
--   
--   >>> t "next week"  -- next monday
--   "2008-12-01"
--   
--   >>> t "this month"
--   "2008-11-01"
--   
--   >>> t "last month"
--   "2008-10-01"
--   
--   >>> t "next month"
--   "2008-12-01"
--   
--   >>> t "this quarter"
--   "2008-10-01"
--   
--   >>> t "last quarter"
--   "2008-07-01"
--   
--   >>> t "next quarter"
--   "2009-01-01"
--   
--   >>> t "this year"
--   "2008-01-01"
--   
--   >>> t "last year"
--   "2007-01-01"
--   
--   >>> t "next year"
--   "2009-01-01"
--   
--   
--   t "last wed" "2008-11-19" t "next friday" "2008-11-28" t "next
--   january" "2009-01-01"
fixSmartDate :: Day -> SmartDate -> Day

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

-- | A safe version of fixSmartDateStr.
fixSmartDateStrEither :: Day -> Text -> Either (ParseErrorBundle Text CustomErr) String
fixSmartDateStrEither' :: Day -> Text -> Either (ParseErrorBundle Text CustomErr) Day

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

-- | Count the days in a DateSpan, or if it is open-ended return Nothing.
daysInSpan :: DateSpan -> Maybe Integer
maybePeriod :: Day -> Text -> Maybe (Interval, DateSpan)
instance GHC.Show.Show Hledger.Data.Types.DateSpan

-- | A Posting represents a change (by some MixedAmount) of
--   the balance in some Account. Each Transaction contains
--   two or more postings which should add up to 0. Postings reference
--   their parent transaction, so we can look up the date or description
--   there.
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
nullsourcepos :: GenericSourcePos
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

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

-- | Tags for this transaction including any from its postings.
transactionAllTags :: Transaction -> [Tag]
relatedPostings :: Posting -> [Posting]

-- | Remove all prices of a posting
removePrices :: 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

-- | Does this posting fall within the given date span ?
isPostingInDateSpan :: DateSpan -> Posting -> Bool
isPostingInDateSpan' :: WhichDate -> DateSpan -> Posting -> Bool

-- | Sorted unique account names referenced by these postings.
accountNamesFromPostings :: [Posting] -> [AccountName]
accountNamePostingType :: AccountName -> PostingType
accountNameWithoutPostingType :: AccountName -> AccountName
accountNameWithPostingType :: PostingType -> 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

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

-- | 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
sumPostings :: [Posting] -> MixedAmount
showPosting :: Posting -> String
showComment :: Text -> String

-- | Apply a transform function to this posting's amount.
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting

-- | Apply a specified valuation to this posting's amount, using the
--   provided price oracle, commodity styles, reference dates, and whether
--   this is for a multiperiod report or not. See amountApplyValuation.
postingApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Maybe Day -> Day -> Bool -> Posting -> ValuationType -> Posting

-- | Convert this posting's amount to cost, and apply the appropriate
--   amount styles.
postingToCost :: Map CommoditySymbol AmountStyle -> Posting -> Posting
tests_Posting :: TestTree

-- | A Transaction represents a movement of some commodity(ies)
--   between two or more accounts. It consists of multiple account
--   Postings 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

-- | Show an account name, clipped to the given width if any, and
--   appropriately bracketed/parenthesised for the given posting type.
showAccountName :: Maybe Int -> PostingType -> AccountName -> String
hasRealPostings :: Transaction -> Bool
realPostings :: Transaction -> [Posting]
assignmentPostings :: Transaction -> [Posting]
virtualPostings :: Transaction -> [Posting]
balancedVirtualPostings :: Transaction -> [Posting]
transactionsPostings :: [Transaction] -> [Posting]

-- | Legacy form of transactionCheckBalanced.
isTransactionBalanced :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Bool

-- | Balance this 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.
--   
--   Transactions with balance assignments can have more than one missing
--   amount; to balance those you should use the more powerful
--   journalBalanceTransactions.
--   
--   The "sum to 0" test is done using commodity display precisions, if
--   provided, so that the result agrees with the numbers users can see.
balanceTransaction :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Either String Transaction

-- | Helper used by balanceTransaction and
--   balanceTransactionWithBalanceAssignmentAndCheckAssertionsB; use one of
--   those instead. It also returns a list of accounts and amounts that
--   were inferred.
balanceTransactionHelper :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])

-- | 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, reference dates, and whether
--   this is for a multiperiod report or not. See amountApplyValuation.
transactionApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Maybe Day -> Day -> Bool -> Transaction -> ValuationType -> Transaction

-- | Convert this transaction's amounts to cost, and apply the appropriate
--   amount styles.
transactionToCost :: Map CommoditySymbol AmountStyle -> Transaction -> Transaction
transactionDate2 :: 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:
--   
--   
--   yyyy-mm-dd[ *][ CODE] description.........          [  ; comment...............]
--       account name 1.....................  ...$amount1[  ; comment...............]
--       account name 2.....................  ..$-amount1[  ; comment...............]
--   
--   pcodewidth    = no limit -- 10          -- mimicking ledger layout.
--   pdescwidth    = no limit -- 20          -- I don't remember what these mean,
--   pacctwidth    = 35 minimum, no maximum  -- they were important at the time.
--   pamtwidth     = 11
--   pcommentwidth = no limit -- 22
--   
--   
--   The output will be parseable journal syntax. To facilitate this,
--   postings with explicit multi-commodity amounts are displayed as
--   multiple similar postings, one per commodity. (Normally does not
--   happen with this function).
showTransaction :: Transaction -> String

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

-- | Deprecated alias for showTransaction
showTransactionUnelided :: Transaction -> String

-- | Deprecated alias for showTransactionOneLineAmounts
showTransactionUnelidedOneLineAmounts :: Transaction -> String

-- | Render a posting, simply. Used in balance assertion errors.
--   showPostingLine p = lineIndent $ if pstatus p == Cleared then "* "
--   else "" ++ -- XXX show ! showAccountName Nothing (ptype p) (paccount
--   p) ++ " " ++ showMixedAmountOneLine (pamount p) ++ assertion where --
--   XXX extract, handle == assertion = maybe "" ((" = " ++) .
--   showAmountWithZeroCommodity . baamount) $ pbalanceassertion p
--   
--   Render a posting, at the appropriate width for aligning with its
--   siblings if any. Used by the rewrite command.
showPostingLines :: Posting -> [String]
sourceFilePath :: GenericSourcePos -> FilePath
sourceFirstLine :: GenericSourcePos -> Int

-- | Render source position in human-readable form. Keep in sync with
--   Hledger.UI.ErrorScreen.hledgerparseerrorpositionp (temporary). XXX
showGenericSourcePos :: GenericSourcePos -> String
annotateErrorWithTransaction :: Transaction -> String -> String
tests_Transaction :: TestTree

-- | 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
None :: Query

-- | negate this match
Not :: Query -> Query

-- | match if any of these match
Or :: [Query] -> Query

-- | match if all of these match
And :: [Query] -> Query

-- | match if code matches this regexp
Code :: Regexp -> Query

-- | match if description matches this regexp
Desc :: Regexp -> Query

-- | match postings whose account matches this regexp
Acct :: Regexp -> Query

-- | match if primary date in this date span
Date :: DateSpan -> Query

-- | match if secondary date in this date span
Date2 :: DateSpan -> Query

-- | match txns/postings with this status
StatusQ :: Status -> Query

-- | match if "realness" (involves a real non-virtual account ?) has this
--   value
Real :: Bool -> Query

-- | match if the amount's numeric quantity is less thangreater
--   thanequal to/unsignedly equal to some value
Amt :: OrdPlus -> Quantity -> Query

-- | match if the entire commodity symbol is matched by this regexp
Sym :: Regexp -> Query

-- | if true, show zero-amount postings/accounts which are usually not
--   shown more of a query option than a query criteria ?
Empty :: Bool -> Query

-- | match if account depth is less than or equal to this value. Depth is
--   sometimes used like a query (for filtering report data) and sometimes
--   like a query option (for controlling display)
Depth :: Int -> Query

-- | match if a tag's name, and optionally its value, is matched by these
--   respective regexps matching the regexp if provided, exists
Tag :: Regexp -> Maybe Regexp -> 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 |
--   QueryOptCostBasis -- ^ show amounts converted to cost where possible |
--   QueryOptDate2 -- ^ show secondary dates instead of primary dates
QueryOptInAcct :: AccountName -> QueryOpt

-- | Construct a payee tag
payeeTag :: Maybe String -> Either RegexError Query

-- | Construct a note tag
noteTag :: Maybe String -> Either RegexError Query

-- | Construct a generated-transaction tag
generatedTransactionTag :: Query

-- | Convert a query expression containing zero or more space-separated
--   terms to a query and zero or more query options; or return an error
--   message if query parsing fails.
--   
--   A query term is either:
--   
--   
--   
- a search pattern, which matches on one or more fields,
--   eg:acct:REGEXP - match the account name with a regular expression
--   desc:REGEXP - match the transaction description date:PERIODEXP - match
--   the date with a period expression
--   
--   
--   The prefix indicates the field to match, or if there is no prefix
--   account name is assumed.
--   
--   
--   
- a query option, which modifies the reporting behaviour in some
--   way. There is currently one of these, which may appear only
--   once:inacct:FULLACCTNAME
--   
--   
--   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.
--   
--   Period expressions may contain relative dates, so a reference date is
--   required to fully parse these.
--   
--   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
--   
--   
--   >>> parseQuery nulldate "expenses:dining out"
--   Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
--   
--   
--   
--   >>> parseQuery nulldate "\"expenses:dining out\""
--   Right (Acct (RegexpCI "expenses:dining out"),[])
--   
parseQuery :: Day -> Text -> Either String (Query, [QueryOpt])
simplifyQuery :: Query -> Query

-- | Remove query terms (or whole sub-expressions) not matching the given
--   predicate from this query. XXX Semantics not completely clear.
filterQuery :: (Query -> Bool) -> Query -> Query

-- | Does this query match everything ?
queryIsNull :: Query -> Bool
queryIsAcct :: Query -> Bool
queryIsAmt :: Query -> Bool
queryIsDepth :: Query -> Bool
queryIsDate :: Query -> Bool
queryIsDate2 :: Query -> Bool
queryIsDateOrDate2 :: 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
queryIsSym :: Query -> Bool
queryIsReal :: Query -> Bool
queryIsStatus :: Query -> Bool
queryIsEmpty :: 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 -> Maybe Int

-- | 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 ?
matchesTransaction :: Query -> Transaction -> Bool

-- | Does the match expression match this posting ?
--   
--   Note that for account match we try both original and effective account
matchesPosting :: Query -> Posting -> Bool

-- | Does the match expression match this account ? A matching in: clause
--   is also considered a match. When matching by account name pattern, if
--   there's a regular expression error, this function calls error.
matchesAccount :: Query -> AccountName -> Bool
matchesMixedAmount :: Query -> MixedAmount -> Bool

-- | Does the match expression match this (simple) amount ?
matchesAmount :: Query -> Amount -> Bool
matchesCommodity :: Query -> CommoditySymbol -> Bool

-- | Does the query match the name and optionally the value of any of these
--   tags ?
matchesTags :: Regexp -> Maybe Regexp -> [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]
prefixes :: [Text]
tests_Query :: TestTree
instance GHC.Classes.Eq Hledger.Query.QueryOpt
instance GHC.Show.Show Hledger.Query.QueryOpt
instance GHC.Show.Show Hledger.Query.Query
instance GHC.Classes.Eq Hledger.Query.Query
instance GHC.Classes.Eq Hledger.Query.OrdPlus
instance GHC.Show.Show Hledger.Query.OrdPlus

-- | A TransactionModifier is a rule that modifies certain
--   Transactions, 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 :: Day -> [TransactionModifier] -> [Transaction] -> Either String [Transaction]

-- | A TimeclockEntry is a clock-in, clock-out, or other directive
--   in a timeclock file (see timeclock.el or the command-line version).
--   These can be converted to Transactions and queried like a
--   ledger.
module Hledger.Data.Timeclock

-- | Convert time log entries to journal transactions. When there is no
--   clockout, add one with the provided current time. Sessions crossing
--   midnight are split into days to give accurate per-day totals.
timeclockEntriesToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]
tests_Timeclock :: TestTree
instance GHC.Show.Show Hledger.Data.Types.TimeclockEntry
instance GHC.Show.Show Hledger.Data.Types.TimeclockCode
instance GHC.Read.Read Hledger.Data.Types.TimeclockCode

-- | An Account has a name, a list of subaccounts, an optional
--   parent account, and subaccounting-excluding and -including balances.
module Hledger.Data.Account
nullacct :: Account

-- | Derive 1. an account tree and 2. each account's total exclusive and
--   inclusive changes from a list of postings. 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] -> [Account]

-- | Convert a list of account names to a tree of Account objects, with
--   just the account names filled in. A single root account with the given
--   name is added.
accountTree :: AccountName -> [AccountName] -> Account

-- | Tie the knot so all subaccounts' parents are set correctly.
tieAccountParents :: Account -> Account

-- | Get this account's parent accounts, from the nearest up to the root.
parentAccounts :: Account -> [Account]

-- | List the accounts at each level of the account tree.
accountsLevels :: Account -> [[Account]]

-- | Map a (non-tree-structure-modifying) function over this and sub
--   accounts.
mapAccounts :: (Account -> Account) -> Account -> Account

-- | Is the predicate true on any of this account or its subaccounts ?
anyAccounts :: (Account -> Bool) -> Account -> Bool

-- | Add subaccount-inclusive balances to an account tree.
sumAccounts :: Account -> Account

-- | Remove all subaccounts below a certain depth.
clipAccounts :: Int -> Account -> Account

-- | 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 :: Maybe Int -> [Account] -> [Account]

-- | Remove all leaf accounts and subtrees matching a predicate.
pruneAccounts :: (Account -> Bool) -> Account -> Maybe Account

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

-- | Filter an account tree (to a list).
filterAccounts :: (Account -> Bool) -> Account -> [Account]

-- | Sort each group of siblings in an account tree by inclusive amount, so
--   that the accounts with largest normal balances are listed first. The
--   provided normal balance sign determines whether normal balances are
--   negative or positive, affecting the sort order. Ie, if balances are
--   normally negative, then the most negative balances sort first, and
--   vice versa.
sortAccountTreeByAmount :: NormalSign -> Account -> Account

-- | Add extra info for this account derived from the Journal's account
--   directives, if any (comment, tags, declaration order..).
accountSetDeclarationInfo :: Journal -> Account -> Account

-- | 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 -> Account
accountDeclarationOrderAndName :: Account -> (Int, AccountName)

-- | Search an account list by name.
lookupAccount :: AccountName -> [Account] -> Maybe Account
printAccounts :: Account -> IO ()
showAccounts :: Account -> String
showAccountsBoringFlag :: Account -> String
showAccountDebug :: PrintfType t => Account -> t
instance GHC.Show.Show Hledger.Data.Types.Account
instance GHC.Classes.Eq Hledger.Data.Types.Account

-- | A PeriodicTransaction is a rule describing recurring
--   transactions.
module Hledger.Data.PeriodicTransaction

-- | Generate transactions from PeriodicTransaction within a
--   DateSpan
--   
--   Note that new transactions require txnTieKnot post-processing.
--   The new transactions will have three tags added: - a
--   recur:PERIODICEXPR tag whose value is the generating periodic
--   expression - a generated-transaction: tag - a hidden
--   _generated-transaction: tag which does not appear in the comment.
--   
--   
--   >>> import Data.Time (fromGregorian)
--   
--   >>> _ptgen "monthly from 2017/1 to 2017/4"
--   2017-01-01
--       ; generated-transaction: ~ monthly from 2017/1 to 2017/4
--       a           $1.00
--   
--   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
--   
--   
--   
--   >>> _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
--   
--   
--   
--   >>> _ptgen "every 2nd day of month from 2017/02 to 2017/04"
--   2017-01-02
--       ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04
--       a           $1.00
--   
--   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
--   
--   
--   
--   >>> _ptgen "every 30th day of month from 2017/1 to 2017/5"
--   2016-12-30
--       ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5
--       a           $1.00
--   
--   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
--   
--   
--   
--   >>> _ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"
--   2016-12-08
--       ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4
--       a           $1.00
--   
--   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
--   
--   
--   
--   >>> _ptgen "every nov 29th from 2017 to 2019"
--   2016-11-29
--       ; generated-transaction: ~ every nov 29th from 2017 to 2019
--       a           $1.00
--   
--   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
--   
--   
--   
--   >>> _ptgen "2017/1"
--   2017-01-01
--       ; generated-transaction: ~ 2017/1
--       a           $1.00
--   
--   
--   
--   >>> _ptgen ""
--   *** Exception: failed to parse...
--   ...
--   
--   
--   
--   >>> _ptgen "weekly from 2017"
--   *** Exception: Unable to generate transactions according to "weekly from 2017" because 2017-01-01 is not a first day of the Week
--   
--   
--   
--   >>> _ptgen "monthly from 2017/5/4"
--   *** Exception: Unable to generate transactions according to "monthly from 2017/5/4" because 2017-05-04 is not a first day of the Month
--   
--   
--   
--   >>> _ptgen "every quarter from 2017/1/2"
--   *** Exception: Unable to generate transactions according to "every quarter from 2017/1/2" because 2017-01-02 is not a first day of the Quarter
--   
--   
--   
--   >>> _ptgen "yearly from 2017/1/14"
--   *** Exception: Unable to generate transactions according to "yearly from 2017/1/14" because 2017-01-14 is not a first day of the Year
--   
--   
--   
--   >>> let reportperiod="daily from 2018/01/03" in let (i,s) = parsePeriodExpr' nulldate reportperiod in runPeriodicTransaction (nullperiodictransaction{ptperiodexpr=reportperiod, ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1]}) (DateSpan (Just $ fromGregorian 2018 01 01) (Just $ fromGregorian 2018 01 03))
--   []
--   
--   
--   
--   >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ fromGregorian 2020 01 01) (Just $ fromGregorian 2020 02 01))
--   
--   
--   
--   >>> _ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ fromGregorian 2020 02 01) (Just $ fromGregorian 2020 03 01))
--   2020-02-01
--       ; generated-transaction: ~ every 3 months from 2019-05
--       a           $1.00
--   
--   
--   >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ fromGregorian 2018 01 01) (Just $ 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
--   
--   
--   >>> _ptgenspan "every 3 days from 2018" (DateSpan (Just $ fromGregorian 2018 01 02) (Just $ fromGregorian 2018 01 05))
--   2018-01-04
--       ; generated-transaction: ~ every 3 days from 2018
--       a           $1.00
--   
runPeriodicTransaction :: PeriodicTransaction -> DateSpan -> [Transaction]

-- | 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.Show.Show Hledger.Data.Types.PeriodicTransaction

-- | A Journal is a set of transactions, plus optional related data.
--   This is hledger's primary data object. It is usually parsed from a
--   journal file or other data format (see Hledger.Read).
module Hledger.Data.Journal
addPriceDirective :: PriceDirective -> Journal -> Journal
addTransactionModifier :: TransactionModifier -> Journal -> Journal
addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addTransaction :: Transaction -> Journal -> Journal

-- | Infer any missing amounts (to satisfy balance assignments and to
--   balance transactions) and check that all transactions balance and
--   (optional) all balance assertions pass. Or return an error message
--   (just the first error encountered).
--   
--   Assumes journalInferCommodityStyles has been called, since those
--   affect transaction balancing.
--   
--   This does multiple things at once because amount inferring, balance
--   assignments, balance assertions and posting dates are interdependent.
journalBalanceTransactions :: Bool -> Journal -> Either String Journal

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

-- | Choose and apply a consistent display style to the posting amounts in
--   each commodity. Each commodity's style is specified by a commodity (or
--   D) directive, or otherwise inferred from posting amounts. Can return
--   an error message eg if inconsistent number formats are found.
journalApplyCommodityStyles :: Journal -> Either String Journal

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

-- | Get the canonical amount styles for this journal, whether declared by
--   commodity directives, by the last default commodity (D) directive, or
--   inferred from posting amounts, as a map from symbol to style. Styles
--   declared by directives take precedence (and commodity takes precedence
--   over D). Styles from directives are guaranteed to specify the decimal
--   mark character.
journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle

-- | Convert all this journal's amounts to cost using the transaction
--   prices, if any. The journal's commodity styles are applied to the
--   resulting amounts.
journalToCost :: Journal -> 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 :: ClockTime -> 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

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

-- | Within each posting's amount, keep only the parts matching the query.
--   This can leave unbalanced transactions.
filterJournalAmounts :: Query -> Journal -> Journal

-- | Filter out all parts of this transaction's amounts which do not match
--   the query. This can leave the transaction unbalanced.
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionPostings :: Query -> Transaction -> Transaction

-- | Filter out all parts of this posting's amount which do not match the
--   query.
filterPostingAmount :: Query -> Posting -> Posting

-- | Apply a transformation to a journal's transactions.
mapJournalTransactions :: (Transaction -> Transaction) -> Journal -> Journal

-- | Apply a transformation to a journal's postings.
mapJournalPostings :: (Posting -> Posting) -> Journal -> Journal

-- | Apply a transformation to a transaction's postings.
mapTransactionPostings :: (Posting -> Posting) -> Transaction -> Transaction

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

-- | Get an ordered list of AmountStyles from the amounts in this
--   journal which influence canonical amount display styles. See
--   traverseJournalAmounts. journalAmounts :: Journal -> [Amount]
--   journalAmounts = getConst . traverseJournalAmounts (Const . (:[]))
--   
--   | Apply a transformation to the journal amounts traversed by
--   traverseJournalAmounts. overJournalAmounts :: (Amount -> Amount)
--   -> Journal -> Journal overJournalAmounts f = runIdentity .
--   traverseJournalAmounts (Identity . f)
--   
--   | A helper that traverses over most amounts in the journal, in
--   particular the ones which influence canonical amount display styles,
--   processing them with the given applicative function.
--   
--   These include, in the following order:
--   
--   
--   
- the amount in the final default commodity (D) directive
--   
- amounts in market price (P) directives (in parse order)
--   
- posting amounts in transactions (in parse order)
--   
--   
--   Transaction price amounts, which may be embedded in posting amounts
--   (the aprice field), are left intact but not traversed/processed.
--   
--   traverseJournalAmounts :: Applicative f => (Amount -> f Amount)
--   -> Journal -> f Journal traverseJournalAmounts f j = recombine
--   $ (traverse . dcamt) f (jparsedefaultcommodity j) *
--   (traverse . pdamt) f (jpricedirectives j) * (traverse . tps .
--   traverse . pamt . amts . traverse) f (jtxns j) where recombine pds
--   txns = j { jpricedirectives = pds, jtxns = txns } -- a bunch of
--   traversals dcamt g pd = (mdc -> case mdc of Nothing -> Nothing
--   Just ((c,stpd{pdamount =amt} ) $ g (pdamount pd) pdamt g pd =
--   (amt -> pd{pdamount =amt}) $ g (pdamount pd) tps g t = (ps
--   -> t {tpostings=ps }) $ g (tpostings t) pamt g p = (amt
--   -> p {pamount =amt}) $ g (pamount p) amts g (Mixed as) =
--   Mixed $ g as
--   
--   The fully specified 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 earliest of this journal's transaction and posting dates, or
--   Nothing if there are none.
journalStartDate :: Bool -> Journal -> Maybe Day

-- | The latest of this journal's transaction and posting dates, or Nothing
--   if there are none.
journalEndDate :: Bool -> Journal -> Maybe Day

-- | Unique transaction descriptions used in this journal.
journalDescriptions :: Journal -> [Text]
journalFilePath :: Journal -> FilePath
journalFilePaths :: 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]

-- | A query for Asset, Liability & Equity accounts in this journal. Cf
--   http://en.wikipedia.org/wiki/Chart_of_accounts#Balance_Sheet_Accounts.
journalBalanceSheetAccountQuery :: Journal -> Query

-- | A query for Profit & Loss accounts in this journal. Cf
--   http://en.wikipedia.org/wiki/Chart_of_accounts#Profit_.26_Loss_accounts.
journalProfitAndLossAccountQuery :: Journal -> Query

-- | A query for accounts in this journal which have been declared as
--   Revenue by account directives, or otherwise for accounts with names
--   matched by the case-insensitive regular expression
--   ^(income|revenue)s?(:|$).
journalRevenueAccountQuery :: Journal -> Query

-- | A query for accounts in this journal which have been declared as
--   Expense by account directives, or otherwise for accounts with names
--   matched by the case-insensitive regular expression
--   ^expenses?(:|$).
journalExpenseAccountQuery :: Journal -> Query

-- | A query for accounts in this journal which have been declared as Asset
--   (or Cash, a subtype of Asset) by account directives, or otherwise for
--   accounts with names matched by the case-insensitive regular expression
--   ^assets?(:|$).
journalAssetAccountQuery :: Journal -> Query

-- | A query for accounts in this journal which have been declared as
--   Liability by account directives, or otherwise for accounts with names
--   matched by the case-insensitive regular expression
--   ^(debts?|liabilit(y|ies))(:|$).
journalLiabilityAccountQuery :: Journal -> Query

-- | A query for accounts in this journal which have been declared as
--   Equity by account directives, or otherwise for accounts with names
--   matched by the case-insensitive regular expression
--   ^equity(:|$).
journalEquityAccountQuery :: Journal -> Query

-- | A query for Cash (liquid asset) accounts in this journal, ie
--   accounts declared as Cash by account directives, or otherwise with
--   names matched by the case-insensitive regular expression
--   ^assets?(:|$). and not including the case-insensitive regular
--   expression (investment|receivable|:A/R|:fixed).
journalCashAccountQuery :: Journal -> Query

-- | Given a list of amount styles (assumed to be from parsed amounts in a
--   single commodity), in parse order, choose a canonical style.
--   Traditionally it's "the style of the first, with the maximum precision
--   of all".
canonicalStyleFrom :: [AmountStyle] -> AmountStyle
nulljournal :: Journal

-- | Check any balance assertions in the journal and return an error
--   message if any of them fail (or if the transaction balancing they
--   require fails).
journalCheckBalanceAssertions :: Journal -> Maybe String
journalNumberAndTieTransactions :: 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.
journalModifyTransactions :: Day -> Journal -> Either String Journal
samplejournal :: Journal
tests_Journal :: TestTree
instance GHC.Show.Show Hledger.Data.Types.Journal
instance GHC.Base.Semigroup Hledger.Data.Types.Journal
instance Data.Default.Class.Default Hledger.Data.Types.Journal

-- | A Ledger is derived from a Journal by applying a filter
--   specification to select Transactions and Postings 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
--   Ledger, containing the journal plus the tree of all its
--   accounts with their subaccount-inclusive and subaccount-exclusive
--   balances. If the query includes a depth limit, the ledger's journal
--   will be depth limited, but the ledger's account tree will not.
ledgerFromJournal :: Query -> Journal -> Ledger

-- | List a ledger's account names.
ledgerAccountNames :: Ledger -> [AccountName]

-- | Get the named account from a ledger.
ledgerAccount :: Ledger -> AccountName -> Maybe Account

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

-- | List a ledger's top-level accounts (the ones below the root), in tree
--   order.
ledgerTopAccounts :: Ledger -> [Account]

-- | List a ledger's bottom-level (subaccount-less) accounts, in tree
--   order.
ledgerLeafAccounts :: Ledger -> [Account]

-- | 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.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
tests_Data :: TestTree

-- | 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:
--   
--   
--   
- a list of each column's period (date span)
--   
- a list of rows, each containing:
--   
--   
--   
--   
- an account label
--   
- the account's depth
--   
- A list of amounts, one for each column. Depending on the value
--   type, these can represent balance changes, ending balances, budget
--   performance, etc. (for example, see BalanceType and
--   Hledger.Cli.Commands.Balance).
--   
- the total of the row's amounts for a periodic report, or zero for
--   cumulative/historical reports (since summing end balances generally
--   doesn't make sense).
--   
- the average of the row's amounts
--   
--   
--   
--   
- the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.
--   
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 " A change in balance during a certain period."
type Balance = MixedAmount " An ending balance as of some date."
type Total = MixedAmount " The sum of 'Change's in a report or a report row. Does not make sense for 'Balance's."
type Average = MixedAmount " The average of 'Change's or 'Balance's in a report or report row."

-- | Figure out the overall date span of a PeridicReport
periodicReportSpan :: PeriodicReport a b -> DateSpan

-- | Given a PeriodicReport and its normal balance sign, if it is known to
--   be normally negative, convert it to normally positive.
prNormaliseSign :: Num b => NormalSign -> PeriodicReport a b -> PeriodicReport a b

-- | 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:
--   
--   
--   
- an overall title
--   
- the period (date span) of each column
--   
- one or more named, normal-positive multi balance reports, with
--   columns corresponding to the above, and a flag indicating whether they
--   increased or decreased the overall totals
--   
- a list of overall totals for each column, and their grand total
--   and average
--   
--   
--   It is used in compound balance report commands like balancesheet,
--   cashflow and incomestatement.
data CompoundPeriodicReport a b
CompoundPeriodicReport :: String -> [DateSpan] -> [(String, PeriodicReport a b, Bool)] -> PeriodicReportRow () b -> CompoundPeriodicReport a b
[cbrTitle] :: CompoundPeriodicReport a b -> String
[cbrDates] :: CompoundPeriodicReport a b -> [DateSpan]
[cbrSubreports] :: CompoundPeriodicReport a b -> [(String, PeriodicReport a b, Bool)]
[cbrTotals] :: CompoundPeriodicReport a b -> PeriodicReportRow () b

-- | Description of one subreport within a compound balance report. Part of
--   a CompoundBalanceCommandSpec, but also used in hledger-lib.
data CBCSubreportSpec
CBCSubreportSpec :: String -> (Journal -> Query) -> NormalSign -> Bool -> CBCSubreportSpec
[cbcsubreporttitle] :: CBCSubreportSpec -> String
[cbcsubreportquery] :: CBCSubreportSpec -> Journal -> Query
[cbcsubreportnormalsign] :: CBCSubreportSpec -> NormalSign
[cbcsubreportincreasestotal] :: CBCSubreportSpec -> Bool

-- | A full name, display name, and depth for an account.
data DisplayName
DisplayName :: AccountName -> AccountName -> Int -> DisplayName
[displayFull] :: DisplayName -> AccountName
[displayName] :: DisplayName -> AccountName
[displayDepth] :: DisplayName -> Int

-- | Construct a flat display name, where the full name is also displayed
--   at depth 1
flatDisplayName :: AccountName -> DisplayName

-- | Construct a tree display name, where only the leaf is displayed at its
--   given depth
treeDisplayName :: AccountName -> DisplayName

-- | Get the full, canonical, name of a PeriodicReportRow tagged by a
--   DisplayName.
prrFullName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the display name of a PeriodicReportRow tagged by a DisplayName.
prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName

-- | Get the display depth of a PeriodicReportRow tagged by a DisplayName.
prrDepth :: PeriodicReportRow DisplayName a -> Int
instance GHC.Classes.Ord Hledger.Reports.ReportTypes.DisplayName
instance GHC.Classes.Eq Hledger.Reports.ReportTypes.DisplayName
instance GHC.Show.Show 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.CompoundPeriodicReport a b)
instance GHC.Generics.Generic (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance (GHC.Show.Show a, GHC.Show.Show b) => GHC.Show.Show (Hledger.Reports.ReportTypes.CompoundPeriodicReport a b)
instance (Data.Aeson.Types.ToJSON.ToJSON a, Data.Aeson.Types.ToJSON.ToJSON b) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance GHC.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance GHC.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReport a)
instance (GHC.Show.Show a, GHC.Show.Show b) => GHC.Show.Show (Hledger.Reports.ReportTypes.PeriodicReport a b)
instance (Data.Aeson.Types.ToJSON.ToJSON b, Data.Aeson.Types.ToJSON.ToJSON a) => Data.Aeson.Types.ToJSON.ToJSON (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance GHC.Generics.Generic (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance GHC.Base.Functor (Hledger.Reports.ReportTypes.PeriodicReportRow a)
instance (GHC.Show.Show a, GHC.Show.Show b) => GHC.Show.Show (Hledger.Reports.ReportTypes.PeriodicReportRow a b)
instance Data.Aeson.Types.ToJSON.ToJSON Hledger.Reports.ReportTypes.DisplayName
instance GHC.Num.Num b => GHC.Base.Semigroup (Hledger.Reports.ReportTypes.PeriodicReportRow a b)

-- | 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 :: Maybe Day -> Period -> Interval -> [Status] -> Maybe ValuationType -> Bool -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> Maybe FormatStr -> String -> Bool -> Bool -> Bool -> BalanceType -> AccountListMode -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe NormalSign -> Bool -> Maybe DateSpan -> Bool -> ReportOpts

-- | The current date. A late addition to ReportOpts. Optional, but when
--   set it may affect some reports: Reports use it when picking a -V
--   valuation date. This is not great, adds indeterminacy.
[today_] :: ReportOpts -> Maybe Day
[period_] :: ReportOpts -> Period
[interval_] :: ReportOpts -> Interval

-- | Zero, one, or two statuses to be matched
[statuses_] :: ReportOpts -> [Status]

-- | What value should amounts be converted to ?
[value_] :: ReportOpts -> Maybe ValuationType

-- | Infer market prices from transactions ?
[infer_value_] :: ReportOpts -> Bool
[depth_] :: ReportOpts -> Maybe Int
[date2_] :: ReportOpts -> Bool
[empty_] :: ReportOpts -> Bool
[no_elide_] :: ReportOpts -> Bool
[real_] :: ReportOpts -> Bool
[format_] :: ReportOpts -> Maybe FormatStr

-- | All query arguments space sepeareted and quoted if needed (see
--   quoteIfNeeded)
[query_] :: ReportOpts -> String
[average_] :: ReportOpts -> Bool
[related_] :: ReportOpts -> Bool
[txn_dates_] :: ReportOpts -> Bool
[balancetype_] :: ReportOpts -> BalanceType
[accountlistmode_] :: ReportOpts -> AccountListMode
[drop_] :: ReportOpts -> Int
[row_total_] :: ReportOpts -> Bool
[no_total_] :: ReportOpts -> Bool
[pretty_tables_] :: ReportOpts -> Bool
[sort_amount_] :: ReportOpts -> Bool
[percent_] :: ReportOpts -> Bool

-- | if true, 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
[forecast_] :: ReportOpts -> Maybe DateSpan
[transpose_] :: ReportOpts -> Bool

-- | Which "balance" is being shown in a balance report.
data BalanceType

-- | The change of balance in each period.
PeriodChange :: BalanceType

-- | The accumulated change across multiple periods.
CumulativeChange :: BalanceType

-- | The historical ending balance, including the effect of all postings
--   before the report period. Unless altered by, a query, this is what you
--   would see on a bank statement.
HistoricalBalance :: BalanceType

-- | 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=cost|then|end|now|DATE[,COMM]
data ValuationType

-- | convert to cost commodity using transaction prices, then optionally to
--   given commodity using market prices at posting date
AtCost :: Maybe CommoditySymbol -> 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

-- | works like AtNow in single period reports, like AtEnd in multiperiod
--   reports
AtDefault :: Maybe CommoditySymbol -> ValuationType
type FormatStr = String
defreportopts :: ReportOpts
rawOptsToReportOpts :: RawOpts -> IO ReportOpts

-- | Do extra validation of report options, raising an error if there's a
--   problem.
checkReportOpts :: ReportOpts -> ReportOpts
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.
whichDateFromOpts :: ReportOpts -> WhichDate

-- | Convert this journal's postings' amounts to cost using their
--   transaction prices, if specified by options (-B/--value=cost). Maybe
--   soon superseded by newer valuation code.
journalSelectingAmountFromOpts :: ReportOpts -> Journal -> Journal

-- | Get the report interval, if any, specified by the last of -p/--period,
--   -D--daily, -W--weekly, -M/--monthly etc. options. An interval
--   from --period counts only if it is explicitly defined.
intervalFromRawOpts :: RawOpts -> Interval

-- | get period expression from --forecast option
forecastPeriodFromRawOpts :: Day -> RawOpts -> Maybe DateSpan

-- | Convert report options and arguments to a query. If there is a parsing
--   problem, this function calls error.
queryFromOpts :: Day -> ReportOpts -> Query

-- | Convert report options to a query, ignoring any non-flag command line
--   arguments.
queryFromOptsOnly :: Day -> ReportOpts -> Query

-- | Convert report options and arguments to query options. If there is a
--   parsing problem, this function calls error.
queryOptsFromOpts :: Day -> ReportOpts -> [QueryOpt]

-- | 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 specified by
--   options or queries, or otherwise the earliest and latest transaction
--   or posting dates in the journal. If no dates are specified by
--   options/queries and the journal is empty, returns the null date span.
--   Needs IO to parse smart dates in options/queries.
reportSpan :: Journal -> ReportOpts -> IO DateSpan
reportStartDate :: Journal -> ReportOpts -> IO (Maybe Day)
reportEndDate :: Journal -> ReportOpts -> IO (Maybe Day)

-- | The specified report start/end dates are the dates specified by
--   options or queries, if any. Needs IO to parse smart dates in
--   options/queries.
specifiedStartEndDates :: ReportOpts -> IO (Maybe Day, Maybe Day)
specifiedStartDate :: ReportOpts -> IO (Maybe Day)
specifiedEndDate :: ReportOpts -> IO (Maybe Day)
reportPeriodStart :: ReportOpts -> Maybe Day
reportPeriodOrJournalStart :: ReportOpts -> Journal -> Maybe Day
reportPeriodLastDay :: ReportOpts -> Maybe Day
reportPeriodOrJournalLastDay :: ReportOpts -> Journal -> Maybe Day
valuationTypeIsCost :: ReportOpts -> Bool
valuationTypeIsDefaultValue :: ReportOpts -> Bool
tests_ReportOptions :: TestTree
instance GHC.Show.Show Hledger.Reports.ReportOptions.ReportOpts
instance GHC.Show.Show Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Show.Show Hledger.Reports.ReportOptions.BalanceType
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.BalanceType
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.ReportOpts
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.AccountListMode
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.BalanceType

-- | Postings report, used by the register command.
module Hledger.Reports.PostingsReport

-- | A postings report is a list of postings with a running total, a label
--   for the total field, and a little extra transaction info to help with
--   rendering. This is used eg for the register command.
type PostingsReport = (String, [PostingsReportItem])
type PostingsReportItem = (Maybe Day, Maybe Day, Maybe String, 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 :: ReportOpts -> Query -> Journal -> PostingsReport

-- | 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 Day -> Posting -> MixedAmount -> PostingsReportItem
tests_PostingsReport :: TestTree

-- | 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.
entriesReport :: ReportOpts -> Query -> Journal -> EntriesReport
tests_EntriesReport :: TestTree

-- | 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:
--   
--   
--   
- the transaction, unmodified
--   
- the transaction as seen in the context of the current account and
--   query, which means:
--   
- the transaction date is set to the "transaction context date",
--   which can be different from the transaction's general date: if
--   postings to the current account (and matched by the report query) have
--   their own dates, it's the earliest of these dates.
--   
- the transaction's postings are filtered, excluding any which are
--   not matched by the report query
--   
- a text description of the other account(s) posted to/from
--   
- a flag indicating whether there's more than one other account
--   involved
--   
- the total increase/decrease to the current account
--   
- the report transactions' running total after this transaction; or
--   if historical balance is requested (-H), the historical running total.
--   The historical running total includes transactions from before the
--   report start date if one is specified, filtered by the report query.
--   The historical running total may or may not be the account's
--   historical running balance, depending on the report query.
--   
--   
--   Items are sorted by transaction register date (the earliest date the
--   transaction posts to the current account), most recent first.
--   Reporting intervals are currently ignored.
type AccountTransactionsReport = (String, [AccountTransactionsReportItem])
type AccountTransactionsReportItem = (Transaction, Transaction, Bool, String, MixedAmount, MixedAmount)
accountTransactionsReport :: ReportOpts -> Journal -> Query -> Query -> AccountTransactionsReport

-- | Generate transactions report items from a list of transactions, using
--   the provided user-specified report query, a query specifying which
--   account to use as the focus, a starting balance, a sign-setting
--   function and a balance-summing function. Or with a None current
--   account query, this can also be used for the transactionsReport.
accountTransactionsReportItems :: Query -> Query -> MixedAmount -> (MixedAmount -> MixedAmount) -> [Transaction] -> [AccountTransactionsReportItem]

-- | What is the transaction's date in the context of a particular account
--   (specified with a query) and report query, as in an account register ?
--   It's normally the transaction's general date, but if any posting(s)
--   matched by the report query and affecting the matched account(s) have
--   their own earlier dates, it's the earliest of these dates. Secondary
--   transaction/posting dates are ignored.
transactionRegisterDate :: Query -> Query -> Transaction -> Day
tests_AccountTransactionsReport :: TestTree

-- | A transactions report. Like an EntriesReport, but with more
--   information such as a running balance.
module Hledger.Reports.TransactionsReport

-- | A transactions report includes a list of transactions touching
--   multiple accounts (posting-filtered and unfiltered variants), a
--   running balance, and some other information helpful for rendering a
--   register view (a flag indicating multiple other accounts and a display
--   string describing them) with or without a notion of current
--   account(s). Two kinds of report use this data structure, see
--   transactionsReport and accountTransactionsReport below for details.
type TransactionsReport = (String, [TransactionsReportItem])
type TransactionsReportItem = (Transaction, Transaction, Bool, String, MixedAmount, MixedAmount)

-- | Select transactions from the whole journal. This is similar to a
--   "postingsReport" except with transaction-based report items which are
--   ordered most recent first. XXX Or an EntriesReport - use that instead
--   ? This is used by hledger-web's journal view.
transactionsReport :: ReportOpts -> Journal -> Query -> TransactionsReport

-- | Split a transactions report whose items may involve several
--   commodities, into one or more single-commodity transactions reports.
transactionsReportByCommodity :: TransactionsReport -> [(CommoditySymbol, TransactionsReport)]
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
tests_TransactionsReport :: 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 triple of storage format name, a
--   detector of that format, and a parser from that format to Journal. The
--   type variable m appears here so that rParserr can hold a journal
--   parser, which depends on it.
data Reader m
Reader :: StorageFormat -> [String] -> (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> (MonadIO m => ErroringJournalParser m ParsedJournal) -> Reader m
[rFormat] :: Reader m -> StorageFormat
[rExtensions] :: Reader m -> [String]
[rReadFn] :: Reader m -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal
[rParser] :: Reader m -> MonadIO m => ErroringJournalParser m ParsedJournal

-- | Various options to use when reading journal files. Similar to
--   CliOptions.inputflags, simplifies the journal-reading functions.
data InputOpts
InputOpts :: Maybe StorageFormat -> Maybe FilePath -> [String] -> Bool -> Bool -> Bool -> Bool -> String -> Bool -> 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 anonymisation/obfuscation of the data
[anon_] :: InputOpts -> Bool

-- | don't check balance assertions
[ignore_assertions_] :: 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

-- | generate automatic postings when journal is parsed
[auto_] :: InputOpts -> Bool
definputopts :: InputOpts
rawOptsToInputOpts :: RawOpts -> InputOpts

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

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

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a)

-- | Run a journal parser in some monad. See also: parseWithState.
rjp :: Monad m => JournalParser m a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a)

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
runErroringJournalParser :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either (ParseErrorBundle Text CustomErr) a))

-- | Run an erroring journal parser in some monad. See also:
--   parseWithState.
rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either FinalParseError (Either (ParseErrorBundle Text CustomErr) a))
genericSourcePos :: SourcePos -> GenericSourcePos

-- | Construct a generic start & end line parse position from start and
--   end megaparsec SourcePos's.
journalSourcePos :: SourcePos -> SourcePos -> GenericSourcePos

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

-- | Like parseAndFinaliseJournal but takes a (non-Erroring) JournalParser.
--   Used for timeclock/timedot. TODO: get rid of this, use
--   parseAndFinaliseJournal instead
parseAndFinaliseJournal' :: JournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal

-- | Post-process a Journal that has just been parsed or generated, in this
--   order:
--   
--   
--   
- apply canonical amount styles,
--   
- save misc info and reverse transactions into their original parse
--   order,
--   
- evaluate balance assignments and balance each transaction,
--   
- apply transaction modifiers (auto postings) if enabled,
--   
- check balance assertions if enabled.
--   
- infer transaction-implied market prices from transaction
--   prices
--   
journalFinalise :: InputOpts -> FilePath -> Text -> Journal -> ExceptT String IO Journal
setYear :: Year -> JournalParser m ()
getYear :: JournalParser m (Maybe Year)
setDefaultCommodityAndStyle :: (CommoditySymbol, AmountStyle) -> JournalParser m ()
getDefaultCommodityAndStyle :: JournalParser m (Maybe (CommoditySymbol, AmountStyle))

-- | Get amount style associated with default currency.
--   
--   Returns AmountStyle used to defined by a latest default
--   commodity directive prior to current position within this file or its
--   parents.
getDefaultAmountStyle :: JournalParser m (Maybe AmountStyle)

-- | Lookup currency-specific amount style.
--   
--   Returns AmountStyle used in commodity directive within current
--   journal prior to current position or in its parents files.
getAmountStyle :: CommoditySymbol -> JournalParser m (Maybe AmountStyle)
addDeclaredAccountType :: AccountName -> AccountType -> JournalParser m ()
pushParentAccount :: AccountName -> JournalParser m ()
popParentAccount :: JournalParser m ()
getParentAccount :: JournalParser m AccountName
addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
getAccountAliases :: MonadState Journal m => m [AccountAlias]
clearAccountAliases :: MonadState Journal m => m ()
journalAddFile :: (FilePath, Text) -> Journal -> Journal
statusp :: TextParser m Status
codep :: TextParser m Text
descriptionp :: 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 :: 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 :: JournalParser m LocalTime
secondarydatep :: Day -> TextParser m Day

-- | Parse an account name (plus one following space if present), then
--   apply any parent account prefix and/or account aliases currently in
--   effect, in that order. (Ie first add the parent account prefix, then
--   rewrite with aliases). This calls error if any account alias with an
--   invalid regular expression exists.
modifiedaccountnamep :: JournalParser m 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 spaces (or end of input).
--   Each part is at least one character long, may have single spaces
--   inside it, and starts with a non-whitespace. Note, this means
--   "{account}", "%^!" and ";comment" are all accepted (parent parsers
--   usually prevent/consume the last). It should have required parts to
--   start with an alphanumeric; for now it remains as-is for backwards
--   compatibility.
accountnamep :: TextParser m AccountName

-- | Parse whitespace then an amount, with an optional left or right
--   currency symbol and optional price, or return the special "missing"
--   marker amount.
spaceandamountormissingp :: JournalParser m MixedAmount

-- | Parse a single-commodity amount, with optional symbol on the left or
--   right, followed by, in any order: an optional transaction price, an
--   optional ledger-style lot price, and/or an optional ledger-style lot
--   date. A lot price and lot date will be ignored.
amountp :: JournalParser m Amount

-- | Parse an amount from a string, or get an error.
amountp' :: String -> Amount

-- | Parse a mixed amount from a string, or get an error.
mamountp' :: String -> MixedAmount
commoditysymbolp :: TextParser m CommoditySymbol
priceamountp :: JournalParser m AmountPrice
balanceassertionp :: JournalParser m BalanceAssertion
lotpricep :: JournalParser m ()

-- | Parse a string representation of a number for its value and display
--   attributes.
--   
--   Some international number formats are accepted, eg either period or
--   comma may be used for the decimal mark, and the other of these may be
--   used for separating digit groups in the integer part. See
--   http://en.wikipedia.org/wiki/Decimal_separator for more
--   examples.
--   
--   This returns: the parsed numeric value, the precision (number of
--   digits seen following the decimal mark), the decimal mark character
--   used if any, and the digit group style if any.
numberp :: Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)

-- | 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.
--   
--   
--   >>> parseTest rawnumberp "1,234,567.89"
--   Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
--   
--   >>> parseTest rawnumberp "1,000"
--   Left (AmbiguousNumber "1" ',' "000")
--   
--   >>> parseTest rawnumberp "1 000"
--   Right (WithSeparators ' ' ["1","000"] Nothing)
--   
rawnumberp :: TextParser m (Either AmbiguousNumber RawNumber)
multilinecommentp :: 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.
emptyorcommentlinep :: TextParser m ()

-- | Parse the text of a (possibly multiline) comment following a journal
--   item.
--   
--   
--   >>> rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   >>> rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
--   Right "\n\n"
--   
followingcommentp :: TextParser m Text

-- | Parse a transaction comment and extract its tags.
--   
--   The first line of a transaction may be followed by comments, which
--   begin with semicolons and extend to the end of the line. Transaction
--   comments may span multiple lines, but comment lines below the
--   transaction must be preceded by leading whitespace.
--   
--   200011 ; a transaction comment starting on the same line ... ;
--   extending to the next line account1 $1 account2
--   
--   Tags are name-value pairs.
--   
--   
--   >>> let getTags (_,tags) = tags
--   
--   >>> let parseTags = fmap getTags . rtp transactioncommentp
--   
--   
--   
--   >>> parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   
--   
--   A tag's name must be immediately followed by a colon, without
--   separating whitespace. The corresponding value consists of all the
--   text following the colon up until the next colon or newline, stripped
--   of leading and trailing whitespace.
transactioncommentp :: TextParser m (Text, [Tag])

-- | 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.
--   
--   200011 account1 $1 ; a posting comment starting on the same
--   line ... ; extending to the next line
--   
--   account2 ; a posting comment beginning on the next line
--   
--   Tags are name-value pairs.
--   
--   
--   >>> let getTags (_,tags,_,_) = tags
--   
--   >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing)
--   
--   
--   
--   >>> parseTags "; name1: val1, name2:all this is value2"
--   Right [("name1","val1"),("name2","all this is value2")]
--   
--   
--   A tag's name must be immediately followed by a colon, without
--   separating whitespace. The corresponding value consists of all the
--   text following the colon up until the next colon or newline, stripped
--   of leading and trailing whitespace.
--   
--   Posting dates may be expressed with "date"/"date2" tags or with
--   bracketed date syntax. Posting dates will inherit their year from the
--   transaction date if the year is not specified. We throw parse errors
--   on invalid dates.
--   
--   
--   >>> let getDates (_,_,d1,d2) = (d1, d2)
--   
--   >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
--   
--   
--   
--   >>> parseDates "; date: 1/2, date2: 1999/12/31"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   
--   >>> parseDates "; [1/2=1999/12/31]"
--   Right (Just 2000-01-02,Just 1999-12-31)
--   
--   
--   Example: tags, date tags, and bracketed dates >>> rtp
--   (postingcommentp (Just 2000)) "; a:b, date:34, [=56]" Right
--   ("a:b, date:34, [=56]n",[("a","b"),("date","3/4")],Just
--   2000-03-04,Just 2000-05-06)
--   
--   Example: extraction of dates from date tags ignores trailing text
--   >>> rtp (postingcommentp (Just 2000)) "; date:34=56"
--   Right ("date:34=56n",[("date","34=56")],Just
--   2000-03-04,Nothing)
postingcommentp :: 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.
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
--   Right [("date",2016-01-02),("date2",2016-03-04)]
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"
--   Left ...not a bracketed date...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"
--   Left ...1:2:...well-formed but invalid date: 2016/1/32...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"
--   Left ...1:2:...partial date 1/31 found, but the current year is unknown...
--   
--   
--   
--   >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
--   Left ...1:13:...expecting month or day...
--   
bracketeddatetagsp :: Maybe Year -> TextParser m [(TagName, Day)]

-- | Parse any text beginning with a non-whitespace character, until a
--   double space or the end of input. TODO including characters which
--   normally start a comment (;#) - exclude those ?
singlespacedtextp :: TextParser m Text

-- | Similar to singlespacedtextp, except that the text must only
--   contain characters satisfying the given predicate.
singlespacedtextsatisfyingp :: (Char -> Bool) -> TextParser m Text

-- | Parse one non-newline whitespace character that is not followed by
--   another one.
singlespacep :: TextParser m ()
skipNonNewlineSpaces :: (Stream s, Token s ~ Char) => ParsecT CustomErr s m ()
skipNonNewlineSpaces1 :: (Stream s, Token s ~ Char) => ParsecT CustomErr s m ()
tests_Common :: TestTree
instance GHC.Classes.Eq Hledger.Read.Common.RawNumber
instance GHC.Show.Show Hledger.Read.Common.RawNumber
instance GHC.Classes.Eq Hledger.Read.Common.AmbiguousNumber
instance GHC.Show.Show Hledger.Read.Common.AmbiguousNumber
instance GHC.Classes.Eq Hledger.Read.Common.DigitGrp
instance GHC.Show.Show Hledger.Read.Common.InputOpts
instance GHC.Show.Show Hledger.Read.Common.DigitGrp
instance GHC.Base.Semigroup Hledger.Read.Common.DigitGrp
instance GHC.Base.Monoid Hledger.Read.Common.DigitGrp
instance GHC.Show.Show (Hledger.Read.Common.Reader m)
instance Data.Default.Class.Default Hledger.Read.Common.InputOpts

-- | A reader for the "timedot" file format. Example:
--   
--   
--   #DATE
--    Each dot represents 15m, spaces are ignored
--    numbers with or without a following h represent hours
--    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   .... .... ..
--   
module Hledger.Read.TimedotReader
reader :: MonadIO m => Reader m
timedotfilep :: forall (m :: Type -> Type). JournalParser m ParsedJournal

-- | A reader for the timeclock file format generated by timeclock.el
--   (http://www.emacswiki.org/emacs/TimeClock). Example:
--   
--   
--   i 2007/03/10 12:26:00 hledger
--   o 2007/03/10 17:26:02
--   
--   
--   From timeclock.el 2.6:
--   
--   
--   A timeclock contains data in the form of a single entry per line.
--   Each entry has the form:
--   
--     CODE YYYYMMDD 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.
--   
module Hledger.Read.TimeclockReader
reader :: MonadIO m => Reader m
timeclockfilep :: MonadIO m => JournalParser m ParsedJournal

-- | A reader for CSV data, using an extra rules file to help interpret the
--   data.
module Hledger.Read.CsvReader
reader :: MonadIO m => Reader m
type CSV = [CsvRecord]
type CsvRecord = [CsvValue]
type CsvValue = String

-- | Given a CSV rules file path, what would normally be the corresponding
--   CSV file ?
csvFileFor :: FilePath -> FilePath

-- | Given a CSV file path, what would normally be the corresponding rules
--   file ?
rulesFileFor :: FilePath -> FilePath

-- | An pure-exception-throwing IO action that parses this file's content
--   as CSV conversion rules, interpolating any included files first, and
--   runs some extra validation checks.
parseRulesFile :: FilePath -> ExceptT String IO CsvRules
printCSV :: CSV -> String
tests_CsvReader :: TestTree
instance GHC.Classes.Eq Hledger.Read.CsvReader.ConditionalBlock
instance GHC.Show.Show Hledger.Read.CsvReader.ConditionalBlock
instance GHC.Classes.Eq Hledger.Read.CsvReader.Matcher
instance GHC.Show.Show Hledger.Read.CsvReader.Matcher
instance GHC.Classes.Eq Hledger.Read.CsvReader.MatcherPrefix
instance GHC.Show.Show Hledger.Read.CsvReader.MatcherPrefix
instance GHC.Classes.Eq Hledger.Read.CsvReader.CsvRules
instance GHC.Show.Show Hledger.Read.CsvReader.CsvRules
instance Text.Megaparsec.Error.ShowErrorComponent GHC.Base.String

-- | A reader for hledger's journal file format
--   (http://hledger.org/MANUAL.html#the-journal-file). hledger's
--   journal format is a compatible subset of c++ ledger's
--   (http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format), so
--   this reader should handle many ledger files as well. Example:
--   
--   
--   2012/3/24 gift
--       expenses:gifts  $10
--       assets:cash
--   
--   
--   Journal format supports the include directive which can read files in
--   other formats, so the other file format readers need to be importable
--   and invocable here.
--   
--   Some important parts of journal parsing are therefore kept in
--   Hledger.Read.Common, to avoid import cycles.
module Hledger.Read.JournalReader

-- | 
--   findReader mformat mpath
--   
--   
--   Find the reader named by mformat, if provided. Or, if a file
--   path is provided, find the first reader that handles its file
--   extension, if any.
findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | If a filepath is prefixed by one of the reader names and a colon,
--   split that off. Eg "csv:-" -> (Just "csv", "-").
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
reader :: MonadIO m => Reader m
genericSourcePos :: SourcePos -> GenericSourcePos

-- | 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 (ParseErrorBundle Text CustomErr) a)

-- | Run a journal parser in some monad. See also: parseWithState.
rjp :: Monad m => JournalParser m a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a)
getParentAccount :: JournalParser m AccountName

-- | A journal parser. Accumulates and returns a ParsedJournal,
--   which should be finalised/validated before use.
--   
--   
--   >>> rejp (journalp <* eof) "2015/1/1\n a  0\n"
--   Right (Right Journal  with 1 transactions, 1 accounts)
--   
journalp :: MonadIO m => ErroringJournalParser m ParsedJournal

-- | Parse any journal directive and update the parse state accordingly. Cf
--   http://hledger.org/manual.html#directives,
--   http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives
directivep :: MonadIO m => ErroringJournalParser m ()
defaultyeardirectivep :: JournalParser m ()
marketpricedirectivep :: 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 :: 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 :: JournalParser m Day

-- | Parse an account name (plus one following space if present), then
--   apply any parent account prefix and/or account aliases currently in
--   effect, in that order. (Ie first add the parent account prefix, then
--   rewrite with aliases). This calls error if any account alias with an
--   invalid regular expression exists.
modifiedaccountnamep :: JournalParser m AccountName
postingp :: Maybe Year -> JournalParser m Posting
statusp :: 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.
emptyorcommentlinep :: TextParser m ()

-- | Parse the text of a (possibly multiline) comment following a journal
--   item.
--   
--   
--   >>> rtp followingcommentp ""   -- no comment
--   Right ""
--   
--   >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
--   Right "\n"
--   
--   >>> rtp followingcommentp ";  \n"
--   Right "\n"
--   
--   >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
--   Right "\n\n"
--   
--   >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
--   Right "\n\n"
--   
followingcommentp :: TextParser m Text
accountaliasp :: TextParser m AccountAlias
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.
module Hledger.Read

-- | A file path optionally prefixed by a reader name and colon (journal:,
--   csv:, timedot:, etc.).
type PrefixedFilePath = FilePath

-- | Read the default journal file specified by the environment, or raise
--   an error.
defaultJournal :: IO Journal

-- | Get the default journal file path specified by the environment. Like
--   ledger, we look first for the LEDGER_FILE environment variable, and if
--   that does not exist, for the legacy LEDGER environment variable. If
--   neither is set, or the value is blank, return the hard-coded default,
--   which is .hledger.journal in the users's home directory (or
--   in the current directory, if we cannot determine a home directory).
defaultJournalPath :: IO String

-- | Read a Journal from each specified file path and combine them into
--   one. Or, return the first error message.
--   
--   Combining Journals means concatenating them, basically. The parse
--   state resets at the start of each file, which means that directives
--   & aliases do not affect subsequent sibling or parent files. They
--   do affect included child files though. Also the final parse state
--   saved in the Journal does span all files.
readJournalFiles :: InputOpts -> [PrefixedFilePath] -> IO (Either String Journal)

-- | Read a Journal from this file, or from stdin if the file path is -, or
--   return an error message. The file path can have a READER: prefix.
--   
--   The reader (data format) to use is determined from (in priority
--   order): the mformat_ specified in the input options, if any;
--   the file path's READER: prefix, if any; a recognised file name
--   extension. if none of these identify a known reader, the journal
--   reader is used.
--   
--   The input options can also configure balance assertion checking,
--   automated posting generation, a rules file for converting CSV data,
--   etc.
readJournalFile :: InputOpts -> PrefixedFilePath -> IO (Either String Journal)

-- | If the specified journal file does not exist (and is not "-"), give a
--   helpful error and quit.
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
--   isWindowsUnsafeDotPath).
ensureJournalFileExists :: FilePath -> IO ()

-- | 
--   readJournal iopts mfile txt
--   
--   
--   Read a Journal from some text, or return an error message.
--   
--   The reader (data format) is chosen based on, in this order:
--   
--   
--   
- a reader name provided in iopts
--   
- a reader prefix in the mfile path
--   
- a file extension in mfile
--   
--   
--   If none of these is available, or if the reader name is unrecognised,
--   we use the journal reader. (We used to try all readers in this case;
--   since hledger 1.17, we prefer predictability.)
readJournal :: InputOpts -> Maybe FilePath -> Text -> IO (Either String Journal)

-- | Read a Journal from the given text, assuming journal format; or throw
--   an error.
readJournal' :: Text -> IO Journal
accountaliasp :: TextParser m AccountAlias
postingp :: Maybe Year -> JournalParser m Posting

-- | 
--   findReader mformat mpath
--   
--   
--   Find the reader named by mformat, if provided. Or, if a file
--   path is provided, find the first reader that handles its file
--   extension, if any.
findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)

-- | If a filepath is prefixed by one of the reader names and a colon,
--   split that off. Eg "csv:-" -> (Just "csv", "-").
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
tests_Read :: TestTree

-- | Text.Tabular.AsciiArt from tabular-0.2.2.7, modified to treat wide
--   characters as double width.
module Text.Tabular.AsciiWide

-- | for simplicity, we assume that each cell is rendered on a single line
render :: Bool -> (rh -> String) -> (ch -> String) -> (a -> String) -> Table rh ch a -> String
verticalBar :: Bool -> Char
leftBar :: Bool -> String
rightBar :: Bool -> String
midBar :: Bool -> String
doubleMidBar :: Bool -> String

-- | We stop rendering on the shortest list!
renderColumns :: Bool -> [Int] -> Header String -> String
renderHLine :: VPos -> Bool -> [Int] -> Header String -> Properties -> [String]
renderHLine' :: VPos -> Bool -> Properties -> [Int] -> Header String -> String
data VPos
VT :: VPos
VM :: VPos
VB :: VPos
data HPos
HL :: HPos
HM :: HPos
HR :: HPos
boxchar :: VPos -> HPos -> Properties -> Properties -> Bool -> String
pick :: String -> String -> Bool -> String
lineart :: Properties -> Properties -> Properties -> Properties -> Bool -> String

-- | 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:
--   
--   
--   
- a list of each column's period (date span)
--   
- a list of rows, each containing:
--   
--   
--   
--   
- the full account name, display name, and display depth
--   
- A list of amounts, one for each column.
--   
- the total of the row's amounts for a periodic report
--   
- the average of the row's amounts
--   
--   
--   
--   
- the column totals, and the overall grand total (or zero for
--   cumulative/historical reports) and grand average.
--   
type MultiBalanceReport = PeriodicReport DisplayName MixedAmount
type MultiBalanceReportRow = PeriodicReportRow DisplayName MixedAmount

-- | Generate a multicolumn balance report for the matched accounts,
--   showing the change of balance, accumulated balance, or historical
--   balance in each of the specified periods. If the normalbalance_ option
--   is set, it adjusts the sorting and sign of amounts (see ReportOpts and
--   CompoundBalanceCommand). hledger's most powerful and useful report,
--   used by the balance command (in multiperiod mode) and (via
--   compoundBalanceReport) by the bscfis commands.
multiBalanceReport :: Day -> ReportOpts -> Journal -> MultiBalanceReport

-- | A helper for multiBalanceReport. This one takes an explicit Query
--   instead of deriving one from ReportOpts, and an extra argument, a
--   PriceOracle to be used for looking up market prices. 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 :: ReportOpts -> Query -> Journal -> PriceOracle -> MultiBalanceReport
type CompoundBalanceReport = CompoundPeriodicReport DisplayName MixedAmount

-- | Generate a compound balance report from a list of CBCSubreportSpec.
--   This shares postings between the subreports.
compoundBalanceReport :: Day -> ReportOpts -> Journal -> [CBCSubreportSpec] -> CompoundBalanceReport

-- | A helper for compoundBalanceReport, similar to multiBalanceReportWith.
compoundBalanceReportWith :: ReportOpts -> Query -> Journal -> PriceOracle -> [CBCSubreportSpec] -> CompoundBalanceReport
tableAsText :: ReportOpts -> (a -> String) -> Table String String a -> String

-- | Sort the rows by amount or by account declaration order.
sortRows :: ReportOpts -> Journal -> [MultiBalanceReportRow] -> [MultiBalanceReportRow]

-- | A sorting helper: sort a list of things (eg report rows) keyed by
--   account name to match the provided ordering of those same account
--   names.
sortRowsLike :: [AccountName] -> [PeriodicReportRow DisplayName b] -> [PeriodicReportRow DisplayName b]
tests_MultiBalanceReport :: 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.
type BudgetCell = (Maybe Change, Maybe BudgetGoal)
type BudgetReportRow = PeriodicReportRow DisplayName BudgetCell
type BudgetReport = PeriodicReport DisplayName BudgetCell

-- | Calculate budget goals from all periodic transactions, actual balance
--   changes from the regular transactions, and compare these to get a
--   BudgetReport. Unbudgeted accounts may be hidden or renamed (see
--   budgetRollup).
budgetReport :: ReportOpts -> Bool -> DateSpan -> Day -> Journal -> BudgetReport

-- | Build a Table from a multi-column balance report.
budgetReportAsTable :: ReportOpts -> BudgetReport -> Table String String (Maybe MixedAmount, Maybe MixedAmount)

-- | Render a budget report as plain text suitable for console output.
budgetReportAsText :: ReportOpts -> BudgetReport -> String

-- | Make a name for the given period in a multiperiod report, given the
--   type of balance being reported and the full set of report periods.
--   This will be used as a column heading (or row heading, in a register
--   summary report). We try to pick a useful name as follows:
--   
--   
--   
- ending-balance reports: the period's end date
--   
- balance change reports where the periods are months and all in the
--   same year: the short month name in the current locale
--   
- all other balance change reports: a description of the datespan,
--   abbreviated to compact form if possible (see showDateSpan).
--   
reportPeriodName :: BalanceType -> [DateSpan] -> DateSpan -> String
tests_BudgetReport :: TestTree

-- | Balance report, used by the balance command.
module Hledger.Reports.BalanceReport

-- | A simple balance report. It has:
--   
--   
--   
- a list of items, one per account, each containing:
--   
--   
--   
--   
- the full account name
--   
- the Ledger-style elided short account name (the leaf account name,
--   prefixed by any boring parents immediately above); or with --flat, the
--   full account name again
--   
- the number of indentation steps for rendering a Ledger-style
--   account tree, taking into account elided boring parents, --no-elide
--   and --flat
--   
- an amount
--   
--   
--   
--   
- the total of all amounts
--   
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 :: ReportOpts -> Query -> 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

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

module Hledger
tests_Hledger :: TestTree
