Hledger.Read.Common

hledger-lib-1.41: A library providing the core functionality of hledger

Safe Haskell | None
Language | Haskell2010

Hledger.Read.Common

Contents

- parsing utilities
- parsers
  - transaction bits
  - dates
  - account names
  - account aliases
  - amounts
  - comments
  - bracketed dates
  - misc
- tests

Description

File reading/parsing utilities used by multiple readers, and a good amount of the parsers for journal format, to avoid import cycles when JournalReader imports other readers.

Some of these might belong in Hledger.Read.JournalReader or Hledger.Read.

Synopsis

- data Reader (m :: Type -> Type) = Reader {
  - rFormat :: StorageFormat
  - rExtensions :: [String]
  - rReadFn :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal
  - rParser :: MonadIO m => ErroringJournalParser m ParsedJournal
  }
- data InputOpts = InputOpts {
  - mformat_ :: Maybe StorageFormat
  - mrules_file_ :: Maybe FilePath
  - aliases_ :: [String]
  - anon_ :: Bool
  - new_ :: Bool
  - new_save_ :: Bool
  - pivot_ :: String
  - forecast_ :: Maybe DateSpan
  - posting_account_tags_ :: Bool
  - verbose_tags_ :: Bool
  - reportspan_ :: DateSpan
  - auto_ :: Bool
  - infer_equity_ :: Bool
  - infer_costs_ :: Bool
  - balancingopts_ :: BalancingOpts
  - strict_ :: Bool
  - _defer :: Bool
  - _ioDay :: Day
  }
- class HasInputOpts c where
  - inputOpts :: Lens' c InputOpts
  - aliases :: Lens' c [String]
  - anon__ :: Lens' c Bool
  - auto__ :: Lens' c Bool
  - balancingopts :: Lens' c BalancingOpts
  - defer :: Lens' c Bool
  - forecast :: Lens' c (Maybe DateSpan)
  - infer_costs :: Lens' c Bool
  - infer_equity :: Lens' c Bool
  - ioDay :: Lens' c Day
  - mformat :: Lens' c (Maybe StorageFormat)
  - mrules_file :: Lens' c (Maybe FilePath)
  - new__ :: Lens' c Bool
  - new_save :: Lens' c Bool
  - pivot :: Lens' c String
  - posting_account_tags :: Lens' c Bool
  - reportspan :: Lens' c DateSpan
  - strict :: Lens' c Bool
  - verbose_tags :: Lens' c Bool
- definputopts :: InputOpts
- rawOptsToInputOpts :: Day -> Bool -> Bool -> RawOpts -> InputOpts
- parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal
- initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal
- journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal
- journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal
- journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal
- setYear :: forall (m :: Type -> Type). Year -> JournalParser m ()
- getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year)
- setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m ()
- getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle))
- getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle)
- getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle)
- addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m ()
- addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m ()
- pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m ()
- popParentAccount :: forall (m :: Type -> Type). JournalParser m ()
- getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName
- addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
- getAccountAliases :: MonadState Journal m => m [AccountAlias]
- clearAccountAliases :: MonadState Journal m => m ()
- journalAddFile :: (FilePath, Text) -> Journal -> Journal
- statusp :: forall (m :: Type -> Type). TextParser m Status
- codep :: forall (m :: Type -> Type). TextParser m Text
- descriptionp :: forall (m :: Type -> Type). TextParser m Text
- datep :: forall (m :: Type -> Type). JournalParser m Day
- datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime
- secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day
- modifiedaccountnamep :: forall (m :: Type -> Type). JournalParser m AccountName
- accountnamep :: forall (m :: Type -> Type). TextParser m AccountName
- accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias
- spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount
- amountp :: forall (m :: Type -> Type). JournalParser m Amount
- amountp' :: forall (m :: Type -> Type). Bool -> JournalParser m Amount
- commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol
- costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost
- balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion
- lotcostp :: forall (m :: Type -> Type). JournalParser m ()
- numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
- fromRawNumber :: RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
- rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber)
- parseamount :: String -> Either HledgerParseErrors Amount
- parseamount' :: String -> Amount
- parsemixedamount :: String -> Either HledgerParseErrors MixedAmount
- parsemixedamount' :: String -> MixedAmount
- isLineCommentStart :: Char -> Bool
- isSameLineCommentStart :: Char -> Bool
- multilinecommentp :: forall (m :: Type -> Type). TextParser m ()
- emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m ()
- emptyorcommentlinep2 :: forall (m :: Type -> Type). [Char] -> TextParser m ()
- followingcommentp :: forall (m :: Type -> Type). TextParser m Text
- transactioncommentp :: forall (m :: Type -> Type). TextParser m (Text, [Tag])
- commentlinetagsp :: forall (m :: Type -> Type). TextParser m [Tag]
- postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)
- bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)]
- doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text
- noncommenttextp :: forall (m :: Type -> Type). TextParser m Text
- noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text
- singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text
- singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text
- singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text
- singlespacep :: forall (m :: Type -> Type). TextParser m ()
- skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
- skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
- aliasesFromOpts :: InputOpts -> [AccountAlias]
- tests_Common :: TestTree

# Documentation

data Reader (m :: Type -> Type) #

A hledger journal reader is a triple of storage format name, a detector of that format, and a parser from that format to Journal. The type variable m appears here so that rParserr can hold a journal parser, which depends on it.

Constructors

Reader |
Fields rFormat :: StorageFormat rExtensions :: [String] rReadFn :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal rParser :: MonadIO m => ErroringJournalParser m ParsedJournal

#### Instances

Instances details

Show (Reader m) # |
Instance details Defined in Hledger.Read.Common Methods showsPrec :: Int -> Reader m -> ShowS # show :: Reader m -> String # showList :: [Reader m] -> ShowS #

data InputOpts #

Constructors

InputOpts |
Fields mformat_ :: Maybe StorageFormat a file/storage format to try, unless overridden by a filename prefix. Nothing means try all. mrules_file_ :: Maybe FilePath a conversion rules file to use (when reading CSV) aliases_ :: [String] account name aliases to apply anon_ :: Bool do light obfuscation of the data ? Now corresponds to --obfuscate, not the old --anon flag. new_ :: Bool read only new transactions since this file was last read ? new_save_ :: Bool save latest new transactions state for next time ? pivot_ :: String use the given field's value as the account name forecast_ :: Maybe DateSpan span in which to generate forecast transactions posting_account_tags_ :: Bool propagate account tags to postings ? verbose_tags_ :: Bool add user-visible tags when generating/modifying transactions & postings ? reportspan_ :: DateSpan a dirty hack keeping the query dates in InputOpts. This rightfully lives in ReportSpec, but is duplicated here. auto_ :: Bool generate extra postings according to auto posting rules ? infer_equity_ :: Bool infer equity conversion postings from costs ? infer_costs_ :: Bool infer costs from equity conversion postings ? distinct from BalancingOpts{infer_balancing_costs_} balancingopts_ :: BalancingOpts options for transaction balancing strict_ :: Bool do extra correctness checks ? _defer :: Bool internal flag: postpone checks, because we are processing multiple files ? _ioDay :: Day today's date, for use with forecast transactions XXX this duplicates _rsDay, and should eventually be removed when it's not needed anymore.

#### Instances

Instances details

Show InputOpts # |
Instance details Defined in Hledger.Read.InputOptions Methods showsPrec :: Int -> InputOpts -> ShowS # show :: InputOpts -> String # showList :: [InputOpts] -> ShowS #
HasBalancingOpts InputOpts # |
Instance details Defined in Hledger.Read.InputOptions Methods balancingOpts :: Lens' InputOpts BalancingOpts # commodity_styles :: Lens' InputOpts (Maybe (Map CommoditySymbol AmountStyle)) # ignore_assertions :: Lens' InputOpts Bool # infer_balancing_costs :: Lens' InputOpts Bool #
HasInputOpts InputOpts # |
Instance details Defined in Hledger.Read.InputOptions Methods inputOpts :: Lens' InputOpts InputOpts # aliases :: Lens' InputOpts [String] # anon__ :: Lens' InputOpts Bool # auto__ :: Lens' InputOpts Bool # balancingopts :: Lens' InputOpts BalancingOpts # defer :: Lens' InputOpts Bool # forecast :: Lens' InputOpts (Maybe DateSpan) # infer_costs :: Lens' InputOpts Bool # infer_equity :: Lens' InputOpts Bool # ioDay :: Lens' InputOpts Day # mformat :: Lens' InputOpts (Maybe StorageFormat) # mrules_file :: Lens' InputOpts (Maybe FilePath) # new__ :: Lens' InputOpts Bool # new_save :: Lens' InputOpts Bool # pivot :: Lens' InputOpts String # posting_account_tags :: Lens' InputOpts Bool # reportspan :: Lens' InputOpts DateSpan # strict :: Lens' InputOpts Bool # verbose_tags :: Lens' InputOpts Bool #

class HasInputOpts c where #

Minimal complete definition

inputOpts

Methods

inputOpts :: Lens' c InputOpts #

aliases :: Lens' c [String] #

anon__ :: Lens' c Bool #

auto__ :: Lens' c Bool #

balancingopts :: Lens' c BalancingOpts #

defer :: Lens' c Bool #

forecast :: Lens' c (Maybe DateSpan) #

infer_costs :: Lens' c Bool #

infer_equity :: Lens' c Bool #

ioDay :: Lens' c Day #

mformat :: Lens' c (Maybe StorageFormat) #

mrules_file :: Lens' c (Maybe FilePath) #

new__ :: Lens' c Bool #

new_save :: Lens' c Bool #

pivot :: Lens' c String #

posting_account_tags :: Lens' c Bool #

reportspan :: Lens' c DateSpan #

strict :: Lens' c Bool #

verbose_tags :: Lens' c Bool #

#### Instances

Instances details

HasInputOpts InputOpts # |
Instance details Defined in Hledger.Read.InputOptions Methods inputOpts :: Lens' InputOpts InputOpts # aliases :: Lens' InputOpts [String] # anon__ :: Lens' InputOpts Bool # auto__ :: Lens' InputOpts Bool # balancingopts :: Lens' InputOpts BalancingOpts # defer :: Lens' InputOpts Bool # forecast :: Lens' InputOpts (Maybe DateSpan) # infer_costs :: Lens' InputOpts Bool # infer_equity :: Lens' InputOpts Bool # ioDay :: Lens' InputOpts Day # mformat :: Lens' InputOpts (Maybe StorageFormat) # mrules_file :: Lens' InputOpts (Maybe FilePath) # new__ :: Lens' InputOpts Bool # new_save :: Lens' InputOpts Bool # pivot :: Lens' InputOpts String # posting_account_tags :: Lens' InputOpts Bool # reportspan :: Lens' InputOpts DateSpan # strict :: Lens' InputOpts Bool # verbose_tags :: Lens' InputOpts Bool #

definputopts :: InputOpts #

rawOptsToInputOpts :: Day -> Bool -> Bool -> RawOpts -> InputOpts #

Parse an InputOpts from a RawOpts and a provided date. This will fail with a usage error if the forecast period expression cannot be parsed.

# parsing utilities

parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal #

Given a parser to ParsedJournal, input options, file path and content: run the parser on the content, and finalise the result to get a Journal; or throw an error.

initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal #

Given a parser to ParsedJournal, input options, file path and content: run the parser on the content. This is all steps of `parseAndFinaliseJournal` without the finalisation step, and is used when you need to perform other actions before finalisation, as in parsing Timeclock and Timedot files.

journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal #

Post-process a Journal that has just been parsed or generated, in this order:

- add misc info (file path, read time)
- reverse transactions into their original parse order
- apply canonical commodity styles
- propagate account tags to postings
- maybe add forecast transactions
- propagate account tags to postings (again to affect forecast transactions)
- maybe add auto postings
- propagate account tags to postings (again to affect auto postings)
- evaluate balance assignments and balance each transaction
- maybe check balance assertions
- maybe infer costs from equity postings
- maybe infer equity postings from costs
- manye infer market prices from costs

One correctness check (parseable) has already passed when this function is called. Up to four more are performed here:

- ordereddates (when enabled)
- assertions (when enabled)
- autobalanced (and with --strict, balanced ?), in the journalBalanceTransactions step.

Others (commodities, accounts..) are done later by journalStrictChecks.

journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal #

Generate periodic transactions from all periodic transaction rules in the journal. These transactions are added to the in-memory Journal (but not the on-disk file).

The start & end date for generated periodic transactions are determined in a somewhat complicated way; see the hledger manual -> Periodic transactions.

journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal #

Apply any auto posting rules to generate extra postings on this journal's transactions. With a true first argument, adds visible tags to generated postings and modified transactions.

setYear :: forall (m :: Type -> Type). Year -> JournalParser m () #

getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year) #

setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m () #

getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle)) #

getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle) #

Get amount style associated with default currency.

Returns `AmountStyle` used to defined by a latest default commodity directive prior to current position within this file or its parents.

getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle) #

Get the `AmountStyle` declared by the most recently parsed (in the current or parent files, prior to the current position) commodity directive for the given commodity, if any.

addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m () #

addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m () #

pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m () #

popParentAccount :: forall (m :: Type -> Type). JournalParser m () #

getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName #

addAccountAlias :: MonadState Journal m => AccountAlias -> m () #

getAccountAliases :: MonadState Journal m => m [AccountAlias] #

clearAccountAliases :: MonadState Journal m => m () #

journalAddFile :: (FilePath, Text) -> Journal -> Journal #

# parsers

## transaction bits

statusp :: forall (m :: Type -> Type). TextParser m Status #

codep :: forall (m :: Type -> Type). TextParser m Text #

descriptionp :: forall (m :: Type -> Type). TextParser m Text #

Parse possibly empty text until a semicolon or newline. Whitespace is preserved (for now - perhaps helps preserve alignment of same-line comments ?).

## dates

datep :: forall (m :: Type -> Type). JournalParser m Day #

Parse a date in YYYY-MM-DD format. Slash (/) and period (.) are also allowed as separators. The year may be omitted if a default year has been set. Leading zeroes may be omitted.

datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime #

Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format. Slash (/) and period (.) are also allowed as date separators. The year may be omitted if a default year has been set. Seconds are optional. The timezone is optional and ignored (the time is always interpreted as a local time). Leading zeroes may be omitted (except in a timezone).

secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day #

## account names

modifiedaccountnamep :: forall (m :: Type -> Type). JournalParser m AccountName #

Parse an account name (plus one following space if present), then apply any parent account prefix and/or account aliases currently in effect, in that order. (Ie first add the parent account prefix, then rewrite with aliases). This calls error if any account alias with an invalid regular expression exists.

accountnamep :: forall (m :: Type -> Type). TextParser m AccountName #

Parse an account name, plus one following space if present. Account names have one or more parts separated by the account separator character, and are terminated by two or more spaces (or end of input). Each part is at least one character long, may have single spaces inside it, and starts with a non-whitespace. Note, this means "{account}", "%^!" and ";comment" are all accepted (parent parsers usually prevent/consume the last). It should have required parts to start with an alphanumeric; for now it remains as-is for backwards compatibility.

## account aliases

accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias #

## amounts

spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount #

Parse whitespace then an amount, or return the special "missing" marker amount.

amountp :: forall (m :: Type -> Type). JournalParser m Amount #

Parse a single-commodity amount, applying the default commodity if there is no commodity symbol; optionally followed by, in any order: a Ledger-style cost, Ledger-style valuation expression, and/or Ledger-style cost basis, which is one or more of lot cost, lot date, and/or lot note (we loosely call this triple the lot's cost basis). The cost basis makes it a lot rather than just an amount. Both cost basis info and valuation expression are discarded for now. The main amount's sign is significant; here are the possibilities and their interpretation. Also imagine an optional VALUATIONEXPR added to any of these (omitted for clarity): @

AMT -- acquiring an amount AMT COST -- acquiring an amount at some cost AMT COST COSTBASIS -- acquiring a lot at some cost, saving its cost basis AMT COSTBASIS COST -- like the above AMT COSTBASIS -- like the above with cost same as the cost basis

- AMT -- releasing an amount
- AMT SELLPRICE -- releasing an amount at some selling price
- AMT SELLPRICE COSTBASISSEL -- releasing a lot at some selling price, selecting it by its cost basis
- AMT COSTBASISSEL SELLPRICE -- like the above
- AMT COSTBASISSEL -- like the above with selling price same as the selected lot's cost basis amount

COST/SELLPRICE can be `UNITAMT,` `TOTALAMT, (`) UNITAMT, or (@@) TOTALAMT. The () are ignored. COSTBASIS is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order, with LOTCOST defaulting to COST. COSTBASISSEL is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order. {LOTCOST} can be {UNITAMT}, {{TOTALAMT}}, {=UNITAMT}, or {{=TOTALAMT}}. The = is ignored. VALUATIONEXPR can be ((VALUE AMOUNT)) or ((VALUE FUNCTION)).

@ Ledger amount syntax is really complex. Rule of thumb: curly braces, parentheses, and/or square brackets in an amount means a Ledger-style cost basis is involved.

To parse an amount's numeric quantity we need to know which character represents a decimal mark. We find it in one of three ways:

1. If a decimal mark has been set explicitly in the journal parse state, we use that
2. Or if the journal has a commodity declaration for the amount's commodity, we get the decimal mark from that
3. Otherwise we will parse any valid decimal mark appearing in the number, as long as the number appears well formed. (This means we handle files with any supported decimal mark without configuration, but it also allows different decimal marks in different amounts, which is a bit too loose. There's an open issue.)

amountp' :: forall (m :: Type -> Type). Bool -> JournalParser m Amount #

commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol #

costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost #

Ledger-style cost notation: `UNITAMT,` `TOTALAMT, (`) UNITAMT, or (@@) TOTALAMT. The () are ignored.

balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion #

lotcostp :: forall (m :: Type -> Type). JournalParser m () #

numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) #

Parse a string representation of a number for its value and display attributes.

Some international number formats are accepted, eg either period or comma may be used for the decimal mark, and the other of these may be used for separating digit groups in the integer part. See http://en.wikipedia.org/wiki/Decimal_separator for more examples.

This returns: the parsed numeric value, the precision (number of digits seen following the decimal mark), the decimal mark character used if any, and the digit group style if any.

fromRawNumber :: RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) #

Interpret a raw number as a decimal number.

Returns: - the decimal number - the precision (number of digits after the decimal point) - the decimal point character, if any - the digit group style, if any (digit group character and sizes of digit groups)

rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber) #

Parse and interpret the structure of a number without external hints. Numbers are digit strings, possibly separated into digit groups by one of two types of separators. (1) Numbers may optionally have a decimal mark, which may be either a period or comma. (2) Numbers may optionally contain digit group marks, which must all be either a period, a comma, or a space.

It is our task to deduce the characters used as decimal mark and digit group mark, based on the allowed syntax. For instance, we make use of the fact that a decimal mark can occur at most once and must be to the right of all digit group marks.

    >>> parseTest rawnumberp "1,234,567.89"
    Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
    >>> parseTest rawnumberp "1,000"
    Left (AmbiguousNumber "1" ',' "000")
    >>> parseTest rawnumberp "1 000"
    Right (WithSeparators ' ' ["1","000"] Nothing)

parseamount :: String -> Either HledgerParseErrors Amount #

Try to parse a single-commodity amount from a string

parseamount' :: String -> Amount #

Parse a single-commodity amount from a string, or get an error.

parsemixedamount :: String -> Either HledgerParseErrors MixedAmount #

Like parseamount', but returns a MixedAmount.

parsemixedamount' :: String -> MixedAmount #

Like parseamount', but returns a MixedAmount.

## comments

isLineCommentStart :: Char -> Bool #

Is this a character that, as the first non-whitespace on a line, starts a comment line ?

isSameLineCommentStart :: Char -> Bool #

Is this a character that, appearing anywhere within a line, starts a comment ?

multilinecommentp :: forall (m :: Type -> Type). TextParser m () #

emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m () #

A blank or comment line in journal format: a line that's empty or containing only whitespace or whose first non-whitespace character is semicolon, hash, or star. See also emptyorcommentlinep2.

emptyorcommentlinep2 :: forall (m :: Type -> Type). [Char] -> TextParser m () #

A newer comment line parser. Parses a line which is empty, all blanks, or whose first non-blank character is one of those provided.

followingcommentp :: forall (m :: Type -> Type). TextParser m Text #

Parse a comment following a journal item, possibly continued on multiple lines, and return the comment text.

    >>> rtp followingcommentp ""   -- no comment
    Right ""
    >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
    Right "\n"
    >>> rtp followingcommentp ";  \n"
    Right "\n"
    >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
    Right "\n\n"
    >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
    Right "\n\n"

transactioncommentp :: forall (m :: Type -> Type). TextParser m (Text, [Tag]) #

Parse a transaction comment and extract its tags.

The first line of a transaction may be followed by comments, which begin with semicolons and extend to the end of the line. Transaction comments may span multiple lines, but comment lines below the transaction must be preceded by leading whitespace.

200011 ; a transaction comment starting on the same line ... ; extending to the next line account1 $1 account2

Tags are name-value pairs.

    >>> let getTags (_,tags) = tags
    >>> let parseTags = fmap getTags . rtp transactioncommentp

    >>> parseTags "; name1: val1, name2:all this is value2"
    Right [("name1","val1"),("name2","all this is value2")]

A tag's name must be immediately followed by a colon, without separating whitespace. The corresponding value consists of all the text following the colon up until the next colon or newline, stripped of leading and trailing whitespace.

commentlinetagsp :: forall (m :: Type -> Type). TextParser m [Tag] #

postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day) #

Parse a posting comment and extract its tags and dates.

Postings may be followed by comments, which begin with semicolons and extend to the end of the line. Posting comments may span multiple lines, but comment lines below the posting must be preceded by leading whitespace.

200011 account1 $1 ; a posting comment starting on the same line ... ; extending to the next line

account2 ; a posting comment beginning on the next line

Tags are name-value pairs.

    >>> let getTags (_,tags,_,_) = tags
    >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing)

    >>> parseTags "; name1: val1, name2:all this is value2"
    Right [("name1","val1"),("name2","all this is value2")]

A tag's name must be immediately followed by a colon, without separating whitespace. The corresponding value consists of all the text following the colon up until the next colon or newline, stripped of leading and trailing whitespace.

Posting dates may be expressed with "date"/"date2" tags or with bracketed date syntax. Posting dates will inherit their year from the transaction date if the year is not specified. We throw parse errors on invalid dates.

    >>> let getDates (_,_,d1,d2) = (d1, d2)
    >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))

    >>> parseDates "; date: 1/2, date2: 1999/12/31"
    Right (Just 2000-01-02,Just 1999-12-31)
    >>> parseDates "; [1/2=1999/12/31]"
    Right (Just 2000-01-02,Just 1999-12-31)

Example: tags, date tags, and bracketed dates >>> rtp (postingcommentp (Just 2000)) "; a:b, date:34, [=56]" Right ("a:b, date:34, [=56]n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06)

Example: extraction of dates from date tags ignores trailing text >>> rtp (postingcommentp (Just 2000)) "; date:34=56" Right ("date:34=56n",[("date","34=56")],Just 2000-03-04,Nothing)

## bracketed dates

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

    >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
    Right [("date",2016-01-02),("date2",2016-03-04)]

    >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"
    Left ...not a bracketed date...

    >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"
    Left ...1:2:...This is not a valid date...

    >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"
    Left ...1:2:...This partial date can not be parsed because the current year is unknown...

    >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
    Left ...1:13:...expecting month or day...

## misc

doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text #

Parse a single line of possibly empty text enclosed in double quotes.

noncommenttextp :: forall (m :: Type -> Type). TextParser m Text #

Parse possibly empty text, including whitespace, until a comment start (semicolon) or newline.

noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text #

Parse non-empty text, including whitespace, until a comment start (semicolon) or newline.

singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text #

Parse non-empty, single-spaced text starting and ending with non-whitespace, until a double space or newline.

singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text #

Parse non-empty, single-spaced text starting and ending with non-whitespace, until a comment start (semicolon), double space, or newline.

singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text #

Parse non-empty, single-spaced text starting and ending with non-whitespace, where all characters satisfy the given predicate.

singlespacep :: forall (m :: Type -> Type). TextParser m () #

Parse one non-newline whitespace character that is not followed by another one.

skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () #

skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () #

aliasesFromOpts :: InputOpts -> [AccountAlias] #

Get the account name aliases from options, if any.

# tests

tests_Common :: TestTree #