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


-- | Core data types, parsers and functionality for the hledger accounting tools
--   
--   This is a reusable library containing hledger's core functionality.
--   
--   hledger is a cross-platform program for tracking money, time, or any
--   other commodity, using double-entry accounting and a simple, editable
--   file format. It is inspired by and largely compatible with ledger(1).
--   hledger provides command-line, curses and web interfaces, and aims to
--   be a reliable, practical tool for daily use.
@package hledger-lib
@version 1.3


-- | 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')
--   
--   2013<i>4</i>10 update: we now trust that current GHC versions &amp;
--   platforms do the right thing, so this file is a no-op and on its way
--   to being removed. Not carefully tested.
module Hledger.Utils.UTF8IOCompat

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

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

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

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

-- | Computation <a>hGetContents</a> <tt>hdl</tt> returns the list of
--   characters corresponding to the unread portion of the channel or file
--   managed by <tt>hdl</tt>, which is put into an intermediate state,
--   <i>semi-closed</i>. In this state, <tt>hdl</tt> is effectively closed,
--   but items are read from <tt>hdl</tt> on demand and accumulated in a
--   special list returned by <a>hGetContents</a> <tt>hdl</tt>.
--   
--   Any operation that fails because a handle is closed, also fails if a
--   handle is semi-closed. The only exception is <tt>hClose</tt>. A
--   semi-closed handle becomes closed:
--   
--   <ul>
--   <li>if <tt>hClose</tt> is applied to it;</li>
--   <li>if an I/O error occurs when reading an item from the handle;</li>
--   <li>or once the entire contents of the handle has been read.</li>
--   </ul>
--   
--   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:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hGetContents :: Handle -> IO String

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

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

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

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

-- | A string received from or being passed to the operating system, such
--   as a file path, command-line argument, or environment variable name or
--   value. With GHC versions before 7.2 on some platforms (posix) these
--   are typically encoded. When converting, we assume the encoding is
--   UTF-8 (cf
--   <a>http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html#UTF8</a>).
type SystemString = String

-- | Convert a system string to an ordinary string, decoding from UTF-8 if
--   it appears to be UTF8-encoded and GHC version is less than 7.2.
fromSystemString :: SystemString -> String

-- | Convert a unicode string to a system string, encoding with UTF-8 if we
--   are on a posix platform with GHC &lt; 7.2.
toSystemString :: String -> SystemString

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

module Hledger.Utils.Test

-- | Get a Test's label, or the empty string.
testName :: Test -> String

-- | Flatten a Test containing TestLists into a list of single tests.
flattenTests :: Test -> [Test]

-- | Filter TestLists in a Test, recursively, preserving the structure.
filterTests :: (Test -> Bool) -> Test -> Test

-- | Simple way to assert something is some expected value, with no label.
is :: (Eq a, Show a) => a -> a -> Assertion

-- | Assert a parse result is successful, printing the parse error on
--   failure.
assertParse :: (Show t, Show e) => (Either (ParseError t e) a) -> Assertion

-- | Assert a parse result is successful, printing the parse error on
--   failure.
assertParseFailure :: (Either (ParseError t e) a) -> Assertion

-- | Assert a parse result is some expected value, printing the parse error
--   on failure.
assertParseEqual :: (Show a, Eq a, Show t, Show e) => (Either (ParseError t e) a) -> a -> Assertion
printParseError :: (Show a) => a -> IO ()


-- | Easy regular expression helpers, currently based on regex-tdfa. These
--   should:
--   
--   <ul>
--   <li>be cross-platform, not requiring C libraries</li>
--   <li>support unicode</li>
--   <li>support extended regular expressions</li>
--   <li>support replacement, with backreferences etc.</li>
--   <li>support splitting</li>
--   <li>have mnemonic names</li>
--   <li>have simple monomorphic types</li>
--   <li>work with simple strings</li>
--   </ul>
--   
--   Regex strings are automatically compiled into regular expressions the
--   first time they are seen, and these are cached. If you use a huge
--   number of unique regular expressions this might lead to increased
--   memory usage. Several functions have memoised variants (*Memo), which
--   also trade space for time.
--   
--   Current limitations:
--   
--   <ul>
--   <li>(?i) and similar are not supported</li>
--   </ul>
module Hledger.Utils.Regex

-- | Regular expression. Extended regular expression-ish syntax ? But does
--   not support eg (?i) syntax.
type Regexp = String

-- | A replacement pattern. May include numeric backreferences (N).
type Replacement = String
regexMatches :: Regexp -> String -> Bool
regexMatchesCI :: Regexp -> String -> Bool

-- | Replace all occurrences of the regexp with the replacement pattern.
--   The replacement pattern supports numeric backreferences (N) but no
--   other RE syntax.
regexReplace :: Regexp -> Replacement -> String -> String
regexReplaceCI :: Regexp -> Replacement -> String -> String

-- | A memoising version of regexReplace. Caches the result for each search
--   pattern, replacement pattern, target string tuple.
regexReplaceMemo :: Regexp -> Replacement -> String -> String
regexReplaceCIMemo :: Regexp -> Replacement -> String -> String

-- | Replace all occurrences of the regexp, transforming each match with
--   the given function.
regexReplaceBy :: Regexp -> (String -> String) -> String -> String
regexReplaceByCI :: Regexp -> (String -> String) -> String -> String

module Hledger.Utils.Tree
root :: Tree a -> a
subs :: Tree a -> Forest a
branches :: Tree a -> Forest a

-- | List just the leaf nodes of a tree
leaves :: Tree a -> [a]

-- | get the sub-tree rooted at the first (left-most, depth-first)
--   occurrence of the specified node value
subtreeat :: Eq a => a -> Tree a -> Maybe (Tree a)

-- | get the sub-tree for the specified node value in the first tree in
--   forest in which it occurs.
subtreeinforest :: Eq a => a -> [Tree a] -> Maybe (Tree a)

-- | remove all nodes past a certain depth
treeprune :: Int -> Tree a -> Tree a

-- | apply f to all tree nodes
treemap :: (a -> b) -> Tree a -> Tree b

-- | remove all subtrees whose nodes do not fulfill predicate
treefilter :: (a -> Bool) -> Tree a -> Tree a

-- | is predicate true in any node of tree ?
treeany :: (a -> Bool) -> Tree a -> Bool

-- | show a compact ascii representation of a tree
showtree :: Show a => Tree a -> String

-- | show a compact ascii representation of a forest
showforest :: Show a => Forest a -> String

-- | An efficient-to-build tree suggested by Cale Gibbard, probably better
--   than accountNameTreeFrom.
newtype FastTree a
T :: (Map a (FastTree a)) -> FastTree a
emptyTree :: FastTree a
mergeTrees :: (Ord a) => FastTree a -> FastTree a -> FastTree a
treeFromPath :: [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)


-- | 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 colors: come in various intensities, which are controlled by
--   <a>ColorIntensity</a>
data Color :: *
Black :: Color
Red :: Color
Green :: Color
Yellow :: Color
Blue :: Color
Magenta :: Color
Cyan :: Color
White :: Color

-- | ANSI colors come in two intensities
data ColorIntensity :: *
Dull :: ColorIntensity
Vivid :: ColorIntensity


-- | Most data types are defined here to avoid import cycles. Here is an
--   overview of the hledger data model:
--   
--   <pre>
--   Journal                  -- a journal is read from one or more data files. It contains..
--    [Transaction]           -- journal transactions (aka entries), which have date, cleared status, code, description and..
--     [Posting]              -- multiple account postings, which have account name and amount
--    [MarketPrice]           -- historical market prices for commodities
--   
--   Ledger                   -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains..
--    Journal                 -- a filtered copy of the original journal, containing only the transactions and postings we are interested in
--    [Account]               -- all accounts, in tree order beginning with a "root" account", with their balances and sub/parent accounts
--   </pre>
--   
--   For more detailed documentation on each type, see the corresponding
--   modules.
module Hledger.Data.Types
type SmartDate = (String, String, String)
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
DayOfWeek :: Int -> Interval
type AccountName = Text
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 price (none, per unit, or total) in another commodity.
--   Note the price should be a positive number, although this is not
--   enforced.
data Price
NoPrice :: Price
UnitPrice :: Amount -> Price
TotalPrice :: Amount -> Price

-- | Display style for an amount.
data AmountStyle
AmountStyle :: Side -> Bool -> !Int -> 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 -> !Int

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

-- | 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 -> [Int] -> DigitGroupStyle
type CommoditySymbol = Text
data Commodity
Commodity :: CommoditySymbol -> Maybe AmountStyle -> Commodity
[csymbol] :: Commodity -> CommoditySymbol
[cformat] :: Commodity -> Maybe AmountStyle
data Amount
Amount :: CommoditySymbol -> Quantity -> Price -> AmountStyle -> Bool -> Amount
[acommodity] :: Amount -> CommoditySymbol
[aquantity] :: Amount -> Quantity

-- | the (fixed) price for this amount, if any
[aprice] :: Amount -> Price
[astyle] :: Amount -> AmountStyle

-- | amount is a multipier for AutoTransactions
[amultiplier] :: Amount -> Bool
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.

-- | 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
data Posting
Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe Amount -> 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]

-- | optional: the expected balance in this commodity in the account after
--   this posting
[pbalanceassertion] :: Posting -> Maybe Amount

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

-- | original posting if this one is result of any transformations (one
--   level only)
[porigin] :: Posting -> Maybe Posting

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

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

-- | file name, inclusive range of 1-based line numbers (first, last).
JournalSourcePos :: FilePath -> (Int, Int) -> GenericSourcePos
data Transaction
Transaction :: Integer -> GenericSourcePos -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Text -> Transaction

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

-- | any comment lines immediately preceding this transaction
[tpreceding_comment_lines] :: Transaction -> Text
data ModifierTransaction
ModifierTransaction :: Text -> [Posting] -> ModifierTransaction
[mtvalueexpr] :: ModifierTransaction -> Text
[mtpostings] :: ModifierTransaction -> [Posting]
data PeriodicTransaction
PeriodicTransaction :: Text -> [Posting] -> PeriodicTransaction
[ptperiodicexpr] :: PeriodicTransaction -> Text
[ptpostings] :: PeriodicTransaction -> [Posting]
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
data MarketPrice
MarketPrice :: Day -> CommoditySymbol -> Amount -> MarketPrice
[mpdate] :: MarketPrice -> Day
[mpcommodity] :: MarketPrice -> CommoditySymbol
[mpamount] :: MarketPrice -> Amount

-- | 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] -> [AccountName] -> Map CommoditySymbol Commodity -> Map CommoditySymbol AmountStyle -> [MarketPrice] -> [ModifierTransaction] -> [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 (&amp; 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 principal data
[jparsetimeclockentries] :: Journal -> [TimeclockEntry]

-- | accounts that have been declared by account directives
[jaccounts] :: Journal -> [AccountName]

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

-- | commodities and formats inferred from journal amounts
[jinferredcommodities] :: Journal -> Map CommoditySymbol AmountStyle
[jmarketprices] :: Journal -> [MarketPrice]
[jmodifiertxns] :: Journal -> [ModifierTransaction]
[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 <tt>journal</tt> or
--   <tt>csv</tt>. The --output-format option selects one of these for
--   output.
type StorageFormat = String

-- | A hledger journal reader is a triple of storage format name, a
--   detector of that format, and a parser from that format to Journal.
data Reader
Reader :: StorageFormat -> [String] -> (Maybe FilePath -> Bool -> FilePath -> Text -> ExceptT String IO Journal) -> Bool -> Reader
[rFormat] :: Reader -> StorageFormat
[rExtensions] :: Reader -> [String]
[rParser] :: Reader -> Maybe FilePath -> Bool -> FilePath -> Text -> ExceptT String IO Journal
[rExperimental] :: Reader -> Bool

-- | An account, with name, balances and links to parent/subaccounts which
--   let you walk up or down the account tree.
data Account
Account :: AccountName -> MixedAmount -> [Account] -> Int -> MixedAmount -> Maybe Account -> Bool -> Account

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

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

-- | sub-accounts
[asubs] :: Account -> [Account]

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

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

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

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

-- | 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.Generics.Generic Hledger.Data.Types.Account
instance Data.Data.Data Hledger.Data.Types.Account
instance GHC.Generics.Generic Hledger.Data.Types.Journal
instance Data.Data.Data Hledger.Data.Types.Journal
instance GHC.Classes.Eq Hledger.Data.Types.Journal
instance GHC.Generics.Generic Hledger.Data.Types.MarketPrice
instance Data.Data.Data Hledger.Data.Types.MarketPrice
instance GHC.Classes.Ord Hledger.Data.Types.MarketPrice
instance GHC.Classes.Eq Hledger.Data.Types.MarketPrice
instance GHC.Generics.Generic Hledger.Data.Types.TimeclockEntry
instance Data.Data.Data 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 Data.Data.Data 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 Data.Data.Data Hledger.Data.Types.PeriodicTransaction
instance GHC.Classes.Eq Hledger.Data.Types.PeriodicTransaction
instance GHC.Generics.Generic Hledger.Data.Types.ModifierTransaction
instance Data.Data.Data Hledger.Data.Types.ModifierTransaction
instance GHC.Classes.Eq Hledger.Data.Types.ModifierTransaction
instance GHC.Generics.Generic Hledger.Data.Types.Posting
instance Data.Data.Data Hledger.Data.Types.Posting
instance GHC.Generics.Generic Hledger.Data.Types.Transaction
instance Data.Data.Data Hledger.Data.Types.Transaction
instance GHC.Classes.Eq Hledger.Data.Types.Transaction
instance GHC.Generics.Generic Hledger.Data.Types.GenericSourcePos
instance Data.Data.Data 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 Data.Data.Data 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 Data.Data.Data Hledger.Data.Types.PostingType
instance GHC.Show.Show Hledger.Data.Types.PostingType
instance GHC.Classes.Eq Hledger.Data.Types.PostingType
instance GHC.Generics.Generic Hledger.Data.Types.MixedAmount
instance Data.Data.Data Hledger.Data.Types.MixedAmount
instance GHC.Classes.Ord Hledger.Data.Types.MixedAmount
instance GHC.Classes.Eq Hledger.Data.Types.MixedAmount
instance GHC.Generics.Generic Hledger.Data.Types.Price
instance Data.Data.Data Hledger.Data.Types.Price
instance GHC.Classes.Ord Hledger.Data.Types.Price
instance GHC.Classes.Eq Hledger.Data.Types.Price
instance GHC.Generics.Generic Hledger.Data.Types.Amount
instance Data.Data.Data 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 Data.Data.Data 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 Data.Data.Data Hledger.Data.Types.AmountStyle
instance GHC.Show.Show 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 Data.Data.Data 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.Side
instance Data.Data.Data 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 Data.Data.Data 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.Interval
instance Data.Data.Data 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 Data.Data.Data 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.Generics.Generic Hledger.Data.Types.DateSpan
instance Data.Data.Data 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 Data.Data.Data (Data.Decimal.DecimalRaw GHC.Integer.Type.Integer)
instance Data.Data.Data System.Time.ClockTime
instance GHC.Generics.Generic System.Time.ClockTime
instance Control.DeepSeq.NFData Hledger.Data.Types.DateSpan
instance Data.Default.Class.Default Hledger.Data.Types.Period
instance Data.Default.Class.Default Hledger.Data.Types.Interval
instance Control.DeepSeq.NFData Hledger.Data.Types.Interval
instance Control.DeepSeq.NFData Hledger.Data.Types.AccountAlias
instance Control.DeepSeq.NFData Hledger.Data.Types.Side
instance Text.Blaze.ToMarkup Hledger.Data.Types.Quantity
instance Control.DeepSeq.NFData Hledger.Data.Types.Price
instance Control.DeepSeq.NFData Hledger.Data.Types.AmountStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.DigitGroupStyle
instance Control.DeepSeq.NFData Hledger.Data.Types.Commodity
instance Control.DeepSeq.NFData Hledger.Data.Types.Amount
instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmount
instance Control.DeepSeq.NFData Hledger.Data.Types.PostingType
instance Control.DeepSeq.NFData Hledger.Data.Types.Status
instance GHC.Show.Show Hledger.Data.Types.Status
instance Control.DeepSeq.NFData Hledger.Data.Types.Posting
instance GHC.Classes.Eq Hledger.Data.Types.Posting
instance Control.DeepSeq.NFData Hledger.Data.Types.GenericSourcePos
instance Control.DeepSeq.NFData Hledger.Data.Types.Transaction
instance Control.DeepSeq.NFData Hledger.Data.Types.ModifierTransaction
instance Control.DeepSeq.NFData Hledger.Data.Types.PeriodicTransaction
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockCode
instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockEntry
instance Control.DeepSeq.NFData Hledger.Data.Types.MarketPrice
instance Control.DeepSeq.NFData System.Time.ClockTime
instance Control.DeepSeq.NFData Hledger.Data.Types.Journal
instance GHC.Show.Show Hledger.Data.Types.Reader

module Hledger.Utils.Parse

-- | A parser of strict text with generic user state, monad and return
--   type.
type TextParser m a = ParsecT Dec Text m a
type JournalStateParser m a = StateT Journal (ParsecT Dec Text m) a
type JournalParser a = StateT Journal (ParsecT Dec Text Identity) a

-- | A journal parser that runs in IO and can throw an error mid-parse.
type ErroringJournalParser m a = StateT Journal (ParsecT Dec Text (ExceptT String 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 Dec Text m) a] -> StateT s (ParsecT Dec Text m) a
parsewith :: Parsec e Text a -> Text -> Either (ParseError Char e) a
parsewithString :: Parsec e String a -> String -> Either (ParseError Char e) a
parseWithState :: Monad m => st -> StateT st (ParsecT Dec Text m) a -> Text -> m (Either (ParseError Char Dec) a)
parseWithState' :: (Stream s, ErrorComponent e) => st -> StateT st (ParsecT e s Identity) a -> s -> (Either (ParseError (Token s) e) a)
fromparse :: (Show t, Show e) => Either (ParseError t e) a -> a
parseerror :: (Show t, Show e) => ParseError t e -> a
showParseError :: (Show t, Show e) => ParseError t e -> String
showDateParseError :: (Show t, Show e) => ParseError t e -> String
nonspace :: TextParser m Char
spacenonewline :: (Stream s, Char ~ Token s) => ParsecT Dec s m Char
restofline :: TextParser m String
eolof :: TextParser m ()


-- | Debugging helpers
module Hledger.Utils.Debug
pprint :: Show a => a -> IO ()

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

-- | Parsec trace - show the current parsec position and next input, and
--   the provided label if it's non-null.
ptrace :: String -> TextParser m ()

-- | Global debug level, which controls the verbosity of debug output on
--   the console. The default is 0 meaning no debug output. The
--   <tt>--debug</tt> command line flag sets it to 1, or <tt>--debug=N</tt>
--   sets it to a higher value (note: not <tt>--debug N</tt> 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 <tt>debug_</tt> field of <a>CliOpts</a>. {--} {--}
debugLevel :: Int

-- | Convenience aliases for tracePrettyAt.
dbg0 :: Show a => String -> a -> a

-- | Pretty-print a message and the showable value to the console when the
--   debug level is &gt;= 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

-- | Convenience aliases for tracePrettyAtIO. Like dbg, but convenient to
--   insert in an IO monad. 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).
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 ()

-- | Pretty-print a message and a showable value to the console if the
--   debug level is at or above the specified level. At level 0, always
--   prints. Otherwise, uses unsafePerformIO.
tracePrettyAt :: Show a => Int -> String -> a -> a
tracePrettyAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
log0 :: Show a => String -> a -> a

-- | Log a message and a pretty-printed showable value to ./debug.log, if
--   the debug level is at or above the specified level. At level 0, always
--   logs. Otherwise, uses unsafePerformIO.
logPrettyAt :: Show a => Int -> String -> a -> a

-- | print this string to the console before evaluating the expression, if
--   the global debug level is at or above the specified level. Uses
--   unsafePerformIO. dbgtrace :: Int -&gt; String -&gt; a -&gt; a dbgtrace
--   level | debugLevel &gt;= level = trace | otherwise = flip const
--   
--   Print a showable value to the console, with a message, if the debug
--   level is at or above the specified level (uses unsafePerformIO).
--   Values are displayed with show, all on one line, which is hard to
--   read. dbgshow :: Show a =&gt; Int -&gt; String -&gt; a -&gt; a dbgshow
--   level | debugLevel &gt;= level = ltrace | otherwise = flip const
--   
--   Print a showable value to the console, with a message, if the debug
--   level is at or above the specified level (uses unsafePerformIO).
--   Values are displayed with ppShow, each field/constructor on its own
--   line.
dbgppshow :: Show a => Int -> String -> a -> a

-- | Like dbg, then exit the program. Uses unsafePerformIO.
dbgExit :: Show a => String -> a -> a

-- | Print a message and parsec debug info (parse position and next input)
--   to the console when the debug level is at or above this level. Uses
--   unsafePerformIO. pdbgAt :: GenParser m =&gt; Float -&gt; String -&gt;
--   m ()
pdbg :: Int -> String -> TextParser m ()

-- | Like dbg, but writes the output to "debug.log" in the current
--   directory. Uses unsafePerformIO. Can fail due to log file contention
--   if called too quickly ("*** Exception: debug.log: openFile: resource
--   busy (file is locked)").
dbglog :: Show a => String -> a -> a

-- | Convert a generic value into a pretty <a>String</a>, if possible.
ppShow :: Show a => a -> String


-- | String formatting helpers, starting to get a bit out of control.
module Hledger.Utils.String
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
escapeQuotes :: String -> String

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

-- | Quote-aware version of unwords - single-quote strings which contain
--   whitespace
unwords' :: [String] -> String
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
elideLeft :: Int -> String -> String
elideRight :: Int -> String -> String

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

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


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

-- | Remove leading and trailing whitespace.
textstrip :: Text -> Text

-- | Remove leading whitespace.
textlstrip :: Text -> Text

-- | Remove trailing whitespace.
textrstrip :: Text -> Text
textElideRight :: Int -> 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
quotechars :: [Char]
whitespacechars :: [Char]
escapeDoubleQuotes :: Text -> Text
escapeSingleQuotes :: Text -> Text

-- | Strip one matching pair of single or double quotes on the ends of a
--   string.
stripquotes :: Text -> Text
isSingleQuoted :: Text -> Bool
isDoubleQuoted :: Text -> Bool
textUnbracket :: 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
difforzero :: (Num a, Ord a) => a -> a -> a

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

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

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

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


-- | 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 :: (t2, t1, t) -> t2
second3 :: (t1, t2, t) -> t2
third3 :: (t1, t, t2) -> t2
first4 :: (t3, t2, t1, t) -> t3
second4 :: (t2, t3, t1, t) -> t3
third4 :: (t2, t1, t3, t) -> t3
fourth4 :: (t2, t1, t, t3) -> t3
first5 :: (t4, t3, t2, t1, t) -> t4
second5 :: (t3, t4, t2, t1, t) -> t4
third5 :: (t3, t2, t4, t1, t) -> t4
fourth5 :: (t3, t2, t1, t4, t) -> t4
fifth5 :: (t3, t2, t1, t, t4) -> t4
first6 :: (t5, t4, t3, t2, t1, t) -> t5
second6 :: (t4, t5, t3, t2, t1, t) -> t5
third6 :: (t4, t3, t5, t2, t1, t) -> t5
fourth6 :: (t4, t3, t2, t5, t1, t) -> t5
fifth6 :: (t4, t3, t2, t1, t5, t) -> t5
sixth6 :: (t4, t3, t2, t1, t, t5) -> t5
splitAtElement :: Eq a => a -> [a] -> [[a]]
getCurrentLocalTime :: IO LocalTime
getCurrentZonedTime :: IO ZonedTime
isLeft :: Either a b -> Bool
isRight :: Either a b -> Bool

-- | Apply a function the specified number of times. 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
firstJust :: Eq a => [Maybe a] -> Maybe a

-- | Read a file in universal newline mode, handling any of the usual line
--   ending conventions.
readFile' :: FilePath -> IO Text

-- | Read a file in universal newline mode, handling any of the usual line
--   ending conventions.
readFileAnyLineEnding :: FilePath -> IO Text

-- | Read the given file, or standard input if the path is "-", using
--   universal newline mode.
readFileOrStdinAnyLineEnding :: String -> 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]
mapM' :: Monad f => (a -> f b) -> [a] -> f [b]

-- | A string received from or being passed to the operating system, such
--   as a file path, command-line argument, or environment variable name or
--   value. With GHC versions before 7.2 on some platforms (posix) these
--   are typically encoded. When converting, we assume the encoding is
--   UTF-8 (cf
--   <a>http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html#UTF8</a>).
type SystemString = String

-- | Convert a system string to an ordinary string, decoding from UTF-8 if
--   it appears to be UTF8-encoded and GHC version is less than 7.2.
fromSystemString :: SystemString -> String

-- | Convert a unicode string to a system string, encoding with UTF-8 if we
--   are on a posix platform with GHC &lt; 7.2.
toSystemString :: String -> SystemString

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


-- | 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:
--   
--   <ul>
--   <li>Left justify ? Right justified if false</li>
--   <li>Minimum width ? Will be space-padded if narrower than this</li>
--   <li>Maximum width ? Will be clipped if wider than this</li>
--   <li>Which of the standard hledger report item fields to
--   interpolate</li>
--   </ul>
FormatField :: Bool -> (Maybe Int) -> (Maybe Int) -> ReportItemField -> StringFormatComponent

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

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

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

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

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

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

-- | A report item's nth field. May be unimplemented.
FieldNo :: Int -> ReportItemField
tests :: Test
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


-- | 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.
type RawOpts = [(String, String)]
setopt :: String -> String -> RawOpts -> RawOpts
setboolopt :: String -> RawOpts -> RawOpts

-- | Is the named option present ?
inRawOpts :: String -> RawOpts -> Bool
boolopt :: String -> RawOpts -> Bool
stringopt :: String -> RawOpts -> String
maybestringopt :: String -> RawOpts -> Maybe String
listofstringopt :: String -> RawOpts -> [String]
intopt :: String -> RawOpts -> Int
maybeintopt :: String -> RawOpts -> Maybe Int


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

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

-- | Convert PeriodBetweens to a more abstract period where possible.
--   
--   <pre>
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)
--   YearPeriod 1
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)
--   QuarterPeriod 2000 4
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)
--   MonthPeriod 2000 2
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)
--   WeekPeriod 2016-07-25
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)
--   DayPeriod 2000-01-01
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)
--   PeriodBetween 2000-02-28 2000-03-01
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)
--   DayPeriod 2000-02-29
--   
--   &gt;&gt;&gt; simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)
--   DayPeriod 2000-12-31
--   </pre>
simplifyPeriod :: Period -> Period
isLastDayOfMonth :: (Num a, Num a1, Eq a, Eq a1) => Integer -> a1 -> a -> 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.
--   
--   <pre>
--   &gt;&gt;&gt; showPeriod (WeekPeriod (fromGregorian 2016 7 25))
--   "2016/07/25w30"
--   </pre>
showPeriod :: 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) -&gt; current
--   year -&gt; current quarter if it's in selected year, otherwise first
--   quarter of selected year -&gt; current month if it's in selected
--   quarter, otherwise first month of selected quarter -&gt; current week
--   if it's in selected month, otherwise first week of selected month
--   -&gt; today if it's in selected week, otherwise first day of selected
--   week, unless that's in previous month, in which case first day of
--   month containing selected week. Shrinking a day has no effect.
periodShrink :: Day -> Period -> Period
mondayBefore :: Day -> Day
yearMonthContainingWeekStarting :: Day -> (Integer, Int)
quarterContainingMonth :: Integral a => a -> a
firstMonthOfQuarter :: Num a => a -> a
startOfFirstWeekInMonth :: Integer -> Int -> Day


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

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

-- | Parse a couple of date string formats to a time type.
parsedateM :: String -> Maybe Day

-- | Parse a YYYY-MM-DD or YYYY<i>MM</i>DD date string to a Day, or raise
--   an error. For testing/debugging.
--   
--   <pre>
--   &gt;&gt;&gt; parsedate "2008/02/03"
--   2008-02-03
--   </pre>
parsedate :: String -> Day
showDate :: Day -> String

-- | Render a datespan as a display string, abbreviating into a compact
--   form if possible.
showDateSpan :: DateSpan -> String
elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a
prevday :: Day -> Day

-- | Parse a period expression to an Interval and overall DateSpan using
--   the provided reference date, or return a parse error.
parsePeriodExpr :: Day -> Text -> Either (ParseError Char Dec) (Interval, DateSpan)
nulldatespan :: DateSpan
failIfInvalidYear :: (Monad m) => String -> m ()
failIfInvalidMonth :: (Monad m) => String -> m ()
failIfInvalidDay :: (Monad m) => String -> m ()
datesepchar :: TextParser m Char
datesepchars :: [Char]
spanStart :: DateSpan -> Maybe Day
spanEnd :: DateSpan -> Maybe Day

-- | Get overall span enclosing multiple sequentially ordered spans.
spansSpan :: [DateSpan] -> DateSpan

-- | Calculate the intersection of two datespans.
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

-- | Parse a date in any of the formats allowed in ledger's period
--   expressions, and maybe some others:
--   
--   <pre>
--   2004
--   2004/10
--   2004/10/1
--   10/1
--   21
--   october, oct
--   yesterday, today, tomorrow
--   this/next/last week/day/month/quarter/year
--   </pre>
--   
--   Returns a SmartDate, to be converted to a full date later (see
--   fixSmartDate). Assumes any text in the parse stream has been
--   lowercased.
smartdate :: Parser SmartDate

-- | Split a DateSpan into one or more consecutive whole spans of the
--   specified length which enclose it. If no interval is specified, the
--   original span is returned.
--   
--   <h4>Examples:</h4>
--   
--   <pre>
--   &gt;&gt;&gt; let t i d1 d2 = splitSpan i $ mkdatespan d1 d2
--   
--   &gt;&gt;&gt; t NoInterval "2008/01/01" "2009/01/01"
--   [DateSpan 2008]
--   
--   &gt;&gt;&gt; t (Quarters 1) "2008/01/01" "2009/01/01"
--   [DateSpan 2008q1,DateSpan 2008q2,DateSpan 2008q3,DateSpan 2008q4]
--   
--   &gt;&gt;&gt; splitSpan (Quarters 1) nulldatespan
--   [DateSpan -]
--   
--   &gt;&gt;&gt; t (Days 1) "2008/01/01" "2008/01/01"  -- an empty datespan
--   [DateSpan 2008/01/01-2007/12/31]
--   
--   &gt;&gt;&gt; t (Quarters 1) "2008/01/01" "2008/01/01"
--   [DateSpan 2008/01/01-2007/12/31]
--   
--   &gt;&gt;&gt; t (Months 1) "2008/01/01" "2008/04/01"
--   [DateSpan 2008/01,DateSpan 2008/02,DateSpan 2008/03]
--   
--   &gt;&gt;&gt; t (Months 2) "2008/01/01" "2008/04/01"
--   [DateSpan 2008/01/01-2008/02/29,DateSpan 2008/03/01-2008/04/30]
--   
--   &gt;&gt;&gt; t (Weeks 1) "2008/01/01" "2008/01/15"
--   [DateSpan 2007/12/31w01,DateSpan 2008/01/07w02,DateSpan 2008/01/14w03]
--   
--   &gt;&gt;&gt; t (Weeks 2) "2008/01/01" "2008/01/15"
--   [DateSpan 2007/12/31-2008/01/13,DateSpan 2008/01/14-2008/01/27]
--   
--   &gt;&gt;&gt; t (DayOfMonth 2) "2008/01/01" "2008/04/01"
--   [DateSpan 2008/01/02-2008/02/01,DateSpan 2008/02/02-2008/03/01,DateSpan 2008/03/02-2008/04/01]
--   
--   &gt;&gt;&gt; t (DayOfWeek 2) "2011/01/01" "2011/01/15"
--   [DateSpan 2011/01/04-2011/01/10,DateSpan 2011/01/11-2011/01/17]
--   </pre>
splitSpan :: Interval -> DateSpan -> [DateSpan]

-- | Convert a SmartDate to an absolute date using the provided reference
--   date.
--   
--   <h4>Examples:</h4>
--   
--   <pre>
--   &gt;&gt;&gt; :set -XOverloadedStrings
--   
--   &gt;&gt;&gt; let t = fixSmartDateStr (parsedate "2008/11/26")
--   
--   &gt;&gt;&gt; t "0000-01-01"
--   "0000/01/01"
--   
--   &gt;&gt;&gt; t "1999-12-02"
--   "1999/12/02"
--   
--   &gt;&gt;&gt; t "1999.12.02"
--   "1999/12/02"
--   
--   &gt;&gt;&gt; t "1999/3/2"
--   "1999/03/02"
--   
--   &gt;&gt;&gt; t "19990302"
--   "1999/03/02"
--   
--   &gt;&gt;&gt; t "2008/2"
--   "2008/02/01"
--   
--   &gt;&gt;&gt; t "0020/2"
--   "0020/02/01"
--   
--   &gt;&gt;&gt; t "1000"
--   "1000/01/01"
--   
--   &gt;&gt;&gt; t "4/2"
--   "2008/04/02"
--   
--   &gt;&gt;&gt; t "2"
--   "2008/11/02"
--   
--   &gt;&gt;&gt; t "January"
--   "2008/01/01"
--   
--   &gt;&gt;&gt; t "feb"
--   "2008/02/01"
--   
--   &gt;&gt;&gt; t "today"
--   "2008/11/26"
--   
--   &gt;&gt;&gt; t "yesterday"
--   "2008/11/25"
--   
--   &gt;&gt;&gt; t "tomorrow"
--   "2008/11/27"
--   
--   &gt;&gt;&gt; t "this day"
--   "2008/11/26"
--   
--   &gt;&gt;&gt; t "last day"
--   "2008/11/25"
--   
--   &gt;&gt;&gt; t "next day"
--   "2008/11/27"
--   
--   &gt;&gt;&gt; t "this week"  -- last monday
--   "2008/11/24"
--   
--   &gt;&gt;&gt; t "last week"  -- previous monday
--   "2008/11/17"
--   
--   &gt;&gt;&gt; t "next week"  -- next monday
--   "2008/12/01"
--   
--   &gt;&gt;&gt; t "this month"
--   "2008/11/01"
--   
--   &gt;&gt;&gt; t "last month"
--   "2008/10/01"
--   
--   &gt;&gt;&gt; t "next month"
--   "2008/12/01"
--   
--   &gt;&gt;&gt; t "this quarter"
--   "2008/10/01"
--   
--   &gt;&gt;&gt; t "last quarter"
--   "2008/07/01"
--   
--   &gt;&gt;&gt; t "next quarter"
--   "2009/01/01"
--   
--   &gt;&gt;&gt; t "this year"
--   "2008/01/01"
--   
--   &gt;&gt;&gt; t "last year"
--   "2007/01/01"
--   
--   &gt;&gt;&gt; t "next year"
--   "2009/01/01"
--   </pre>
--   
--   t "last wed" "2008<i>11</i>19" t "next friday" "2008<i>11</i>28" t
--   "next january" "2009<i>01</i>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 (ParseError Char Dec) String
fixSmartDateStrEither' :: Day -> Text -> Either (ParseError Char Dec) Day

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

-- | Make a datespan from two valid date strings parseable by parsedate (or
--   raise an error). Eg: mkdatespan "2011<i>1</i>1" "2011<i>12</i>31".
mkdatespan :: String -> String -> DateSpan
instance GHC.Show.Show Hledger.Data.Types.DateSpan


-- | A <a>Commodity</a> is a symbol representing a currency or some other
--   kind of thing we are tracking, and some display preferences that tell
--   how to display <a>Amount</a>s of the commodity - is the symbol on the
--   left or right, are thousands separated by comma, significant decimal
--   places and so on.
module Hledger.Data.Commodity
nonsimplecommoditychars :: [Char]
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
tests_Hledger_Data_Commodity :: Test


-- | A simple <a>Amount</a> is some quantity of money, shares, or anything
--   else. It has a (possibly null) <a>CommoditySymbol</a> and a numeric
--   quantity:
--   
--   <pre>
--   $1
--   £-50
--   EUR 3.44
--   GOOG 500
--   1.5h
--   90 apples
--   0
--   </pre>
--   
--   It may also have an assigned <a>Price</a>, representing this amount's
--   per-unit or total cost in a different commodity. If present, this is
--   rendered like so:
--   
--   <pre>
--   EUR 2 @ $1.50  (unit price)
--   EUR 2 @@ $3   (total price)
--   </pre>
--   
--   A <a>MixedAmount</a> is zero or more simple amounts, so can represent
--   multiple commodities; this is the type most often used:
--   
--   <pre>
--   0
--   $50 + EUR 3
--   16h + $13.55 + AAPL 500 + 6 oranges
--   </pre>
--   
--   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
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 an amount to the commodity of its assigned price, if any.
--   Notes:
--   
--   <ul>
--   <li>price amounts must be MixedAmounts with exactly one component
--   Amount (or there will be a runtime error) XXX</li>
--   <li>price amounts should be positive, though this is not currently
--   enforced</li>
--   </ul>
costOfAmount :: Amount -> Amount

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

-- | 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.
showAmountWithoutPrice :: Amount -> String

-- | For rendering: a special precision value which means show all
--   available digits.
maxprecision :: Int

-- | For rendering: a special precision value which forces display of a
--   decimal point.
maxprecisionwithpoint :: Int

-- | Set an amount's display precision.
setAmountPrecision :: Int -> Amount -> Amount

-- | Set an amount's display precision, flipped.
withPrecision :: Amount -> Int -> 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

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

-- | Convert a mixed amount's component amounts to the commodity of their
--   assigned price, if any.
costOfMixedAmount :: MixedAmount -> MixedAmount

-- | Divide a mixed amount's quantities by a constant.
divideMixedAmount :: MixedAmount -> Quantity -> 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 it can be normalised to a single
--   commodity ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool

-- | Does this amount appear to be zero when displayed with its given
--   precision ?
isZeroAmount :: Amount -> Bool

-- | Is this amount "really" zero, regardless of the display precision ?
isReallyZeroAmount :: Amount -> Bool

-- | Does this mixed amount appear to be zero when displayed with its given
--   precision ?
isZeroMixedAmount :: MixedAmount -> Bool

-- | Is this mixed amount "really" zero ? See isReallyZeroAmount.
isReallyZeroMixedAmount :: MixedAmount -> Bool

-- | Is this mixed amount "really" zero, after converting to cost
--   commodities where possible ?
isReallyZeroMixedAmountCost :: MixedAmount -> Bool

-- | 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, but without any @
--   prices.
showMixedAmountWithoutPrice :: MixedAmount -> String

-- | Get the one-line string representation of a mixed amount, but without
--   any @ prices.
showMixedAmountOneLineWithoutPrice :: MixedAmount -> String

-- | Colour version.
cshowMixedAmountWithoutPrice :: MixedAmount -> String

-- | Colour version.
cshowMixedAmountOneLineWithoutPrice :: 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 :: Int -> MixedAmount -> String

-- | Set the display precision in the amount's commodities.
setMixedAmountPrecision :: Int -> 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_Hledger_Data_Amount :: Test
instance GHC.Show.Show Hledger.Data.Types.MarketPrice
instance GHC.Show.Show Hledger.Data.Types.Amount
instance GHC.Num.Num Hledger.Data.Types.Amount
instance GHC.Show.Show Hledger.Data.Types.MixedAmount
instance GHC.Num.Num Hledger.Data.Types.MixedAmount


-- | A <a>MarketPrice</a> represents a historical exchange rate between two
--   commodities. (Ledger calls them historical prices.) For example,
--   prices published by a stock exchange or the foreign exchange market.
--   Some commands (balance, currently) can use this information to show
--   the market value of things at a given date.
module Hledger.Data.MarketPrice

-- | Get the string representation of an market price, based on its
--   commodity's display settings.
showMarketPrice :: MarketPrice -> String
tests_Hledger_Data_MarketPrice :: Test


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

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

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

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

-- | <ul>
--   <li><i>"a:b:c","d:e"</i> -&gt; ["a","d"]</li>
--   </ul>
topAccountNames :: [AccountName] -> [AccountName]
parentAccountName :: AccountName -> AccountName
parentAccountNames :: 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

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

-- | Convert a list of account names to a tree.
accountNameTreeFrom :: [AccountName] -> Tree AccountName
nullaccountnametree :: IsString a => Tree a

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

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

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

-- | Escape an AccountName for use within a regular expression.
--   &gt;&gt;&gt; putStr $ escapeName "First?!*? %)*!<tt>#" First?!#$*?$(*)
--   !</tt>^
escapeName :: 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 but not
--   its subaccounts.
accountNameToAccountOnlyRegex :: AccountName -> Regexp

-- | Convert an exact account-matching regular expression to a plain
--   account name.
accountRegexToAccountName :: Regexp -> AccountName

-- | Does this string look like an exact account-matching regular
--   expression ?
isAccountRegex :: String -> Bool
tests_Hledger_Data_AccountName :: Test


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

-- | Tags for this posting including implicit and any inherited from its
--   parent transaction.
postingAllImplicitTags :: Posting -> [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

-- | Get the minimal date span which contains all the postings, or the null
--   date span if there are none.
postingsDateSpan :: [Posting] -> DateSpan
postingsDateSpan' :: WhichDate -> [Posting] -> DateSpan
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.
accountNameApplyAliases :: [AccountAlias] -> AccountName -> AccountName

-- | Memoising version of accountNameApplyAliases, maybe overkill.
accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> AccountName
transactionPayee :: Transaction -> Text
transactionNote :: Transaction -> Text

-- | Parse a transaction's description into payee and note (aka narration)
--   fields, assuming a convention of separating these with | (like
--   Beancount). Ie, everything up to the first | is the payee, everything
--   after it is the note. When there's no |, payee == note == description.
payeeAndNoteFromDescription :: Text -> (Text, Text)
sumPostings :: [Posting] -> MixedAmount
showPosting :: Posting -> String
showComment :: Text -> String
tests_Hledger_Data_Posting :: Test
instance GHC.Show.Show Hledger.Data.Types.Posting


-- | A <a>Transaction</a> represents a movement of some commodity(ies)
--   between two or more accounts. It consists of multiple account
--   <a>Posting</a>s which balance to zero, a date, and optional extras
--   like description, cleared status, and tags.
module Hledger.Data.Transaction
nullsourcepos :: GenericSourcePos
nulltransaction :: 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]

-- | Is this transaction balanced ? A balanced transaction's real
--   (non-virtual) postings sum to 0, and any balanced virtual postings
--   also sum to 0.
isTransactionBalanced :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Bool
transactionDate2 :: Transaction -> Day

-- | Get the sums of a transaction's real, virtual, and balanced virtual
--   postings.
transactionPostingBalances :: Transaction -> (MixedAmount, MixedAmount, MixedAmount)

-- | Ensure this transaction is balanced, possibly inferring a missing
--   amount or conversion price(s), or return an error message. Balancing
--   is affected by commodity display precisions, so those can (optionally)
--   be provided.
--   
--   this fails for example, if there are several missing amounts (possibly
--   with balance assignments)
balanceTransaction :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Either String Transaction

-- | More general version of <a>balanceTransaction</a> that takes an update
--   function
balanceTransactionUpdate :: MonadError String m => (AccountName -> MixedAmount -> m ()) -> Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> m Transaction

-- | Show a journal transaction, formatted for the print command. ledger
--   2.x's standard format looks like this:
--   
--   <pre>
--   yyyy<i>mm</i>dd[ *][ CODE] description.........          [  ; comment...............]
--       account name 1.....................  ...$amount1[  ; comment...............]
--       account name 2.....................  ..$-amount1[  ; comment...............]
--   
--   pcodewidth    = no limit -- 10          -- mimicking ledger layout.
--   pdescwidth    = no limit -- 20          -- I don't remember what these mean,
--   pacctwidth    = 35 minimum, no maximum  -- they were important at the time.
--   pamtwidth     = 11
--   pcommentwidth = no limit -- 22
--   </pre>
showTransaction :: Transaction -> String
showTransactionUnelided :: Transaction -> String
showTransactionUnelidedOneLineAmounts :: Transaction -> String
showPostingLine :: Posting -> String

-- | Produce posting line with all comment lines associated with it
showPostingLines :: Posting -> [String]
sourceFilePath :: GenericSourcePos -> FilePath
sourceFirstLine :: GenericSourcePos -> Int
showGenericSourcePos :: GenericSourcePos -> String
tests_Hledger_Data_Transaction :: Test
instance GHC.Show.Show Hledger.Data.Types.Transaction
instance GHC.Show.Show Hledger.Data.Types.ModifierTransaction
instance GHC.Show.Show Hledger.Data.Types.PeriodicTransaction


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

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

-- | Convert a timeclock clockin and clockout entry to an equivalent
--   journal transaction, representing the time expenditure. Note this
--   entry is not balanced, since we omit the "assets:time" transaction for
--   simpler output.
entryFromTimeclockInOut :: TimeclockEntry -> TimeclockEntry -> Transaction
tests_Hledger_Data_Timeclock :: Test
instance GHC.Show.Show Hledger.Data.Types.TimeclockEntry
instance GHC.Show.Show Hledger.Data.Types.TimeclockCode
instance GHC.Read.Read Hledger.Data.Types.TimeclockCode


-- | A general query system for matching things (accounts, postings,
--   transactions..) by various criteria, and a parser 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 than<i>greater
--   than</i>equal 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

-- | Convert a query expression containing zero or more space-separated
--   terms to a query and zero or more query options. A query term is
--   either:
--   
--   <ol>
--   <li>a search pattern, which matches on one or more fields,
--   eg:acct:REGEXP - match the account name with a regular expression
--   desc:REGEXP - match the transaction description date:PERIODEXP - match
--   the date with a period expression</li>
--   </ol>
--   
--   The prefix indicates the field to match, or if there is no prefix
--   account name is assumed.
--   
--   <ol>
--   <li>a query option, which modifies the reporting behaviour in some
--   way. There is currently one of these, which may appear only
--   once:inacct:FULLACCTNAME</li>
--   </ol>
--   
--   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 :: Day -> Text -> (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
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 secondary date span) does this query specify ? For
--   OR expressions, use the widest possible span. NOT is ignored.
queryDateSpan :: Bool -> Query -> DateSpan

-- | What date span (or secondary date span) does this query specify ? For
--   OR expressions, use the widest possible span. NOT is ignored.
queryDateSpan' :: Query -> DateSpan

-- | The depth limit this query specifies, or a large number if none.
queryDepth :: Query -> 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.
matchesAccount :: Query -> AccountName -> Bool
matchesMixedAmount :: Query -> MixedAmount -> Bool

-- | Does the match expression match this (simple) amount ?
matchesAmount :: Query -> Amount -> 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]
tests_Hledger_Query :: Test
instance Data.Data.Data Hledger.Query.Query
instance GHC.Classes.Eq Hledger.Query.Query
instance Data.Data.Data Hledger.Query.OrdPlus
instance GHC.Classes.Eq Hledger.Query.OrdPlus
instance GHC.Show.Show Hledger.Query.OrdPlus
instance Data.Data.Data Hledger.Query.QueryOpt
instance GHC.Classes.Eq Hledger.Query.QueryOpt
instance GHC.Show.Show Hledger.Query.QueryOpt
instance GHC.Show.Show Hledger.Query.Query


-- | This module provides utilities for applying automated transactions
--   like <a>ModifierTransaction</a> and <a>PeriodicTransaction</a>.
module Hledger.Data.AutoTransaction

-- | Builds a <a>Transaction</a> transformer based on
--   <a>ModifierTransaction</a>.
--   
--   <a>Query</a> parameter allows injection of additional restriction on
--   posting match. Don't forget to call <a>txnTieKnot</a>.
--   
--   <pre>
--   &gt;&gt;&gt; runModifierTransaction Any (ModifierTransaction "" ["pong" `post` usd 2]) nulltransaction{tpostings=["ping" `post` usd 1]}
--   0000/01/01
--       ping           $1.00
--       pong           $2.00
--   
--   
--   
--   &gt;&gt;&gt; runModifierTransaction Any (ModifierTransaction "miss" ["pong" `post` usd 2]) nulltransaction{tpostings=["ping" `post` usd 1]}
--   0000/01/01
--       ping           $1.00
--   
--   
--   
--   &gt;&gt;&gt; runModifierTransaction None (ModifierTransaction "" ["pong" `post` usd 2]) nulltransaction{tpostings=["ping" `post` usd 1]}
--   0000/01/01
--       ping           $1.00
--   
--   
--   
--   &gt;&gt;&gt; runModifierTransaction Any (ModifierTransaction "ping" ["pong" `post` amount{amultiplier=True, aquantity=3}]) nulltransaction{tpostings=["ping" `post` usd 2]}
--   0000/01/01
--       ping           $2.00
--       pong           $6.00
--   </pre>
runModifierTransaction :: Query -> ModifierTransaction -> (Transaction -> Transaction)

-- | Generate transactions from <a>PeriodicTransaction</a> within a
--   <a>DateSpan</a>
--   
--   Note that new transactions require <a>txnTieKnot</a> post-processing.
--   
--   <pre>
--   &gt;&gt;&gt; mapM_ (putStr . show) $ runPeriodicTransaction (PeriodicTransaction "monthly from 2017/1 to 2017/4" ["hi" `post` usd 1]) nulldatespan
--   2017/01/01
--       hi           $1.00
--   
--   2017/02/01
--       hi           $1.00
--   
--   2017/03/01
--       hi           $1.00
--   </pre>
runPeriodicTransaction :: PeriodicTransaction -> (DateSpan -> [Transaction])

-- | Extract <a>Query</a> equivalent of <a>mtvalueexpr</a> from
--   <a>ModifierTransaction</a>
--   
--   <pre>
--   &gt;&gt;&gt; mtvaluequery (ModifierTransaction "" []) undefined
--   Any
--   
--   &gt;&gt;&gt; mtvaluequery (ModifierTransaction "ping" []) undefined
--   Acct "ping"
--   
--   &gt;&gt;&gt; mtvaluequery (ModifierTransaction "date:2016" []) undefined
--   Date (DateSpan 2016)
--   
--   &gt;&gt;&gt; mtvaluequery (ModifierTransaction "date:today" []) (read "2017-01-01")
--   Date (DateSpan 2017/01/01)
--   </pre>
mtvaluequery :: ModifierTransaction -> (Day -> Query)

-- | <a>DateSpan</a> of all dates mentioned in <a>Journal</a>
--   
--   <pre>
--   &gt;&gt;&gt; jdatespan nulljournal
--   DateSpan -
--   
--   &gt;&gt;&gt; jdatespan nulljournal{jtxns=[nulltransaction{tdate=read "2016-01-01"}] }
--   DateSpan 2016/01/01
--   
--   &gt;&gt;&gt; jdatespan nulljournal{jtxns=[nulltransaction{tdate=read "2016-01-01", tpostings=[nullposting{pdate=Just $ read "2016-02-01"}]}] }
--   DateSpan 2016/01/01-2016/02/01
--   </pre>
jdatespan :: Journal -> DateSpan


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

-- | Apply additional account aliases (eg from the command-line) to all
--   postings in a journal.
journalApplyAliases :: [AccountAlias] -> Journal -> Journal

-- | Fill in any missing amounts and check that all journal transactions
--   balance, or return an error message. This is done after parsing all
--   amounts and applying canonical commodity styles, since balancing
--   depends on display precision. Reports only the first error
--   encountered.
journalBalanceTransactions :: Bool -> Journal -> Either String Journal

-- | Choose and apply a consistent display format to the posting amounts in
--   each commodity. Each commodity's format is specified by a commodity
--   format directive, or otherwise inferred from posting amounts as in
--   hledger &lt; 0.28.
journalApplyCommodityStyles :: Journal -> Journal

-- | Given a list of amounts in parse order, build a map from their
--   commodity names to standard commodity display formats.
commodityStylesFromAmounts :: [Amount] -> Map CommoditySymbol AmountStyle

-- | Convert all this journal's amounts to cost by applying their prices,
--   if any.
journalConvertAmountsToCost :: Journal -> Journal

-- | Do post-parse processing on a parsed journal to make it ready for use.
--   Reverse parsed data to normal order, canonicalise amount formats,
--   check/ensure that transactions are balanced, and maybe check balance
--   assertions.
journalFinalise :: ClockTime -> FilePath -> Text -> Bool -> ParsedJournal -> Either String Journal

-- | Keep only transactions matching the query expression.
filterJournalTransactions :: Query -> Journal -> Journal

-- | Keep only postings matching the query expression. This can leave
--   unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal

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

-- | Unique account names in this journal, including parent accounts
--   containing no postings.
journalAccountNames :: Journal -> [AccountName]

-- | Unique account names posted to in this journal.
journalAccountNamesUsed :: Journal -> [AccountName]

-- | Get an ordered list of the amounts in this journal which will
--   influence amount style canonicalisation. These are:
--   
--   <ul>
--   <li>amounts in market price directives (in parse order)</li>
--   <li>amounts in postings (in parse order)</li>
--   </ul>
--   
--   Amounts in default commodity directives also influence
--   canonicalisation, but earlier, as amounts are parsed. Amounts in
--   posting prices are not used for canonicalisation.
journalAmounts :: Journal -> [Amount]

-- | Maps over all of the amounts in the journal
overJournalAmounts :: (Amount -> Amount) -> Journal -> Journal

-- | Traverses over all ofthe amounts in the journal, in the order
--   indicated by <a>journalAmounts</a>.
traverseJournalAmounts :: Applicative f => (Amount -> f Amount) -> Journal -> f Journal

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

-- | 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 &amp; Equity accounts in this journal. Cf
--   <a>http://en.wikipedia.org/wiki/Chart_of_accounts#Balance_Sheet_Accounts</a>.
journalBalanceSheetAccountQuery :: Journal -> Query

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

-- | A query for Income (Revenue) accounts in this journal. This is
--   currently hard-coded to the case-insensitive regex
--   <tt>^(income|revenue)s?(:|$)</tt>.
journalIncomeAccountQuery :: Journal -> Query

-- | A query for Expense accounts in this journal. This is currently
--   hard-coded to the case-insensitive regex <tt>^expenses?(:|$)</tt>.
journalExpenseAccountQuery :: Journal -> Query

-- | A query for Asset accounts in this journal. This is currently
--   hard-coded to the case-insensitive regex <tt>^assets?(:|$)</tt>.
journalAssetAccountQuery :: Journal -> Query

-- | A query for Liability accounts in this journal. This is currently
--   hard-coded to the case-insensitive regex
--   <tt>^(debts?|liabilit(y|ies))(:|$)</tt>.
journalLiabilityAccountQuery :: Journal -> Query

-- | A query for Equity accounts in this journal. This is currently
--   hard-coded to the case-insensitive regex <tt>^equity(:|$)</tt>.
journalEquityAccountQuery :: Journal -> Query

-- | A query for Cash (-equivalent) accounts in this journal (ie, accounts
--   which appear on the cashflow statement.) This is currently hard-coded
--   to be all the Asset accounts except for those containing the
--   case-insensitive regex <tt>(receivable|A/R)</tt>.
journalCashAccountQuery :: Journal -> Query

-- | Given an ordered list of amount styles, choose a canonical style. That
--   is: the style of the first, and the maximum precision of all.
canonicalStyleFrom :: [AmountStyle] -> AmountStyle

-- | Check if a set of hledger account/description filter patterns matches
--   the given account name or entry description. Patterns are
--   case-insensitive regular expressions. Prefixed with not:, they become
--   anti-patterns.
matchpats :: [String] -> String -> Bool
nulljournal :: Journal

-- | Check any balance assertions in the journal and return an error
--   message if any of them fail.
journalCheckBalanceAssertions :: Journal -> Either String Journal
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
samplejournal :: Journal
tests_Hledger_Data_Journal :: Test
instance GHC.Show.Show Hledger.Data.Types.Journal
instance GHC.Base.Monoid Hledger.Data.Types.Journal


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

-- | 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 an AccountName tree to an Account tree
nameTreeToAccount :: AccountName -> FastTree 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).
clipAccountsAndAggregate :: 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]

-- | 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
tests_Hledger_Data_Account :: Test
instance GHC.Show.Show Hledger.Data.Types.Account
instance GHC.Classes.Eq Hledger.Data.Types.Account


-- | A <a>Ledger</a> is derived from a <a>Journal</a> by applying a filter
--   specification to select <a>Transaction</a>s and <a>Posting</a>s of
--   interest. It contains the filtered journal and knows the resulting
--   chart of accounts, account balances, and postings in each account.
module Hledger.Data.Ledger
nullledger :: Ledger

-- | Filter a journal's transactions with the given query, then derive a
--   ledger containing the chart of accounts and balances. If the query
--   includes a depth limit, that will affect the ledger's journal but not
--   the ledger's account tree.
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]

-- | Accounts in ledger whose name matches the pattern, in tree order.
ledgerAccountsMatching :: [String] -> 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_ledgerFromJournal :: [Test]
tests_Hledger_Data_Ledger :: Test
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_Hledger_Data :: Test


-- | Some common parsers and helpers used by several readers. Some of these
--   might belong in Hledger.Read.JournalReader or Hledger.Read.
module Hledger.Read.Common

-- | Run a string parser with no state in the identity monad.
runTextParser :: TextParser Identity a -> Text -> Either (ParseError Char Dec) a

-- | Run a string parser with no state in the identity monad.
rtp :: TextParser Identity a -> Text -> Either (ParseError Char Dec) a

-- | Run a journal parser with a null journal-parsing state.
runJournalParser :: Monad m => TextParser m a -> Text -> m (Either (ParseError Char Dec) a)

-- | Run a journal parser with a null journal-parsing state.
rjp :: Monad m => TextParser m a -> Text -> m (Either (ParseError Char Dec) a)

-- | Run an error-raising journal parser with a null journal-parsing state.
runErroringJournalParser :: Monad m => ErroringJournalParser m a -> Text -> m (Either String a)

-- | Run an error-raising journal parser with a null journal-parsing state.
rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either String a)
genericSourcePos :: SourcePos -> GenericSourcePos
journalSourcePos :: SourcePos -> SourcePos -> GenericSourcePos

-- | Given a megaparsec ParsedJournal parser, balance assertion flag, file
--   path and file content: parse and post-process a Journal, or give an
--   error.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> Bool -> FilePath -> Text -> ExceptT String IO Journal
parseAndFinaliseJournal' :: JournalParser ParsedJournal -> Bool -> FilePath -> Text -> ExceptT String IO Journal
setYear :: Year -> JournalStateParser m ()
getYear :: JournalStateParser m (Maybe Year)
setDefaultCommodityAndStyle :: (CommoditySymbol, AmountStyle) -> JournalStateParser m ()
getDefaultCommodityAndStyle :: JournalStateParser m (Maybe (CommoditySymbol, AmountStyle))
pushAccount :: AccountName -> JournalStateParser m ()
pushParentAccount :: AccountName -> JournalStateParser m ()
popParentAccount :: JournalStateParser m ()
getParentAccount :: JournalStateParser m AccountName
addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
getAccountAliases :: MonadState Journal m => m [AccountAlias]
clearAccountAliases :: MonadState Journal m => m ()
journalAddFile :: (FilePath, Text) -> Journal -> Journal

-- | Terminate parsing entirely, returning the given error message with the
--   given parse position prepended.
parserErrorAt :: Monad m => SourcePos -> String -> ErroringJournalParser m a
statusp :: TextParser m Status
codep :: TextParser m String
descriptionp :: JournalStateParser m String

-- | Parse a date in YYYY<i>MM</i>DD format. Hyphen (-) and period (.) are
--   also allowed as separators. The year may be omitted if a default year
--   has been set. Leading zeroes may be omitted.
datep :: JournalStateParser m Day

-- | Parse a date and time in YYYY<i>MM</i>DD HH:MM[:SS][+-ZZZZ] format.
--   Hyphen (-) 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 :: JournalStateParser m LocalTime
secondarydatep :: Day -> JournalStateParser m Day

-- | <pre>
--   &gt; parsewith twoorthreepartdatestringp "2016/01/2"
--   </pre>
--   
--   Right "2016<i>01</i>2" twoorthreepartdatestringp = do n1 &lt;- some
--   digitChar c &lt;- datesepchar n2 &lt;- some digitChar mn3 <a>optional
--   $ char c</a>&gt; some digitChar return $ n1 ++ c:n2 ++ maybe "" (c:)
--   mn3
--   
--   Parse an account name, then apply any parent account prefix and/or
--   account aliases currently in effect.
modifiedaccountnamep :: JournalStateParser m AccountName

-- | Parse an account name. Account names start with a non-space, may have
--   single spaces inside them, and are terminated by two or more spaces
--   (or end of input). Also they have one or more components of at least
--   one character, separated by the account separator char. (This parser
--   will also consume one following space, if present.)
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 :: Monad m => JournalStateParser m MixedAmount

-- | Parse a single-commodity amount, with optional symbol on the left or
--   right, optional unit or total price, and optional (ignored)
--   ledger-style balance assertion or fixed lot price declaration.
amountp :: Monad m => JournalStateParser 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
signp :: TextParser m String
multiplierp :: TextParser m Bool
leftsymbolamountp :: Monad m => JournalStateParser m Amount
rightsymbolamountp :: Monad m => JournalStateParser m Amount
nosymbolamountp :: Monad m => JournalStateParser m Amount
commoditysymbolp :: TextParser m CommoditySymbol
quotedcommoditysymbolp :: TextParser m CommoditySymbol
simplecommoditysymbolp :: TextParser m CommoditySymbol
priceamountp :: Monad m => JournalStateParser m Price
partialbalanceassertionp :: Monad m => JournalStateParser m (Maybe Amount)
fixedlotpricep :: Monad m => JournalStateParser m (Maybe Amount)

-- | 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 point, and the other of these may be
--   used for separating digit groups in the integer part. See
--   <a>http://en.wikipedia.org/wiki/Decimal_separator</a> for more
--   examples.
--   
--   This returns: the parsed numeric value, the precision (number of
--   digits seen following the decimal point), the decimal point character
--   used if any, and the digit group style if any.
numberp :: TextParser m (Quantity, Int, Maybe Char, Maybe DigitGroupStyle)
multilinecommentp :: JournalStateParser m ()
emptyorcommentlinep :: JournalStateParser m ()

-- | Parse a possibly multi-line comment following a semicolon.
followingcommentp :: JournalStateParser m Text

-- | Parse a possibly multi-line comment following a semicolon, and any
--   tags and/or posting dates within it. Posting dates can be expressed
--   with "date"<i>"date2" tags and</i>or bracketed dates. The dates are
--   parsed in full here so that errors are reported in the right position.
--   Missing years can be inferred if a default date is provided.
--   
--   <pre>
--   &gt;&gt;&gt; rejp (followingcommentandtagsp (Just $ fromGregorian 2000 1 2)) "; a:b, date:3/4, [=5/6]"
--   Right ("a:b, date:3/4, [=5/6]\n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06)
--   </pre>
--   
--   Year unspecified and no default provided -&gt; unknown year error, at
--   correct position: &gt;&gt;&gt; rejp (followingcommentandtagsp Nothing)
--   " ; xxx date:3/4n ; second line" Left ...1:22...partial date 3/4
--   found, but the current year is unknown...
--   
--   Date tag value contains trailing text - forgot the comma, confused:
--   the syntaxes ? We'll accept the leading date anyway &gt;&gt;&gt; rejp
--   (followingcommentandtagsp (Just $ fromGregorian 2000 1 2)) ";
--   date:3<i>4=5</i>6" Right
--   ("date:3<i>4=5</i>6n",[("date","3<i>4=5</i>6")],Just
--   2000-03-04,Nothing)
followingcommentandtagsp :: MonadIO m => Maybe Day -> ErroringJournalParser m (Text, [Tag], Maybe Day, Maybe Day)
commentp :: JournalStateParser m Text
commentchars :: [Char]
semicoloncommentp :: JournalStateParser m Text
commentStartingWithp :: [Char] -> JournalStateParser m Text

-- | Extract any tags (name:value ended by comma or newline) embedded in a
--   string.
--   
--   <pre>
--   &gt;&gt;&gt; commentTags "a b:, c:c d:d, e"
--   [("b",""),("c","c d:d")]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; commentTags "a [1/1/1] [1/1] [1], [=1/1/1] [=1/1] [=1] [1/1=1/1/1] [1=1/1/1] b:c"
--   [("b","c")]
--   </pre>
--   
--   <ul>
--   
--   <li>-[("date","1<i>1</i>1"),("date","1<i>1"),("date2","1</i>1<i>1"),("date2","1</i>1"),("date","1<i>1"),("date2","1</i>1<i>1"),("date","1"),("date2","1</i>1/1")]</li>
--   </ul>
--   
--   <pre>
--   &gt;&gt;&gt; commentTags "\na b:, \nd:e, f"
--   [("b",""),("d","e")]
--   </pre>
commentTags :: Text -> [Tag]

-- | Parse all tags found in a string.
tagsp :: Parser [Tag]

-- | Parse everything up till the first tag.
--   
--   <pre>
--   &gt;&gt;&gt; rtp nontagp "\na b:, \nd:e, f"
--   Right "\na "
--   </pre>
nontagp :: Parser String

-- | Tags begin with a colon-suffixed tag name (a word beginning with a
--   letter) and are followed by a tag value (any text up to a comma or
--   newline, whitespace-stripped).
--   
--   <pre>
--   &gt;&gt;&gt; rtp tagp "a:b b , c AuxDate: 4/2"
--   Right ("a","b b")
--   </pre>
tagp :: Parser Tag

-- | <pre>
--   &gt;&gt;&gt; rtp tagnamep "a:"
--   Right "a"
--   </pre>
tagnamep :: Parser Text
tagvaluep :: TextParser m Text

-- | Parse all posting dates found in a string. Posting dates can be
--   expressed with date<i>date2 tags and</i>or bracketed dates. The dates
--   are parsed fully to give useful errors. Missing years can be inferred
--   only if a default date is provided.
postingdatesp :: Monad m => Maybe Day -> ErroringJournalParser m [(TagName, Day)]

-- | Date tags are tags with name "date" or "date2". Their value is parsed
--   as a date, using the provided default date if any for inferring a
--   missing year if needed. Any error in date parsing is reported and
--   terminates parsing.
--   
--   <pre>
--   &gt;&gt;&gt; rejp (datetagp Nothing) "date: 2000/1/2 "
--   Right ("date",2000-01-02)
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (datetagp (Just $ fromGregorian 2001 2 3)) "date2:3/4"
--   Right ("date2",2001-03-04)
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (datetagp Nothing) "date:  3/4"
--   Left ...1:9...partial date 3/4 found, but the current year is unknown...
--   </pre>
datetagp :: Monad m => Maybe Day -> ErroringJournalParser m (TagName, Day)

-- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as "date"
--   and/or "date2" tags. Anything that looks like an attempt at this (a
--   square-bracketed sequence of 0123456789/-.= containing at least one
--   digit and one date separator) is also parsed, and will throw an
--   appropriate error.
--   
--   The dates are parsed in full here so that errors are reported in the
--   right position. A missing year in DATE can be inferred if a default
--   date is provided. A missing year in DATE2 will be inferred from DATE.
--   
--   <pre>
--   &gt;&gt;&gt; rejp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
--   Right [("date",2016-01-02),("date2",2016-03-04)]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (bracketeddatetagsp Nothing) "[1]"
--   Left ...not a bracketed date...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (bracketeddatetagsp Nothing) "[2016/1/32]"
--   Left ...1:11:...bad date: 2016/1/32...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (bracketeddatetagsp Nothing) "[1/31]"
--   Left ...1:6:...partial date 1/31 found, but the current year is unknown...
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; rejp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
--   Left ...1:15:...bad date, different separators...
--   </pre>
bracketeddatetagsp :: Monad m => Maybe Day -> ErroringJournalParser m [(TagName, Day)]


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

-- | An error-throwing 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

-- | An error-throwing action that parses this text as CSV conversion rules
--   and runs some extra validation checks. The file path is for error
--   messages.
parseAndValidateCsvRules :: FilePath -> Text -> ExceptT String IO CsvRules

-- | Look for hledger rules file-style include directives in this text, and
--   interpolate the included files, recursively. Included file paths may
--   be relative to the directory of the provided file path. This is a
--   cheap hack to avoid rewriting the CSV rules parser.
expandIncludes :: FilePath -> Text -> IO Text
transactionFromCsvRecord :: SourcePos -> CsvRules -> CsvRecord -> Transaction
tests_Hledger_Read_CsvReader :: Test
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 the timeclock file format generated by timeclock.el
--   (<a>http://www.emacswiki.org/emacs/TimeClock</a>). Example:
--   
--   <pre>
--   i 2007/03/10 12:26:00 hledger
--   o 2007/03/10 17:26:02
--   </pre>
--   
--   From timeclock.el 2.6:
--   
--   <pre>
--   A timeclock contains data in the form of a single entry per line.
--   Each entry has the form:
--   
--     CODE YYYY<i>MM</i>DD HH:MM:SS [COMMENT]
--   
--   CODE is one of: b, h, i, o or O.  COMMENT is optional when the code is
--   i, o or O.  The meanings of the codes are:
--   
--     b  Set the current time balance, or "time debt".  Useful when
--        archiving old log data, when a debt must be carried forward.
--        The COMMENT here is the number of seconds of debt.
--   
--     h  Set the required working time for the given day.  This must
--        be the first entry for that day.  The COMMENT in this case is
--        the number of hours in this workday.  Floating point amounts
--        are allowed.
--   
--     i  Clock in.  The COMMENT in this case should be the name of the
--        project worked on.
--   
--     o  Clock out.  COMMENT is unnecessary, but can be used to provide
--        a description of how the period went, for example.
--   
--     O  Final clock out.  Whatever project was being worked on, it is
--        now finished.  Useful for creating summary reports.
--   </pre>
module Hledger.Read.TimeclockReader
reader :: Reader
timeclockfilep :: ErroringJournalParser IO ParsedJournal
tests_Hledger_Read_TimeclockReader :: Test


-- | A reader for the "timedot" file format. Example:
--   
--   <pre>
--   #DATE
--    Each dot represents 15m, spaces are ignored
--   
--   # on 2/1, 1h was spent on FOSS haskell work, 0.25h on research, etc.
--   2/1
--   fos.haskell   .... ..
--   biz.research  .
--   inc.client1   .... .... .... .... .... ....
--   
--   2/2
--   biz.research  .
--   inc.client1   .... .... ..
--   </pre>
module Hledger.Read.TimedotReader
reader :: Reader
timedotfilep :: JournalStateParser m ParsedJournal
tests_Hledger_Read_TimedotReader :: Test


-- | A reader for hledger's journal file format
--   (<a>http://hledger.org/MANUAL.html#the-journal-file</a>). hledger's
--   journal format is a compatible subset of c++ ledger's
--   (<a>http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format</a>), so
--   this reader should handle many ledger files as well. Example:
--   
--   <pre>
--   2012/3/24 gift
--       expenses:gifts  $10
--       assets:cash
--   </pre>
--   
--   Journal format supports the include directive which can read files in
--   other formats, so the other file format readers need to be importable
--   here. Some low-level journal syntax parsers which those readers also
--   use are therefore defined separately in Hledger.Read.Common, avoiding
--   import cycles.
module Hledger.Read.JournalReader
reader :: Reader
genericSourcePos :: SourcePos -> GenericSourcePos

-- | Given a megaparsec ParsedJournal parser, balance assertion flag, file
--   path and file content: parse and post-process a Journal, or give an
--   error.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> Bool -> FilePath -> Text -> ExceptT String IO Journal

-- | Run a journal parser with a null journal-parsing state.
runJournalParser :: Monad m => TextParser m a -> Text -> m (Either (ParseError Char Dec) a)

-- | Run a journal parser with a null journal-parsing state.
rjp :: Monad m => TextParser m a -> Text -> m (Either (ParseError Char Dec) a)

-- | Run an error-raising journal parser with a null journal-parsing state.
runErroringJournalParser :: Monad m => ErroringJournalParser m a -> Text -> m (Either String a)

-- | Run an error-raising journal parser with a null journal-parsing state.
rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either String a)
getParentAccount :: JournalStateParser m AccountName

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

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

-- | Parse a date and time in YYYY<i>MM</i>DD HH:MM[:SS][+-ZZZZ] format.
--   Hyphen (-) 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 :: JournalStateParser m LocalTime

-- | Parse a date in YYYY<i>MM</i>DD format. Hyphen (-) and period (.) are
--   also allowed as separators. The year may be omitted if a default year
--   has been set. Leading zeroes may be omitted.
datep :: JournalStateParser m Day

-- | <pre>
--   &gt; parsewith twoorthreepartdatestringp "2016/01/2"
--   </pre>
--   
--   Right "2016<i>01</i>2" twoorthreepartdatestringp = do n1 &lt;- some
--   digitChar c &lt;- datesepchar n2 &lt;- some digitChar mn3 <a>optional
--   $ char c</a>&gt; some digitChar return $ n1 ++ c:n2 ++ maybe "" (c:)
--   mn3
--   
--   Parse an account name, then apply any parent account prefix and/or
--   account aliases currently in effect.
modifiedaccountnamep :: JournalStateParser m AccountName
postingp :: MonadIO m => Maybe Day -> ErroringJournalParser m Posting
statusp :: TextParser m Status
emptyorcommentlinep :: JournalStateParser m ()

-- | Parse a possibly multi-line comment following a semicolon.
followingcommentp :: JournalStateParser m Text
accountaliasp :: TextParser m AccountAlias
tests_Hledger_Read_JournalReader :: Test


-- | 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 <tt>.hledger.journal</tt> in the users's home directory (or
--   in the current directory, if we cannot determine a home directory).
defaultJournalPath :: IO String

-- | <pre>
--   readJournalFiles mformat mrulesfile assrt prefixedfiles
--   </pre>
--   
--   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
--   &amp; aliases do not cross file boundaries. (The final parse state
--   saved in the Journal does span all files, however.)
--   
--   As with readJournalFile, file paths can optionally have a READER:
--   prefix, and the <tt>mformat</tt>, <tt>mrulesfile, and </tt>assrt@
--   arguments are supported (and these are applied to all files).
readJournalFiles :: Maybe StorageFormat -> Maybe FilePath -> Bool -> [PrefixedFilePath] -> IO (Either String Journal)

-- | <pre>
--   readJournalFile mformat mrulesfile assrt prefixedfile
--   </pre>
--   
--   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) is chosen based on (in priority order): the
--   <tt>mformat</tt> argument; the file path's READER: prefix, if any; a
--   recognised file name extension (in readJournal); if none of these
--   identify a known reader, all built-in readers are tried in turn.
--   
--   A CSV conversion rules file (<tt>mrulesfiles</tt>) can be specified to
--   help convert CSV data.
--   
--   Optionally, any balance assertions in the journal can be checked
--   (<tt>assrt</tt>).
readJournalFile :: Maybe StorageFormat -> Maybe FilePath -> Bool -> 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.
ensureJournalFileExists :: FilePath -> IO ()

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

-- | <pre>
--   readJournal mformat mrulesfile assrt mfile txt
--   </pre>
--   
--   Read a Journal from some text, or return an error message.
--   
--   The reader (data format) is chosen based on (in priority order): the
--   <tt>mformat</tt> argument; a recognised file name extension in
--   <tt>mfile</tt> (if provided). If none of these identify a known
--   reader, all built-in readers are tried in turn (returning the first
--   one's error message if none of them succeed).
--   
--   A CSV conversion rules file (<tt>mrulesfiles</tt>) can be specified to
--   help convert CSV data.
--   
--   Optionally, any balance assertions in the journal can be checked
--   (<tt>assrt</tt>).
readJournal :: Maybe StorageFormat -> Maybe FilePath -> Bool -> Maybe FilePath -> Text -> IO (Either String Journal)

-- | Read a Journal from the given text trying all readers in turn, or
--   throw an error.
readJournal' :: Text -> IO Journal
accountaliasp :: TextParser m AccountAlias
postingp :: MonadIO m => Maybe Day -> ErroringJournalParser m Posting
samplejournal :: IO Journal
tests_Hledger_Read :: Test


-- | Options common to most hledger reports.
module Hledger.Reports.ReportOptions

-- | Standard options for customising report filtering and output,
--   corresponding to hledger's command-line options and query language
--   arguments. Used in hledger-lib and above.
data ReportOpts
ReportOpts :: Period -> Interval -> [Status] -> Bool -> Maybe Int -> Maybe DisplayExp -> Bool -> Bool -> Bool -> Bool -> Maybe FormatStr -> String -> Bool -> Bool -> BalanceType -> AccountListMode -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> ReportOpts
[period_] :: ReportOpts -> Period
[interval_] :: ReportOpts -> Interval

-- | Zero, one, or two statuses to be matched
[statuses_] :: ReportOpts -> [Status]
[cost_] :: ReportOpts -> Bool
[depth_] :: ReportOpts -> Maybe Int
[display_] :: ReportOpts -> Maybe DisplayExp
[date2_] :: ReportOpts -> Bool
[empty_] :: ReportOpts -> Bool
[no_elide_] :: ReportOpts -> Bool
[real_] :: ReportOpts -> Bool
[format_] :: ReportOpts -> Maybe FormatStr
[query_] :: ReportOpts -> String
[average_] :: ReportOpts -> Bool
[related_] :: ReportOpts -> Bool
[balancetype_] :: ReportOpts -> BalanceType
[accountlistmode_] :: ReportOpts -> AccountListMode
[drop_] :: ReportOpts -> Int
[row_total_] :: ReportOpts -> Bool
[no_total_] :: ReportOpts -> Bool
[value_] :: ReportOpts -> Bool
[pretty_tables_] :: ReportOpts -> Bool
[color_] :: 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
ALDefault :: AccountListMode
ALTree :: AccountListMode
ALFlat :: AccountListMode
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 t => [t] -> [t]

-- | Report which date we will report on based on --date2.
whichDateFromOpts :: ReportOpts -> WhichDate

-- | Convert this journal's postings' amounts to the cost basis amounts if
--   specified by options.
journalSelectingAmountFromOpts :: ReportOpts -> Journal -> Journal

-- | Convert report options and arguments to a query.
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.
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 start date is the one specified by options or
--   queries, otherwise the earliest transaction or posting date in the
--   journal, otherwise (for an empty journal) nothing. Needs IO to parse
--   smart dates in options/queries.
reportStartDate :: Journal -> ReportOpts -> IO (Maybe Day)

-- | The effective report end date is the one specified by options or
--   queries, otherwise the latest transaction or posting date in the
--   journal, otherwise (for an empty journal) nothing. Needs IO to parse
--   smart dates in options/queries.
reportEndDate :: Journal -> ReportOpts -> IO (Maybe Day)
reportStartEndDates :: Journal -> ReportOpts -> IO (Maybe (Day, Day))
tests_Hledger_Reports_ReportOptions :: Test
instance Data.Data.Data Hledger.Reports.ReportOptions.ReportOpts
instance GHC.Show.Show Hledger.Reports.ReportOptions.ReportOpts
instance Data.Data.Data Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Show.Show Hledger.Reports.ReportOptions.AccountListMode
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.AccountListMode
instance Data.Data.Data Hledger.Reports.ReportOptions.BalanceType
instance GHC.Show.Show Hledger.Reports.ReportOptions.BalanceType
instance GHC.Classes.Eq Hledger.Reports.ReportOptions.BalanceType
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.BalanceType
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.AccountListMode
instance Data.Default.Class.Default Hledger.Reports.ReportOptions.ReportOpts
instance Data.Default.Class.Default GHC.Types.Bool


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

-- | A simple single-column balance report. It has:
--   
--   <ol>
--   <li>a list of items, one per account, each containing:</li>
--   </ol>
--   
--   <ul>
--   <li>the full account name</li>
--   <li>the Ledger-style elided short account name (the leaf account name,
--   prefixed by any boring parents immediately above); or with --flat, the
--   full account name again</li>
--   <li>the number of indentation steps for rendering a Ledger-style
--   account tree, taking into account elided boring parents, --no-elide
--   and --flat</li>
--   <li>an amount</li>
--   </ul>
--   
--   <ol>
--   <li>the total of all amounts</li>
--   </ol>
type BalanceReport = ([BalanceReportItem], MixedAmount)
type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount)

-- | Enabling this makes balance --flat --empty also show parent accounts
--   without postings, in addition to those with postings and a zero
--   balance. Disabling it shows only the latter. No longer supported, but
--   leave this here for a bit. flatShowsPostinglessAccounts = True
--   
--   Generate a simple balance report, containing the matched accounts and
--   their balances (change of balance) during the specified period. This
--   is like PeriodChangeReport with a single column (but more mature, eg
--   this can do hierarchical display).
balanceReport :: ReportOpts -> Query -> Journal -> BalanceReport

-- | Convert all the amounts in a single-column balance report to their
--   value on the given date in their default valuation commodities.
balanceReportValue :: Journal -> Day -> BalanceReport -> BalanceReport
mixedAmountValue :: Journal -> Day -> MixedAmount -> MixedAmount

-- | Find the market value of this amount on the given date, in it's
--   default valuation commodity, based on recorded market prices. If no
--   default valuation commodity can be found, the amount is left
--   unchanged.
amountValue :: Journal -> Day -> Amount -> Amount

-- | 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_Hledger_Reports_BalanceReport :: Test


-- | 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_Hledger_Reports_EntriesReport :: Test


-- | Multi-column balance reports, used by the balance command.
module Hledger.Reports.MultiBalanceReports

-- | A multi balance report is a balance report with one or more columns.
--   It has:
--   
--   <ol>
--   <li>a list of each column's period (date span)</li>
--   <li>a list of row items, each containing:</li>
--   </ol>
--   
--   <ul>
--   <li>the full account name</li>
--   <li>the leaf account name</li>
--   <li>the account's depth</li>
--   <li>the amounts to show in each column</li>
--   <li>the total of the row's amounts</li>
--   <li>the average of the row's amounts</li>
--   </ul>
--   
--   <ol>
--   <li>the column totals and the overall total and average</li>
--   </ol>
--   
--   The meaning of the amounts depends on the type of multi balance
--   report, of which there are three: periodic, cumulative and historical
--   (see <a>BalanceType</a> and <a>Hledger.Cli.Balance</a>).
newtype MultiBalanceReport
MultiBalanceReport :: ([DateSpan], [MultiBalanceReportRow], MultiBalanceReportTotals) -> MultiBalanceReport
type MultiBalanceReportRow = (AccountName, AccountName, Int, [MixedAmount], MixedAmount, 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.
multiBalanceReport :: ReportOpts -> Query -> Journal -> MultiBalanceReport

-- | Convert all the amounts in a multi-column balance report to their
--   value on the given date in their default valuation commodities (which
--   are determined as of that date, not the report interval dates).
multiBalanceReportValue :: Journal -> Day -> MultiBalanceReport -> MultiBalanceReport

-- | Generates a single column BalanceReport like balanceReport, but uses
--   multiBalanceReport, so supports --historical. TODO Does not support
--   boring parent eliding or --flat yet.
singleBalanceReport :: ReportOpts -> Query -> Journal -> BalanceReport
instance GHC.Show.Show Hledger.Reports.MultiBalanceReports.MultiBalanceReport


-- | 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_Hledger_Reports_PostingsReport :: Test


-- | Here are several variants of a transactions report. Transactions
--   reports are like a postings report, but more transaction-oriented, and
--   (in the account-centric variant) relative to a some base account. They
--   are used by hledger-web.
module Hledger.Reports.TransactionsReports

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

-- | 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 account
--   register view, where we want to show one row per transaction, in the
--   context of the current account. Report items consist of:
--   
--   <ul>
--   <li>the transaction, unmodified</li>
--   <li>the transaction as seen in the context of the current account and
--   query, which means:</li>
--   <li>the transaction date is set to the "transaction context date",
--   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.</li>
--   <li>the transaction's postings are filtered, excluding any which are
--   not matched by the report query</li>
--   <li>a text description of the other account(s) posted to/from</li>
--   <li>a flag indicating whether there's more than one other account
--   involved</li>
--   <li>the total increase/decrease to the current account</li>
--   <li>the report transactions' running total after this transaction; or
--   if historical balance is requested (-H), the historical running total.
--   The historical running total includes transactions from before the
--   report start date if one is specified, filtered by the report query.
--   The historical running total may or may not be the account's
--   historical running balance, depending on the report query.</li>
--   </ul>
--   
--   Items are sorted by transaction register date (the earliest date the
--   transaction posts to the current account), most recent first.
--   Reporting intervals are currently ignored.
type AccountTransactionsReport = (String, [AccountTransactionsReportItem])
type AccountTransactionsReportItem = (Transaction, Transaction, Bool, String, MixedAmount, MixedAmount)
triOrigTransaction :: (t5, t4, t3, t2, t1, t) -> t5
triDate :: (t4, Transaction, t3, t2, t1, t) -> Day
triAmount :: (t4, t3, t2, t1, t5, t) -> t5
triBalance :: (t4, t3, t2, t1, t, t5) -> t5
triCommodityAmount :: CommoditySymbol -> (t4, t3, t2, t1, MixedAmount, t) -> MixedAmount
triCommodityBalance :: CommoditySymbol -> (t4, t3, t2, t1, t, 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.
journalTransactionsReport :: ReportOpts -> Journal -> Query -> TransactionsReport
accountTransactionsReport :: ReportOpts -> Journal -> Query -> Query -> AccountTransactionsReport

-- | Split a transactions report whose items may involve several
--   commodities, into one or more single-commodity transactions reports.
transactionsReportByCommodity :: TransactionsReport -> [(CommoditySymbol, TransactionsReport)]

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


-- | 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_Hledger_Reports :: Test


-- | Account balance history report.
module Hledger.Reports.BalanceHistoryReport

-- | Get the historical running inclusive balance of a particular account,
--   from earliest to latest posting date.
accountBalanceHistory :: ReportOpts -> Journal -> Account -> [(Day, MixedAmount)]

module Hledger
tests_Hledger :: Test
