| Safe Haskell | None |
|---|---|
| Language | GHC2021 |
Hledger.Read.Common
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 -> Handle -> ExceptT String IO Journal
- rParser :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal
- readerReadsOwnInput :: forall (m :: Type -> Type). Reader m -> Bool
- includeFileParser :: forall (m :: Type -> Type). MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal
- type PrefixedFilePath = FilePath
- isStdin :: PrefixedFilePath -> Bool
- data InputOpts = InputOpts {
- mformat_ :: Maybe StorageFormat
- mrules_file_ :: Maybe FilePath
- aliases_ :: [String]
- anon_ :: Bool
- new_ :: Bool
- new_save_ :: Bool
- pivot_ :: String
- forecast_ :: Maybe DateSpan
- verbose_tags_ :: Bool
- reportspan_ :: DateSpan
- auto_ :: Bool
- infer_equity_ :: Bool
- infer_costs_ :: Bool
- ignore_lots_ :: Bool
- balancingopts_ :: BalancingOpts
- strict_ :: Bool
- _defer :: Bool
- _importing :: Bool
- _dryrun :: Bool
- _scanfiles :: Bool
- _forecastOnlyForDisplay :: Bool
- _ioDay :: Day
- _oldtimeclock :: Bool
- _journaldir :: Maybe FilePath
- _fileoverrides :: Map FilePath Text
- 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
- dryrun :: Lens' c Bool
- fileoverrides :: Lens' c (Map FilePath Text)
- forecast :: Lens' c (Maybe DateSpan)
- forecastOnlyForDisplay :: Lens' c Bool
- ignore_lots :: Lens' c Bool
- importing :: Lens' c Bool
- infer_costs :: Lens' c Bool
- infer_equity :: Lens' c Bool
- ioDay :: Lens' c Day
- journaldir :: Lens' c (Maybe FilePath)
- mformat :: Lens' c (Maybe StorageFormat)
- mrules_file :: Lens' c (Maybe FilePath)
- new__ :: Lens' c Bool
- new_save :: Lens' c Bool
- oldtimeclock :: Lens' c Bool
- pivot :: Lens' c String
- reportspan :: Lens' c DateSpan
- scanfiles :: Lens' c Bool
- strict :: Lens' c Bool
- verbose_tags :: Lens' c Bool
- definputopts :: InputOpts
- rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts
- handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
- 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
- journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()
- setYear :: forall (m :: Type -> Type). Year -> JournalParser m ()
- getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year)
- getSourcePos' :: forall (m :: Type -> Type). JournalParser m SourcePos
- setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m ()
- getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle))
- getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle)
- getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle)
- journalDecimalMarkStyle :: Journal -> Maybe AmountStyle
- journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle
- shareText :: forall (m :: Type -> Type). Text -> JournalParser m Text
- shareAmountStyle :: forall (m :: Type -> Type). AmountStyle -> JournalParser m AmountStyle
- addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m ()
- addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m ()
- pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m ()
- getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName
- addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
- getAccountAliases :: MonadState Journal m => m [AccountAlias]
- journalAddFile :: JournalFile -> Journal -> Journal
- statusp :: forall (m :: Type -> Type). TextParser m Status
- codep :: forall (m :: Type -> Type). TextParser m Text
- descriptionp :: forall (m :: Type -> Type). TextParser m Text
- datep :: forall (m :: Type -> Type). JournalParser m Day
- datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime
- timeofdayp :: forall (m :: Type -> Type). TextParser m TimeOfDay
- secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day
- modifiedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName
- aliasedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName
- applyParentAndOptionAliases :: forall (m :: Type -> Type). AccountName -> JournalParser m AccountName
- accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName
- accountnamep :: forall (m :: Type -> Type). TextParser m AccountName
- accountnamenosemicolonp :: forall (m :: Type -> Type). TextParser m AccountName
- parentaccountnamep :: 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
- data AmountParseKind
- amountp' :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
- postingamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
- simpleamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount
- commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol
- costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost
- balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion
- lotcostp :: forall (m :: Type -> Type). Quantity -> JournalParser m CostBasis
- 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)
- interpretRawNumber :: Maybe Char -> Maybe AmountStyle -> Either AmbiguousNumber RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
- data RawNumber
- = NoSeparators DigitGrp (Maybe (Char, DigitGrp))
- | WithSeparators Char [DigitGrp] (Maybe (Char, DigitGrp))
- data AmbiguousNumber = AmbiguousNumber DigitGrp Char DigitGrp
- data DigitGrp = DigitGrp {
- digitGroupLength :: !Word
- digitGroupNumber :: !Integer
- isDigitSeparatorChar :: Char -> Bool
- parseamount :: String -> Either HledgerParseErrors Amount
- parseamountWithStyles :: Map CommoditySymbol AmountStyle -> 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) Source #
A hledger journal reader is a storage format name, a list of file extensions assumed to be in this format, and an IO action that reads data in this format, returning a Journal.
The journal parser used by the latter is also stored separately for direct use by the journal reader's includedirectivep to parse included files. The type variable m is needed for this parser. Lately it requires an InputOpts, basically to support --old-timeclock.
Constructors
| Reader | |
Fields
| |
readerReadsOwnInput :: forall (m :: Type -> Type). Reader m -> Bool Source #
Does this reader's rParser read the included file itself, ignoring the text it is given ? The CSV and rules readers do, since their data may be in a non-UTF-8 encoding declared by the rules file, or (for rules files) in a separate data file.
includeFileParser :: forall (m :: Type -> Type). MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal Source #
Make an include file parser (see rParser) from an IO action which reads the file
at the given path and converts it to an unfinalised journal, with lists in reverse order
as journalFinalise expects. This is for readers of non-journal formats like CSV.
The megaparsec input is ignored; the file path is taken from the parse state's include file stack.
The account aliases in effect (from alias directives, then --alias options) are applied to the result,
as they would be for inlined journal entries (but not the parent account from apply account directives;
see accountNameApplyModifiers).
Any error, including an IO error, is rethrown as a final parse error showing the include file stack.
type PrefixedFilePath = FilePath Source #
A file path optionally prefixed by a reader name and colon (journal:, csv:, timedot:, etc.). The file path part can also be - meaning standard input.
isStdin :: PrefixedFilePath -> Bool Source #
Is this the special file path meaning standard input ? (-, possibly prefixed)
Constructors
| InputOpts | |
Fields
| |
Instances
class HasInputOpts c where Source #
Minimal complete definition
Methods
inputOpts :: Lens' c InputOpts Source #
aliases :: Lens' c [String] Source #
anon__ :: Lens' c Bool Source #
auto__ :: Lens' c Bool Source #
balancingopts :: Lens' c BalancingOpts Source #
defer :: Lens' c Bool Source #
dryrun :: Lens' c Bool Source #
fileoverrides :: Lens' c (Map FilePath Text) Source #
forecast :: Lens' c (Maybe DateSpan) Source #
forecastOnlyForDisplay :: Lens' c Bool Source #
ignore_lots :: Lens' c Bool Source #
importing :: Lens' c Bool Source #
infer_costs :: Lens' c Bool Source #
infer_equity :: Lens' c Bool Source #
journaldir :: Lens' c (Maybe FilePath) Source #
mformat :: Lens' c (Maybe StorageFormat) Source #
mrules_file :: Lens' c (Maybe FilePath) Source #
new__ :: Lens' c Bool Source #
new_save :: Lens' c Bool Source #
oldtimeclock :: Lens' c Bool Source #
pivot :: Lens' c String Source #
reportspan :: Lens' c DateSpan Source #
scanfiles :: Lens' c Bool Source #
strict :: Lens' c Bool Source #
verbose_tags :: Lens' c Bool Source #
Instances
rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts Source #
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.
handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal Source #
parsing utilities
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal Source #
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 Source #
Given a parser to ParsedJournal, input options, file path and
content: run the parser on the content. This is all steps of
parseAndFinaliseJournal without the finalisation step, and is used when
you need to perform other actions before finalisatison, as in parsing
Timeclock and Timedot files.
journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal Source #
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal Source #
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 Source #
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.
journalCheckAssertsWith :: InputOpts -> Journal -> Either String () Source #
Check a finalised journal's assert rules, as journal loading does, with these input options:
resolving relative dates with their today's date, and ignoring forecast transactions
if they were generated only for display (see _forecastOnlyForDisplay).
Also used by hledger-ui to recheck the rules in memory.
setYear :: forall (m :: Type -> Type). Year -> JournalParser m () Source #
getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year) Source #
getSourcePos' :: forall (m :: Type -> Type). JournalParser m SourcePos Source #
Get the current source position, like megaparsec's getSourcePos but
cheaper on large inputs. megaparsec walks every character since the last
position it calculated, checking each one's width; this instead starts
from the most recently calculated position kept in the parse state (see
ParsePos), counts the newlines since then with a fast scan, and walks
only the current line, using megaparsec's column rules. The journal
parsers should use this rather than getSourcePos. On the first call, or
if the parser has somehow moved backwards, it falls back to getSourcePos.
(Though, measured in 2026 on a 100k-transaction journal, this saved only
about 4% of total run time: the per-character walk is cheap in optimised code,
and this still scans the text, just faster.)
setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m () Source #
getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle)) Source #
getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle) Source #
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) Source #
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.
journalDecimalMarkStyle :: Journal -> Maybe AmountStyle Source #
The amount style implied by a decimal-mark directive or CSV rule in effect, if any.
journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle Source #
The AmountStyle declared by the most recently parsed commodity directive for the given
commodity, or failing that by the most recent default commodity directive, if any.
shareText :: forall (m :: Type -> Type). Text -> JournalParser m Text Source #
Return an identical text parsed earlier (an account name or commodity symbol), if there is one, so that they share one copy; otherwise remember (a compact copy of) this one and return that. Journals use relatively few distinct account names and commodity symbols, so this saves memory.
shareAmountStyle :: forall (m :: Type -> Type). AmountStyle -> JournalParser m AmountStyle Source #
Return an identical amount style parsed earlier, if there is one, so that amounts share it; otherwise remember and return this one. Journals use few distinct styles, so this saves memory.
addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m () Source #
addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m () Source #
pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m () Source #
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName Source #
addAccountAlias :: MonadState Journal m => AccountAlias -> m () Source #
getAccountAliases :: MonadState Journal m => m [AccountAlias] Source #
journalAddFile :: JournalFile -> Journal -> Journal Source #
parsers
transaction bits
statusp :: forall (m :: Type -> Type). TextParser m Status Source #
codep :: forall (m :: Type -> Type). TextParser m Text Source #
descriptionp :: forall (m :: Type -> Type). TextParser m Text Source #
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 Source #
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 Source #
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).
timeofdayp :: forall (m :: Type -> Type). TextParser m TimeOfDay Source #
Parse a time of day (HH:MM[:SS]), and skip any time zone suffix (like +0100) following it.
secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day Source #
account names
modifiedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName Source #
Parse an account name plus one following space if present (see accountnamep);
then apply the alias directives, parent account prefix and --alias options currently in effect,
in that order (see accountNameApplyModifiers, which explains this).
This calls error if any account alias with an invalid regular expression exists.
The flag says whether account names may include semicolons; currently account names
in journal format may, but account names in timeclock/timedot formats may not.
aliasedaccountnamep :: forall (m :: Type -> Type). Bool -> JournalParser m AccountName Source #
Parse an account name like modifiedaccountnamep, but apply only the alias directives,
not the parent account prefix or --alias options (see accountNameApplyModifiers).
applyParentAndOptionAliases :: forall (m :: Type -> Type). AccountName -> JournalParser m AccountName Source #
Add the parent account prefix to an account name (with alias directives already applied),
then apply the --alias options (see accountNameApplyModifiers).
This calls error if an --alias option has an invalid regular expression.
accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName Source #
Rewrite an account name as written in a journal entry, using the given alias directives (most recent first), parent account (from apply account directives) and --alias options. Can fail with a bad replacement pattern in a regular expression alias.
This is the reference for how account names are modified during parsing. There are three modifiers, applied in this order:
- alias directives and account directives' alias: tags (kept in
jparsealiases), applied to the name as written. This is as in Ledger, and it means a file's aliases keep working when the file is included under apply account (#2733). Before hledger 2, these were applied after step 2. - the parent account from apply account directives (
jparseparentaccounts), prepended. - --alias options (
jparseoptaliases), applied to the full account name, since that is the name users see in reports. These are kept separately from 1, so that end aliases can forget alias directives without forgetting them.
The code is split up because of a few special cases:
- The parsers apply these in two parts:
aliasedaccountnamepdoes step 1, andapplyParentAndOptionAliasesdoes steps 2 and 3. Normally both are used (modifiedaccountnamep). But accountdirectivep also needs the name after step 1 only: it is the target of the directive's alias: tags, which (like alias directives) are applied before step 2, so a target which already included the parent account would get it added twice. - The journal reader's fast path for simple transactions (fasttransactionp) does all three steps with this function, since it works on text rather than in the parser.
- Entries from included CSV/rules files get steps 1 and 3, but not 2 (
includeFileParser). (Included timeclock/timedot files are parsed withmodifiedaccountnamep, so they get all three.) - When a non-journal file is read directly,
jparseoptaliasesis empty, and its reader applies step 3 itself after parsing.
accountnamep :: forall (m :: Type -> Type). TextParser m AccountName Source #
Parse an account name, plus one following space if present. Account names have one or more parts separated by the account separator character, and are terminated by two or more whitespace characters (spaces or tabs), or end of input. Each part is at least one character long, may have single spaces inside it, and starts with a non-whitespace. (We should have required them to start with an alphanumeric, but didn't.) An empty part (from a leading, trailing or repeated separator) is an error. Note, this means account names can contain all kinds of punctuation, including ; which usually starts a following comment. Parent parsers usually remove the following comment before using this parser.
accountnamenosemicolonp :: forall (m :: Type -> Type). TextParser m AccountName Source #
parentaccountnamep :: forall (m :: Type -> Type). TextParser m AccountName Source #
Parse the parent account name of an apply account directive. Like accountnamep, but one trailing account separator is allowed, and dropped (as in Ledger, #2858).
account aliases
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias Source #
amounts
spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount Source #
Parse whitespace then an amount, or return the special "missing" marker amount.
amountp :: forall (m :: Type -> Type). JournalParser m Amount Source #
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:
- If a decimal mark has been set explicitly in the journal parse state (by a decimal-mark directive or CSV rule), we use that, strictly
- Or if the journal has a commodity declaration for the amount's commodity, we get the decimal mark from that, and use it only to interpret ambiguous numbers (see AmountParseKind for details)
- 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.)
data AmountParseKind Source #
The kinds of amount which are parsed a little differently.
A decimal-mark directive (or CSV rule) declares how numbers are written in the data, and data amounts (OrdinaryAmount, MultiplierAmount) must obey it strictly; violations are parse errors, reported at the number. A commodity or D directive declares a display style, given as a sample amount (StyleAmount), which may use a different decimal mark from the data. When there's no decimal-mark directive, a commodity's display style is also used to interpret ambiguous numbers like 1,000, but it is not enforced.
Constructors
| OrdinaryAmount | An amount in the data: in a posting, cost, balance assertion, price directive, CSV record, etc. If a decimal-mark directive is in effect, the number must use only that decimal mark: 1,000.00 is rejected when , is declared, and 1.2.34 when . is declared. |
| MultiplierAmount | A multiplier in an auto posting rule (*AMT). The default commodity is not applied to it. Otherwise it's parsed like an OrdinaryAmount. |
| StyleAmount | The sample amount in a commodity directive (or its format subdirective) or a D directive, declaring a display style. Its decimal mark may differ from the one declared by decimal-mark, so that is not enforced; but it is still used to interpret ambiguous numbers like 1,000. |
Instances
| Eq AmountParseKind Source # | |
Defined in Hledger.Read.Common Methods (==) :: AmountParseKind -> AmountParseKind -> Bool (/=) :: AmountParseKind -> AmountParseKind -> Bool | |
| Show AmountParseKind Source # | |
Defined in Hledger.Read.Common Methods showsPrec :: Int -> AmountParseKind -> ShowS show :: AmountParseKind -> String showList :: [AmountParseKind] -> ShowS | |
amountp' :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount Source #
postingamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount Source #
A posting amount. Like amountp', except that the amount may also be written as a simple arithmetic expression, which is evaluated to a single amount (see amountexprp) (#2648). Any cost, valuation or lot annotations come after the expression, and apply to its result.
simpleamountp :: forall (m :: Type -> Type). AmountParseKind -> JournalParser m Amount Source #
commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol Source #
costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountCost Source #
Ledger-style cost notation:
UNITAMT, TOTALAMT, () UNITAMT, or (@@) TOTALAMT. The () are ignored.
The amount can be an amount expression (see amountexprp) (#2857).
balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion Source #
numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) Source #
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) Source #
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) Source #
Parse and interpret the structure of a number without external hints. Numbers are digit strings, possibly separated into digit groups by one of two types of separators. (1) Numbers may optionally have a decimal mark, which may be either a period or comma. (2) Numbers may optionally contain digit group marks, which must all be either a period, a comma, or a space.
It is our task to deduce the characters used as decimal mark and digit group mark, based on the allowed syntax. For instance, we make use of the fact that a decimal mark can occur at most once and must be to the right of all digit group marks.
>>>parseTest rawnumberp "1,234,567.89"Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))>>>parseTest rawnumberp "1,000"Left (AmbiguousNumber "1" ',' "000")>>>parseTest rawnumberp "1 000"Right (WithSeparators ' ' ["1","000"] Nothing)>>>parseTest rawnumberp "1'000"Right (WithSeparators '\'' ["1","000"] Nothing)>>>parseTest rawnumberp "1_000"Right (WithSeparators '_' ["1","000"] Nothing)
interpretRawNumber :: Maybe Char -> Maybe AmountStyle -> Either AmbiguousNumber RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) Source #
Interpret a possibly-ambiguous raw number as a decimal number. The suggested style (from a decimal-mark or commodity directive, eg), if any, is used to disambiguate it. If a required decimal mark is given (from a decimal-mark directive, eg), the number must use only that decimal mark.
Some kinds of number literal we might parse.
Constructors
| NoSeparators DigitGrp (Maybe (Char, DigitGrp)) | A number with no digit group marks (eg 100), or with a leading or trailing comma or period which (apparently) we interpret as a decimal mark (like 100. or .100) |
| WithSeparators Char [DigitGrp] (Maybe (Char, DigitGrp)) | A number with identifiable digit group marks (eg 1,000,000 or 1,000.50 or 1 000) |
Instances
data AmbiguousNumber Source #
Another kind of number literal: this one contains either a digit group separator or a decimal mark, we're not sure which (eg 1,000 or 100.50).
Constructors
| AmbiguousNumber DigitGrp Char DigitGrp |
Instances
| Eq AmbiguousNumber Source # | |
Defined in Hledger.Read.Common Methods (==) :: AmbiguousNumber -> AmbiguousNumber -> Bool (/=) :: AmbiguousNumber -> AmbiguousNumber -> Bool | |
| Show AmbiguousNumber Source # | |
Defined in Hledger.Read.Common Methods showsPrec :: Int -> AmbiguousNumber -> ShowS show :: AmbiguousNumber -> String showList :: [AmbiguousNumber] -> ShowS | |
Description of a single digit group in a number literal. Thousands is one well known digit grouping, but there are others.
Constructors
| DigitGrp | |
Fields
| |
isDigitSeparatorChar :: Char -> Bool Source #
parseamount :: String -> Either HledgerParseErrors Amount Source #
Try to parse a single-commodity amount from a string
parseamountWithStyles :: Map CommoditySymbol AmountStyle -> String -> Either HledgerParseErrors Amount Source #
Try to parse a single-commodity amount from a string, using these commodities' styles to read an ambiguous number (eg 10.000 EUR is ten thousand if EUR's decimal mark is a comma, or if it has no decimal places).
parseamount' :: String -> Amount Source #
Parse a single-commodity amount from a string, or get an error.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount Source #
Like parseamount', but returns a MixedAmount.
parsemixedamount' :: String -> MixedAmount Source #
Like parseamount', but returns a MixedAmount.
comments
isLineCommentStart :: Char -> Bool Source #
Is this a character that, as the first non-whitespace on a line, starts a comment line ?
isSameLineCommentStart :: Char -> Bool Source #
Is this a character that, appearing anywhere within a line, starts a comment ?
multilinecommentp :: forall (m :: Type -> Type). TextParser m () Source #
emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m () Source #
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 () Source #
A newer comment line parser. Parses a line which is empty, all blanks, or whose first non-blank character is one of those provided. A final newline is optional.
followingcommentp :: forall (m :: Type -> Type). TextParser m Text Source #
Parse a comment following a journal item, possibly continued on multiple lines, and return the comment text.
>>>rtp followingcommentp "" -- no commentRight "">>>rtp followingcommentp ";" -- just a (empty) same-line comment. newline is addedRight "\n">>>rtp followingcommentp "; \n"Right "\n">>>rtp followingcommentp ";\n ;\n" -- a same-line and a next-line commentRight "\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]) Source #
Parse a transaction comment and extract its tags.
The first line of a transaction may be followed a 1-or-more-lines comment, beginning with a semicolon possibly preceded by whitespace on the current line, or with an indented semicolon on the next line. Additional lines also must begin with an indented semicolon. See also followingcommentpWith.
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] Source #
postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day) Source #
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)
Example: date tags with empty values set no date >>> rtp (postingcommentp (Just 2000)) "; date:, date2: , a:b" Right ("date:, date2: , a:bn",[("date",""),("date2",""),("a","b")],Nothing,Nothing)
bracketed dates
bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)] Source #
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 Source #
Parse a single line of possibly empty text enclosed in double quotes.
noncommenttextp :: forall (m :: Type -> Type). TextParser m Text Source #
Parse possibly empty text, including whitespace, until a comment start (semicolon) or newline.
noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text Source #
Parse non-empty text, including whitespace, until a comment start (semicolon) or newline.
singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text Source #
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 Source #
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 Source #
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 () Source #
Parse one non-newline whitespace character that is not followed by another one. (A single tab is not a separator, unlike in Ledger; hledger 1 and 2 agree on this.)
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () Source #
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () Source #
aliasesFromOpts :: InputOpts -> [AccountAlias] Source #
Get the account name aliases from options, if any. A bad alias argument causes a program exit with a parse error message.