One of the languages supported by Babel is Ledger, so that you can have ledger commands embedded in a text file and have the output of ledger commands also appear in the text file. The output can be updated whenever any new ledger entries are added.
For instance, the following Org mode text document snippet illustrates a very naive but still useful application of the Babel system:
* A simple test of ledger in an org file The following are some entries and I have requested that ledger be run to generate a balance on the accounts. I could have asked for a register or, in fact, anything at all the ledger can do through command-line options. #+begin_src ledger :cmdline bal :results value 2010/01/01 * Starting balance assets:bank:savings £1300.00 income:starting balances 2010/07/22 * Got paid assets:bank:chequing £1000.00 income:salary 2010/07/23 Rent expenses:rent £500.00 assets:bank:chequing #+end_src #+results: : £1800.00 assets:bank : £500.00 chequing : £1300.00 savings : £500.00 expenses:rent : £-2300.00 income : £-1000.00 salary : £-1300.00 starting balances
Typing C-c C-c anywhere in the “ledger source code block” will invoke ledger on the contents of that block and generate a “results” block. The results block can appear anywhere in the file but, by default, will appear immediately below the source code block.
You can combine multiple source code blocks before executing ledger and do all kinds of other wonderful things with Babel (and Org mode).
Next: The pricemap
command, Previous: Emacs org
Mode, Up: Reports in other Formats [Contents][Index]
Using Babel, it is possible to record financial transactions conveniently in an org file and subsequently generate the financial reports required.
As of Org mode 7.01, Ledger support is provided. Check the Babel documentation on Worg for instructions on how to achieve this but I currently do this directly as follows:
(org-babel-do-load-languages 'org-babel-load-languages '((ledger . t) ;this is the important one for this tutorial ))
Once Ledger support in Babel has been enabled, we can proceed to include Ledger entries within an org file. There are three ways (at least) in which these can be included:
noweb
literary programming approach, supported by Babel, to
combine these into one block elsewhere in the file for processing by
Ledger,
tangle
to
generate a Ledger file which you can subsequently process using Ledger
directly.
The first two are described in more detail in this short tutorial.
Next: Multiple Ledger source blocks with noweb
, Previous: Org mode with Babel, Up: Org mode with Babel [Contents][Index]
The easiest, albeit possibly least useful, way in which to use Ledger within an org file is to use a single source block to record all Ledger entries. The following is an example source block:
#+name: allinone #+begin_src ledger 2010/01/01 * Starting balance assets:bank:savings £1300.00 income:starting balances 2010/07/22 * Got paid assets:bank:chequing £1000.00 income:salary 2010/07/23 Rent expenses:rent £500.00 assets:bank:chequing 2010/07/24 Food expenses:food £150.00 assets:bank:chequing 2010/07/31 * Interest on bank savings assets:bank:savings £3.53 income:interest 2010/07/31 * Transfer savings assets:bank:savings £250.00 assets:bank:chequing 2010/08/01 got paid again assets:bank:chequing £1000.00 income:salary #+end_src
In this example, we have combined both expenses and income into one set
of Ledger entries. We can now generate register and balance reports (as
well as many other types of reports) using Babel to invoke Ledger with
specific arguments. The arguments are passed to Ledger using the
:cmdline
header argument. In the code block above, there is no
such argument so the system takes the default. For Ledger code blocks,
the default :cmdline
argument is bal
and the result of
evaluating this code block (C-c C-c) would be:
#+results: allinone() : £2653.53 assets:bank : £1100.00 chequing : £1553.53 savings : £650.00 expenses : £150.00 food : £500.00 rent : £-3303.53 income : £-3.53 interest : £-2000.00 salary : £-1300.00 starting balances
If, instead, you wished to generate a register of all the transactions,
you would change the #+begin_src
line for the code block to
include the required command-line option:
#+begin_src ledger :cmdline reg
Evaluating the code block again would generate a different report.
Having to change the actual directive on the code block and re-evaluate
makes it difficult to have more than one view of your transactions and
financial state. Eventually, Babel will support passing arguments to
#+call
evaluations of code blocks but this support is missing
currently. Instead, we can use the concepts of literary programming, as
implemented by the noweb
features of Babel, to help us.
Next: Income Entries, Previous: Embedded Ledger example with single source block, Up: Org mode with Babel [Contents][Index]
noweb
The noweb
feature of Babel allows us to expand references to
other code blocks within a code block. For Ledger, this can be used to
group transactions according to type, say, and then bring various sets
of transactions together to generate reports.
Using the same transactions used above, we could consider splitting these into expenses and income, as follows:
Next: Expenses, Previous: Multiple Ledger source blocks with noweb
, Up: Org mode with Babel [Contents][Index]
The first set of entries relates to income, either monthly pay or
interest, all typically going into one of my bank accounts. Here, I have
placed several entries, but we could have had each entry in a separate
src
block. Note that all code blocks you wish to refer to later
must have the :noweb yes
header argument specified.
#+name: income #+begin_src ledger :noweb yes 2010/01/01 * Starting balance assets:bank:savings £1300.00 income:starting balances 2010/07/22 * Got paid assets:bank:chequing £1000.00 income:salary 2010/07/31 * Interest on bank savings assets:bank:savings £3.53 income:interest 2010/07/31 * Transfer savings assets:bank:savings £250.00 assets:bank:chequing 2010/08/01 got paid again assets:bank:chequing £1000.00 income:salary #+end_src
Next: Financial Summaries, Previous: Income Entries, Up: Org mode with Babel [Contents][Index]
The following entries relate to personal expenses, such as rent and
food. Again, these have all been placed in a single src
block but
could have been done individually.
#+name: expenses #+begin_src ledger :noweb yes 2010/07/23 Rent expenses:rent £500.00 assets:bank:chequing 2010/07/24 Food expenses:food £150.00 assets:bank:chequing #+end_src
Next: An overall balance summary, Previous: Expenses, Up: Org mode with Babel [Contents][Index]
Given the ledger entries defined above in the income and expenses code
blocks, we can now refer to these using the noweb expansion directives,
<<name>>
. We can now define different code blocks to generate
specific reports for those transactions. Below are two examples, one to
generate a balance report and one to generate a register report of all
transactions.
Next: Generating a monthly register, Previous: Financial Summaries, Up: Org mode with Babel [Contents][Index]
The overall balance of your account and expenditure with a breakdown
according to category is specified by passing the :cmdline bal
argument to Ledger. This code block can now be evaluated (C-c C-c)
and the results generated by incorporating the transactions referred to
by the <<income>>
and <<expenses>>
lines.
#+name: balance #+begin_src ledger :cmdline bal :noweb yes <<income>> <<expenses>> #+end_src #+results: balance : £2653.53 assets:bank : £1100.00 chequing : £1553.53 savings : £650.00 expenses : £150.00 food : £500.00 rent : £-3303.53 income : £-3.53 interest : £-2000.00 salary : £-1300.00 starting balances
If you want a less detailed breakdown of where your money is, you can specify the --collapse (-n) flag (i.e. ‘:cmdline -n bal’) to tell Ledger to exclude sub-accounts in the report.
#+begin_src ledger :cmdline -n bal :noweb yes <<income>> <<expenses>> #+end_src #+results: : £2653.53 assets : £650.00 expenses : £-3303.53 income
Next: Summary, Previous: An overall balance summary, Up: Org mode with Babel [Contents][Index]
You can also generate a monthly register (the reg
command) by
executing the following src
block. This presents a summary of
transactions for each monthly period (the --monthly (-M)
argument) with a running total in the final column (which should be 0 at
the end if all the entries are correct).
#+name: monthlyregister #+begin_src ledger :cmdline -M reg :noweb yes <<income>> <<expenses>> #+end_src #+results: monthlyregister :2010/01/01 - 2010/01/31 assets:bank:savings £1300.00 £1300.00 : in:starting balances £-1300.00 0 :2010/07/01 - 2010/07/31 assets:bank:chequing £100.00 £100.00 : assets:bank:savings £253.53 £353.53 : expenses:food £150.00 £503.53 : expenses:rent £500.00 £1003.53 : income:interest £-3.53 £1000.00 : income:salary £-1000.00 0 :2010/08/01 - 2010/08/01 assets:bank:chequing £1000.00 £1000.00 : income:salary £-1000.00 0
We could also generate a monthly report on our assets showing how these are increasing (or decreasing!). In this case, the final column will be the running total of the assets in our ledger.
#+name: monthlyassetsregister #+begin_src ledger :cmdline -M reg assets :noweb yes <<income>> <<expenses>> #+end_src #+results: monthlyassetsregister : 2010/01/01 - 2010/01/31 assets:bank:savings £1300.00 £1300.00 : 2010/07/01 - 2010/07/31 assets:bank:chequing £100.00 £1400.00 : assets:bank:savings £253.53 £1653.53 : 2010/08/01 - 2010/08/01 assets:bank:chequing £1000.00 £2653.53
Previous: Generating a monthly register, Up: Org mode with Babel [Contents][Index]
This short tutorial shows how Ledger entries can be embedded in an org file and manipulated using Babel. However, only simple Ledger features have been illustrated; please refer to the Ledger documentation for examples of more complex operations on a ledger.
Next: The xml
command, Previous: Org mode with Babel, Up: Reports in other Formats [Contents][Index]
pricemap
commandIf you have the graphviz graph visualization package installed, ledger can generate a graph of the relationship between your various commodities. The output file is in the “dot” format.
This is probably not very interesting, unless you have many different commodities valued in terms of each other. For example, multiple currencies and multiple investments valued in those currencies.
Next: prices
and pricedb
commands, Previous: The pricemap
command, Up: Reports in other Formats [Contents][Index]
xml
commandBy default, Ledger uses a human-readable data format, and displays its reports in a manner meant to be read on screen. For the purpose of writing tools which use Ledger, however, it is possible to read and display data using XML. This section documents that format.
The general format used for Ledger data is:
<?xml version="1.0"?> <ledger> <xact>...</xact> <xact>...</xact> <xact>...</xact>... </ledger>
The data stream is enclosed in a ledger
tag, which contains a
series of one or more transactions. Each xact
describes one
transaction and contains a series of one or more postings:
<xact> <en:date>2004/03/01</en:date> <en:cleared/> <en:code>100</en:code> <en:payee>John Wiegley</en:payee> <en:postings> <posting>...</posting> <posting>...</posting> <posting>...</posting>... </en:postings> </xact>
The date format for en:date
is always YYYY/MM/DD
. The
en:cleared
tag is optional, and indicates whether the posting has
been cleared or not. There is also an en:pending
tag, for
marking pending postings. The en:code
and en:payee
tags
both contain whatever text the user wishes.
After the initial transaction data, there must follow a set of postings
marked with en:postings
. Typically these postings will all
balance each other, but if not they will be automatically balanced into
an account named ‘Unknown’.
Within the en:postings
tag is a series of one or more
posting
’s, which have the following form:
<posting> <tr:account>Expenses:Computer:Hardware</tr:account> <tr:amount> <value type="amount"> <amount> <commodity flags="PT">$</commodity> <quantity>90.00</quantity> </amount> </value> </tr:amount> </posting>
This is a basic posting. It may also begin with
tr:virtual
and/or tr:generated
tags, to indicate virtual
and auto-generated postings. Then follows the tr:account
tag, which contains the full name of the account the posting is
related to. Colons separate parent from child in an account name.
Lastly follows the amount of the posting, indicated by
tr:amount
. Within this tag is a value
tag, of which
there are four different kinds, each with its own format:
The format of a Boolean value is true
or false
surrounded by a boolean
tag, for example:
<boolean>true</boolean>
The format of an integer value is the numerical value surrounded by an
integer
tag, for example:
<integer>12036</integer>
The format of an amount contains two members, the commodity and the quantity. The commodity can have a set of flags that indicate how to display it. The meaning of the flags (all of which are optional) are:
P
The commodity is prefixed to the value.
S
The commodity is separated from the value by a space.
T
Thousands markers are used to display the amount.
E
The format of the amount is European, with period used as a thousands marker, and comma used as the decimal point.
The actual quantity for an amount is an integer of arbitrary size. Ledger uses the GNU multiple precision arithmetic library to handle such values. The XML format assumes the reader to be equally capable. Here is an example amount:
<value type="amount"> <amount> <commodity flags="PT">$</commodity> <quantity>90.00</quantity> </amount> </value>
Lastly, a balance value contains a series of amounts, each with a different commodity. Unlike the name, such a value does need to balance. It is called a balance because it sums several amounts. For example:
<value type="balance"> <balance> <amount> <commodity flags="PT">$</commodity> <quantity>90.00</quantity> </amount> <amount> <commodity flags="TE">DM</commodity> <quantity>200.00</quantity> </amount> </balance> </value>
That is the extent of the XML data format used by Ledger. It will
output such data if the xml
command is used, and can read
the same data.
Previous: The xml
command, Up: Reports in other Formats [Contents][Index]
prices
and pricedb
commandsThe prices
command displays the price history for matching
commodities. The --average (-A) option is useful with this
report, to display the running average price, or --deviation
(-D) to show each price’s deviation from that average.
There is also a pricedb
command which outputs the same
information as prices
, but does so in a format that can be
parsed by Ledger. This is useful for generating and tidying up
pricedb database files.
Previous: Reports in other Formats, Up: Reporting Commands [Contents][Index]
• accounts : | ||
• payees : | ||
• commodities : | ||
• tags : | ||
• xact : | ||
• stats : | ||
• select : |
Next: payees
, Previous: Reports about your Journals, Up: Reports about your Journals [Contents][Index]
accounts
The accounts
command reports all of the accounts in the
journal. Following the command with a regular expression will limit the
output to accounts matching the regex. The output is sorted by name.
Using the --count option will tell you how many entries use
each account.
Next: commodities
, Previous: accounts
, Up: Reports about your Journals [Contents][Index]
payees
The payees
command reports all of the unique payees in the
journal. Using the --count option will tell you how many
entries use each payee. To filter the payees displayed you must use the
prefix @:
$ ledger payees @Nic
Nicolas Nicolas BOILABUS Oudtshoorn Municipality Vaca Veronica
Next: tags
, Previous: payees
, Up: Reports about your Journals [Contents][Index]
commodities
Report all commodities present in the journals under consideration. The output is sorted by name. Using the --count option will tell you how many entries use each commodity.
Next: xact
, Previous: commodities
, Up: Reports about your Journals [Contents][Index]
tags
The tags
command reports all of the tags in the journal. The
output is sorted by name. Using the --count option will tell
you how many entries use each tag. Using the --values option
will report the values used by each tag.
Next: stats
, Previous: tags
, Up: Reports about your Journals [Contents][Index]
xact
The xact
command simplifies the creation of new transactions.
It works on the principle that 80% of all postings are variants of
earlier postings. Here’s how it works:
Say you currently have this posting in your ledger file:
2004/03/15 * Viva Italiano Expenses:Food $12.45 Expenses:Tips $2.55 Liabilities:MasterCard $-15.00
Now it’s ‘2004/4/9’, and you’ve just eaten at ‘Viva Italiano’
again. The exact amounts are different, but the overall form is the
same. With the xact
command you can type:
$ ledger xact 2004/4/9 viva food 11 tips 2.50
This produces the following output:
2004/04/09 Viva Italiano Expenses:Food $11.00 Expenses:Tips $2.50 Liabilities:MasterCard
It works by finding a past posting matching the regular expression ‘viva’, and assuming that any accounts or amounts specified will be similar to that earlier posting. If Ledger does not succeed in generating a new transaction, an error is printed and the exit code is set to ‘1’.
Here are a few more examples of the xact
command, assuming
the above journal transaction:
$ ledger xact 4/9 viva 11.50 $ ledger xact 4/9 viva 11.50 checking # (from `checking') $ ledger xact 4/9 viva food 11.50 tips 8 $ ledger xact 4/9 viva food 11.50 tips 8 cash $ ledger xact 4/9 viva food $11.50 tips $8 cash $ ledger xact 4/9 viva dining "DM 11.50"
draft
and entry
are both synonyms of
xact
. entry
is provided for backwards compatibility
with Ledger 2.X.
Next: select
, Previous: xact
, Up: Reports about your Journals [Contents][Index]
stats
UNDOCUMENTED! Please help by contributing documentation for this feature.
Previous: stats
, Up: Reports about your Journals [Contents][Index]
select
UNDOCUMENTED! Please help by contributing documentation for this feature.
Next: Budgeting and Forecasting, Previous: Reporting Commands, Up: Top [Contents][Index]
| • Basic Usage: | ||
| • Command-Line Quick Reference: | ||
| • Detailed Option Description: | ||
| • Period Expressions: |
Next: Command-Line Quick Reference, Previous: Command-Line Syntax, Up: Command-Line Syntax [Contents][Index]
This chapter describes Ledger’s features and options. You may wish to survey this to get an overview before diving into the Ledger Tutorial and more detailed examples that follow.
Ledger has a very simple command-line interface, named—enticingly enough—ledger. It supports a few reporting commands, and a large number of options for refining the output from those commands. The basic syntax of any ledger command is:
$ ledger [OPTIONS...] COMMAND [ARGS...]
After the command word there may appear any number of arguments. For
most commands, these arguments are regular expressions that cause the
output to relate only to postings matching those regular expressions.
For the xact
command, the arguments have a special meaning,
described below.
The regular expressions arguments always match the account name that a posting refers to. To match on the payee of the transaction instead, precede the regular expression with ‘payee’ or ‘@’. For example, the following balance command reports account totals for rent, food and movies, but only those whose payee matches Freddie:
$ ledger bal rent food movies payee freddie
or
$ ledger bal rent food movies @freddie
There are many, many command options available with the ledger program, and it takes a while to master them. However, none of them are required to use the basic reporting commands.
Next: Detailed Option Description, Previous: Basic Usage, Up: Command-Line Syntax [Contents][Index]
| • Basic Reporting Commands: | ||
| • Basic Options: | ||
| • Report Filtering: | ||
| • Error Checking and Calculation Options: | ||
| • Output Customization: | ||
| • Grouping Options: | ||
| • Commodity Reporting: |
Next: Basic Options, Previous: Command-Line Quick Reference, Up: Command-Line Quick Reference [Contents][Index]
balance
bal
Show account balances.
register
reg
Show all transactions with running total.
csv
Show transactions in csv format, for exporting to other programs.
print
Print transactions in a format readable by ledger.
xml
Produce XML output of the register command.
lisp
emacs
Produce s-expression output, suitable for Emacs.
equity
Print account balances as transactions.
prices
Print price history for matching commodities.
pricedb
Print price history for matching commodities in a format readable by ledger.
xact
Generate transactions based on previous postings.
Next: Report Filtering, Previous: Basic Reporting Commands, Up: Command-Line Quick Reference [Contents][Index]
Display the man page for ledger.
Print version information and exit.
Read FILE as a ledger file.
Redirect output to FILE.
Specify an options file.
Import FILE as Python module.
Specify default account STR for QIF file postings.
Next: Error Checking and Calculation Options, Previous: Basic Options, Up: Command-Line Quick Reference [Contents][Index]
Display only transactions on or before the current date.
Limit the processing to transactions on or after DATE.
Limit the processing to transactions before DATE.
Limit the processing to transactions in PERIOD_EXPRESSION.
Sort postings within each period according to VEXPR.
Display only cleared postings.
Display register or balance in debit/credit format.
Display only uncleared postings.
Display only real postings.
Display only actual postings, not automated ones.
Display related postings.
Display how close your postings meet your budget.
Show unbudgeted postings.
Show only unbudgeted postings.
Project balances into the future.
Limit which postings are used in calculations by EXPR.
Change value expression reported in register
report.
Change the value expression used for “totals” column in
register
and balance
reports.
Next: Output Customization, Previous: Report Filtering, Up: Command-Line Quick Reference [Contents][Index]
Accounts, tags or commodities not previously declared will cause warnings.
Accounts, tags or commodities not previously declared will cause errors.
Enable strict and pedantic checking for payees as well as accounts, commodities and tags. This only works in conjunction with --strict or --pedantic.
Instruct ledger to evaluate calculations immediately rather than lazily.
Next: Grouping Options, Previous: Error Checking and Calculation Options, Up: Command-Line Quick Reference [Contents][Index]
Collapse transactions with multiple postings.
Report register as a single subtotal.
Report subtotals by payee.
Include empty accounts in the report.
Report posting totals by week.
Report posting totals by quarter.
Report posting totals by year.
Report posting totals by day of week.
Sort a report using VEXPR.
Assume 132 columns instead of 80.
Report the first INT postings.
Report the last INT postings.
Direct output to FILE pager program.
Direct output to stdout, avoiding pager program.
Report the average posting value.
Report each posting’s deviation from the average.
Show subtotals in the balance report as percentages.
Produce a pivot table of the TAG type specified.
Show only the date and value columns to format the output for plots.
Specify the format for the plot output.
Show only the date and total columns to format the output for plots.
Specify the format for the plot output.
Display only postings that meet the criteria in the EXPR.
Change the basic date format used in reports.
Set the reporting format for various reports.
Print the ledger register with anonymized accounts and payees, useful for filing bug reports.
Next: Commodity Reporting, Previous: Output Customization, Up: Command-Line Quick Reference [Contents][Index]
Group postings by common payee names.
Group postings by day.
Group postings by week.
Group postings by month.
Group postings by quarter.
Group postings by year.
Group by day of weeks.
Group postings together, similar to the balance report.
Previous: Grouping Options, Up: Command-Line Quick Reference [Contents][Index]
Use FILE for retrieving stored commodity prices.
Set expected freshness of prices in INT minutes.
Download quotes using the script named getquote.
Report commodity totals without conversion.
Report cost basis.
Report last known market value.
Report net gain or loss for commodities that have a price history.
Next: Period Expressions, Previous: Command-Line Quick Reference, Up: Command-Line Syntax [Contents][Index]
| • Global Options: | ||
| • Session Options: | ||
| • Report Options: | ||
| • Basic options: | ||
| • Report filtering: | ||
| • Output customization: | ||
| • Commodity reporting: | ||
| • Environment variables: |
Next: Session Options, Previous: Detailed Option Description, Up: Detailed Option Description [Contents][Index]
Options for Ledger reports affect three separate scopes of operation: Global, Session, and Report. In practice there is very little difference between these scopes. Ledger 3.0 contains provisions for GUIs, which would make use of the different scopes by keeping an instance of Ledger running in the background and running multiple sessions with multiple reports per session.
Ignore all environment and init-file settings and use only command-line arguments to control Ledger. Useful for debugging or testing small journal files not associated with your main financial database.
UNDOCUMENTED! Please help by contributing documentation for this feature. If ledger has been built with debug options this will provide extra data during the run.
Display the man page for ledger.
Specify the location of the init file. The default is home directory ~/.ledgerrc, or current directory ./.ledgerrc if not found in home directory.
Display the options in effect for this Ledger invocation, along with their values and the source of those values, for example:
$ ledger --options bal --cleared
=============================================================================== [Global scope options] --args-only --args-only [Session scope options] --file = A9349E4.dat --file [Report scope options] --cleared --cleared --columns = 80 --columns --limit = cleared --cleared =============================================================================== $15.00 Expenses $12.45 Food $2.55 Tips $-15.00 Liabilities:MasterCard -------------------- 0
For the source column, a value starting with a ‘-’ or ‘--’
indicated the source was a command-line argument. If the entry starts
with a ‘$’, the source was an environment variable. If the source
is ?normalize
the value was set internally by ledger, in
a function called normalize_options
.
Execute a ledger script.
Enable tracing. The INT specifies the level of trace desired.
Print detailed information on the execution of Ledger.
Enable additional assertions during run-time. This causes a significant slowdown. When combined with --debug CODE ledger will produce memory trace information.
Verify that every constructed object is properly destructed. This is for debugging purposes only.
Print version information and exit.
Next: Report Options, Previous: Global Options, Up: Detailed Option Description [Contents][Index]
Options for Ledger reports affect three separate scopes of operation: Global, Session, and Report. In practice there is very little difference between these scopes. Ledger 3.0 contains provisions for GUIs, which would make use of the different scopes by keeping an instance of Ledger running in the background and running multiple sessions with multiple reports per session.
Enable strict and pedantic checking for payees as well as accounts, commodities and tags. This only works in conjunction with --strict or --pedantic.
Break up register
report of timelog entries that span multiple
days by day.
Direct Ledger to parse journals using the European standard comma as a decimal separator, not the usual period.
Direct Ledger to download prices.
Direct Ledger to require pre-declarations for entities (such as accounts, commodities and tags) rather than taking entities from cleared transactions as defined. This option is useful in combination with --strict or --pedantic.
Specify the input FILE for this invocation.
Specify the input date format for journal entries. For example,
$ ledger convert Export.csv --input-date-format "%m/%d/%Y"
Would convert the Export.csv file to ledger format, assuming the dates in the CSV file are like 12/23/2009 (see Date and Time Format Codes).
Prepend all account names with the argument.
$ ledger -f drewr3.dat bal --no-total --master-account HUMBUG
0 HUMBUG $ -3,804.00 Assets $ 1,396.00 Checking $ 30.00 Business $ -5,200.00 Savings $ -1,000.00 Equity:Opening Balances $ 6,654.00 Expenses $ 5,500.00 Auto $ 20.00 Books $ 300.00 Escrow $ 334.00 Food:Groceries $ 500.00 Interest:Mortgage $ -2,030.00 Income $ -2,000.00 Salary $ -30.00 Sales $ 180.00 Liabilities $ -20.00 MasterCard $ 200.00 Mortgage:Principal
Ledger does not expand any aliases if this option is specified.
Accounts, tags or commodities not previously declared will cause errors.
Quiet balance assertions.
Specify the location of the price entry data file.
Set the expected freshness of price quotes, in INT minutes. That is, if the last known quote for any commodity is older than this value, and if --download is being used, then the Internet will be consulted again for a newer price. Otherwise, the old price is still considered to be fresh enough.
Ledger normally silently accepts any account or commodity in a posting, even if you have misspelled a commonly used one. The option --strict changes that behavior. While running with --strict, Ledger interprets all cleared transactions as correct, and if it encounters a new account or commodity (same as a misspelled commodity or account) it will issue a warning giving you the file and line number of the problem.
Normally, ledger only expands aliases once. With this option, ledger tries to expand the result of alias expansion recursively, until no more expansions apply.
The --time-colon option will display the value for a seconds based commodity as real hours and minutes.
For example 8100 seconds by default will be displayed as 2.25 whereas with the --time-colon option they will be displayed as 2:15.
Set a global value expression annotation.
Next: Basic options, Previous: Session Options, Up: Detailed Option Description [Contents][Index]
Options for Ledger reports affect three separate scopes of operation: Global, Session, and Report. In practice there is very little difference between these scopes. Ledger 3.0 contains provisions for GUIs, which would make use of the different scopes by keeping an instance of Ledger running in the background and running multiple sessions with multiple reports per session.
Set the minimum length an account can be abbreviated to if it doesn’t
fit inside the account-width
. If INT is zero, then the
account name will be truncated on the right. If INT is greater
than account-width
then the account will be truncated on the
left, with no shortening of the account names in order to fit into the
desired width.
Prepend STR to all accounts reported. That is, the option ‘--account Personal’ would tack ‘Personal:’ to the beginning of every account reported in a balance report or register report.
Set the width of the account column in the register
report
to INT characters.
Report only real transactions, ignoring all automated or virtual transactions.
Show only unbudgeted postings.
Apply the given value expression to the posting amount (see Value Expressions). Using --amount EXPR you can apply an arbitrary transformation to the postings.
On a register report print only the date and amount of postings. Useful for graphing and spreadsheet applications.
Set the width in characters of the amount column in the
register
report.
Anonymize registry output, mostly for sending in bug reports.
When generating a ledger transaction from a CSV file using the
convert
command, automatically match an account from the
Ledger journal.
Show auxiliary dates for all calculations (see Effective Dates).
Print average values over the number of transactions instead of running totals.
Specify the format to use for the balance
report (see Format Strings). The default is:
"%(justify(scrub(display_total), 20, -1, true, color))" " %(!options.flat ? depth_spacer : \"\")" "%-(ansify_if(partial_account(options.flat), blue if color))\n%/" "%$1\n%/" "--------------------\n"
Reduce convertible commodities down the bottom of the conversion, e.g. display time in seconds. This also applies to custom commodity conversions (see Commodity equivalences).
Report the cost basis on all posting.
Specify the start DATE of all calculations. Transactions before that date will be ignored.
Print the entire line in bold if the given value expression is true (see Value Expressions).
$ ledger reg Expenses --begin Dec --bold-if "amount>100"
list all transactions since the beginning of December and print in bold any posting greater than $100.
Only display budgeted items. In a register report this displays transactions in the budget, in a balance report this displays accounts in the budget (see Budgeting and Forecasting).
Specify the format to use for the budget
report (see Format Strings). The default is:
"%(justify(scrub(get_at(display_total, 0)), 12, -1, true, color))" " %(justify(-scrub(get_at(display_total, 1)), 12, " " 12 + 1 + 12, true, color))" " %(justify(scrub(get_at(display_total, 1) + " " get_at(display_total, 0)), 12, " " 12 + 1 + 12 + 1 + 12, true, color))" " %(ansify_if(" " justify((get_at(display_total, 1) ? " " (100% * quantity(scrub(get_at(display_total, 0)))) / " " -quantity(scrub(get_at(display_total, 1))) : 0), " " 5, -1, true, false)," " magenta if (color and get_at(display_total, 1) and " " (abs(quantity(scrub(get_at(display_total, 0))) / " " quantity(scrub(get_at(display_total, 1)))) >= 1))))" " %(!options.flat ? depth_spacer : \"\")" "%-(ansify_if(partial_account(options.flat), blue if color))\n" "%/%$1 %$2 %$3 %$4\n%/" "%(prepend_width ? \" \" * int(prepend_width) : \"\")" "------------ ------------ ------------ -----\n"
Group the register report by payee.
Consider only transactions that have been cleared for display and calculation.
Specify the format to use for the cleared
report (see Format Strings). The default is:
"%(justify(scrub(get_at(total_expr, 0)), 16, 16 + prepend_width, " " true, color)) %(justify(scrub(get_at(total_expr, 1)), 18, " " 36 + prepend_width, true, color))" " %(latest_cleared ? format_date(latest_cleared) : \" \")" " %(!options.flat ? depth_spacer : \"\")" "%-(ansify_if(partial_account(options.flat), blue if color))\n%/" "%$1 %$2 %$3\n%/" "%(prepend_width ? \" \" * prepend_width : \"\")" "---------------- ---------------- ---------\n"
By default ledger prints all accounts in an account tree. With --collapse it prints only the top level account specified.
Collapse the account display only if it has a zero balance.
Use color if the terminal supports it.
Specify the width of the register
report in characters.
Direct ledger to report the number of items when appended to the
commodities
, accounts
or payees
command.
Specify the format to use for the csv
report (see Format Strings). The default is:
"%(quoted(date))," "%(quoted(code))," "%(quoted(payee))," "%(quoted(display_account))," "%(quoted(commodity(scrub(display_amount))))," "%(quoted(quantity(scrub(display_amount))))," "%(quoted(cleared ? \"*\" : (pending ? \"!\" : \"\")))," "%(quoted(join(note | xact.note)))\n"
Shorthand for ‘--limit "date <= today"’.
Shorthand for ‘--period "daily"’.
Transform the date of the transaction using EXPR.
Specify the format ledger should use to read and print dates (see Date and Time Format Codes).
Specify the width, in characters, of the date column in the
register
report.
Specify the format ledger should use to print datetimes.
Display register or balance in debit/credit format If you use
--dc with either the register
(reg) or
balance
(bal) commands, you will now get extra columns.
The register goes from this:
12-Mar-10 Employer Assets:Cash $100 $100 Income:Employer $-100 0 12-Mar-10 KFC Expenses:Food $20 $20 Assets:Cash $-20 0 12-Mar-10 KFC - Rebate Assets:Cash $5 $5 Expenses:Food $-5 0 12-Mar-10 KFC - Food & Reb.. Expenses:Food $20 $20 Expenses:Food $-5 $15 Assets:Cash $-15 0
To this:
12-Mar-10 Employer Assets:Cash $100 0 $100 In:Employer 0 $100 0 12-Mar-10 KFC Expens:Food $20 0 $20 Assets:Cash 0 $20 0 12-Mar-10 KFC - Rebate Assets:Cash $5 0 $5 Expens:Food 0 $5 0 12-Mar-10 KFC - Food &.. Expens:Food $20 0 $20 Expens:Food 0 $5 $15 Assets:Cash 0 $15 0
Where the first column is debits, the second is credits, and the third is the running total. Only the running total may contain negative values.
For the balance report without --dc:
$70 Assets:Cash $30 Expenses:Food $-100 Income:Employer -------------------- 0
And with --dc it becomes this:
$105 $35 $70 Assets:Cash $40 $10 $30 Expenses:Food 0 $100 $-100 Income:Employer -------------------------------------------- $145 $145 0
Limit the depth of the account tree. In a balance report, for example, a ‘--depth 2’ statement will print balances only for accounts with two levels, i.e. ‘Expenses:Entertainment’ but not ‘Expenses:Entertainment:Dining’. This is a display predicate, which means it only affects display, not the total calculations.
Report each posting’s deviation from the average. It is only meaningful in the register and prices reports.
Display only lines that satisfy the expression EXPR.
Apply a transformation to the displayed amount. This happens after calculations occur.
Apply a transformation to the displayed total. This happens after calculations occur.
Group transactions by the day of the week.
$ ledger reg Expenses --dow --collapse
Will print all Expenses totaled for each day of the week.
Include empty accounts in the report and in average calculations.
Specify the end DATE for a transaction to be considered in the report. All transactions on or after this date are ignored.
Related to the equity
command (see The equity
command). Gives current account balances in the form of a register
report.
Report beginning and ending of periods by the date of the first and last posting occurring in that period.
Display values in terms of the given COMMODITY. The latest available price is used. The syntax -X COMMODITY1:COMMODITY2 displays values in COMMODITY1 in terms of COMMODITY2 using the latest available price, but will not automatically covert any other commodities to COMMODITY2. Multiple -X arguments may be used on a single command-line (as in -X COMMODITY1:COMMODITY2 -X COMMODITY3:COMMODITY2), which is particularly useful for situations where many prices are available for reporting in terms of COMMODITY2, but only a few should be displayed that way.
Force the full names of accounts to be used in the balance report. The balance report will not use an indented tree.
Output TTY color codes even if the TTY doesn’t support them. Useful for TTYs that don’t advertise their capabilities correctly.
Force Ledger to paginate its output.
Continue forecasting while VEXPR is true.
Forecast at most INT years into the future.
Use the given format string to print output.
Report on gains using the latest available prices.
Include auto-generated postings (such as those from automated transactions) in the report, in cases where you normally wouldn’t want them.
Group transactions together in the register
report.
EXPR can be anything, although most common would be payee
or commodity
. The tags()
function is also useful here.
Set the format for the headers that separates the report sections of a grouped report.  Expenses:Auto:Hobbies $ 48.20 $ 48.20 ...
Print the first INT entries. Opposite of --tail INT.
Value commodities at the time of their acquisition.
Evaluate calculations immediately rather than lazily.
Use Expected
amounts in calculations. In case you know
what amount a transaction should be, but the actual transaction has the
wrong value you can use metadata to specify the expected amount:
2012-03-12 Paycheck Income $-990; Expected:: $-1000.00 Checking
Then using the command ledger reg --inject=Expected Income
would
treat the transaction as if the “Expected Value” was actual.
Change the sign of all reported values.
Only transactions that satisfy EXPR are considered in calculations and for display.
Report the date on which each commodity in a balance report was purchased.
Report the tag attached to each commodity in a balance report.
Report the price at which each commodity in a balance report was purchased.
Report the date and price at which each commodity was purchased in a balance report.
Preserve the uniqueness of commodities so they aren’t merged during reporting without printing the lot annotations.
Use the latest market value for all commodities.
In the register report, prepend the transaction with the value of the given TAG.
Specify the width of the Meta column used for the --meta TAG options.
Synonym for ‘--period "monthly"’.
Aliases are completely ignored.
Suppress any color TTY output.
Direct output to stdout, avoiding pager program.
Stop Ledger from showing <Revalued>
postings. This option is useful
in combination with the --exchange or --market option.
Don’t output ‘<Adjustment>’ postings. Note that this will cause the running total to often not add up! Its main use is for --amount-data (-j) and --total-data (-J) reports.
Suppress the output of group titles.
Suppress printing the final total line in a balance report.
Define the current date in case you want to calculate in the past or future using --current.
This is a postings predicate that applies after certain transforms have been executed, such as periodic gathering.
Redirect the output of ledger to the file defined in FILE.
Direct output to FILE pager program.
Sets a value expression for formatting the payee. In the
register
report this prevents the second entry from having
a date and payee for each transaction.
Set the number of columns dedicated to the payee in the register report to INT.
Use only postings that are marked pending.
Calculate the percentage value of each account in balance reports. Only works for accounts that have a single commodity.
Define a period expression that sets the time period during which
transactions are to be accounted. For a register
report only
the transactions that satisfy the period expression with be displayed.
For a balance
report only those transactions will be accounted
in the final balances.
Produce a balance pivot report around the given TAG. For example, if you have multiple cars and track each fuel purchase in ‘Expenses:Auto:Fuel’ and tag each fuel purchase with a tag identifying which car the purchase was for ‘; Car: Prius’, then the command:
$ ledger bal Fuel --pivot "Car" --period "this year"
$ 3491.26 Car $ 1084.22 M3:Expenses:Auto:Fuel $ 149.65 MG V11:Expenses:Auto:Fuel $ 621.89 Prius:Expenses:Auto:Fuel $ 1635.50 Sienna:Expenses:Auto:Fuel $ 42.69 Expenses:Auto:Fuel -------------------- $ 3533.95
See Metadata values.
Define the output format for an amount data plot. See Visualizing with Gnuplot.
Define the output format for a total data plot. See Visualizing with Gnuplot.
Prepend STR to every line of the output.
Reserve INT spaces at the beginning of each line of the output.
Use the price of the commodity purchase for performing calculations.
Set the format expected for the historical price file.
Set the format for the prices
report.
Show primary dates for all calculations (see Effective Dates).
Report commodity totals (this is the default).
Synonym for ‘--period "quarterly"’.
In the print
report, show transactions using the exact same
syntax as specified by the user in their data file. Don’t do any
massaging or interpreting. This can be useful for minor cleanups, like
just aligning amounts.
Account using only real transactions ignoring virtual and automatic transactions.
Define the output format for the register
report.
In a register
report show the related account. This is the
other side of the transaction.
Show all postings in a transaction, similar to --related but show both sides of each transaction.
Report discrepancy in values for manual reports by inserting <Revalued>
postings. This is implied when using the --exchange or
--market option.
Show only <Revalued>
postings.
Display the sum of the revalued postings as the running total, which serves to show unrealized capital in a gain/losses report.
When generating a ledger transaction from a CSV file using the
convert
command, add CSV, Imported, and UUID metadata.
Set the random seed to INT for the generate
command.
Used as part of development testing.
Sort the register
report based on the value expression given
to sort.
UNDOCUMENTED! Please help by contributing documentation for this feature.
Sort the postings within transactions using the given value expression.
Tell ledger to use a particular day of the week to start its “weekly” summary. ‘--start-of-week=1’ specifies Monday as the start of the week.
Cause all transactions in a register
report to be collapsed
into a single, subtotaled transaction.
Report only the last INT entries. Only useful in
a register
report.
Add two columns to the balance report to show the earliest checkin and checkout times for timelog entries.
Define a value expression used to calculate the total in reports.
Show only dates and totals to format the output for plots.
Set the width of the total field in the register report.
Indicates how truncation should happen when the contents of columns exceed their width. Valid arguments are ‘leading’, ‘middle’, and ‘trailing’. The default is smarter than any of these three, as it considers sub-names within the account name (that style is called “abbreviate”).
Show only unbudgeted postings.
Use only uncleared transactions in calculations and reports.
Show generated unrealized gain and loss accounts in the balance report.
Allow the user to specify what account name should be used for unrealized gains. Defaults to ‘"Equity:Unrealized Gains"’. Often set in one’s ~/.ledgerrc file to change the default.
Allow the user to specify what account name should be used for unrealized losses. Defaults to ‘"Equity:Unrealized Losses"’. Often set in one’s ~/.ledgerrc file to change the default.
Perform all calculations without rounding and display results to full precision.
Shows the values used by each tag when used in combination with the
tags
command.
Synonym for ‘--period "weekly"’.
Let the register report use 132 columns instead of 80 (the default). Identical to ‘--columns "132"’.
Synonym for ‘--period "yearly"’.
Next: Report filtering, Previous: Report Options, Up: Detailed Option Description [Contents][Index]
These are the most basic command options. Most likely, the user will want to set them using environment variables (see Environment variables), instead of using actual command-line options:
Display the man page for ledger.
Print the current version of ledger and exits. This is useful for sending bug reports, to let the author know which version of ledger you are using.
Read FILE as a ledger file. FILE can be ‘-’ which is
a synonym for ‘/dev/stdin’. This command may be used multiple
times. Typically, the environment variable LEDGER_FILE
is set,
rather than using this command-line option.
Redirect output from any command to FILE. By default, all output goes to standard output.
Causes FILE to be read by ledger before any other ledger file. This file may not contain any postings, but it may contain option settings. To specify options in the init file, use the same syntax as on the command-line, but put each option on its own line. Here is an example init file:
--price-db ~/finance/.pricedb --wide ; ~/.ledgerrc ends here
Option settings on the command-line or in the environment always take precedence over settings in the init file.
Specify the default account which QIF file postings are assumed to relate to.
Next: Output customization, Previous: Basic options, Up: Detailed Option Description [Contents][Index]
These options change which postings affect the outcome of a report, in ways other than just using regular expressions:
Display only transactions occurring on or before the current date.
Constrain the report to transactions on or after DATE. Only transactions after that date will be calculated, which means that the running total in the balance report will always start at zero with the first matching transaction. (Note: This is different from using --display EXPR to constrain what is displayed).
Constrain the report so that transactions on or after DATE are not considered.
Set the reporting period to STR. This will subtotal all matching transactions within each period separately, making it easy to see weekly, monthly, quarterly, etc., posting totals. A period string can even specify the beginning and end of the report range, using simple terms like ‘last June’ or ‘next month’. For more details on period expressions, see Period Expressions.
Sort the postings within each reporting period using the value expression EXPR. This is most often useful when reporting monthly expenses, in order to view the highest expense categories at the top of each month:
$ ledger -M --period-sort total reg ^Expenses
Display only postings whose transaction has been marked “cleared” (by placing an asterisk to the right of the date).
Display only postings whose transaction has not been marked “cleared” (i.e., if there is no asterisk to the right of the date).
Display only real postings, not virtual. (A virtual posting is indicated by surrounding the account name with parentheses or brackets; see Virtual postings for more information).
Display only actual postings, and not those created by automated transactions.
Display postings that are related to whichever postings would otherwise have matched the filtering criteria. In the register report, this shows where money went to, or the account it came from. In the balance report, it shows all the accounts affected by transactions having a related posting. For example, if a file had this transaction:
2004/03/20 Safeway Expenses:Food $65.00 Expenses:Cash $20.00 Assets:Checking $-85.00
And the register command was:
$ ledger -f example.dat -r register food
The following would be printed, showing the postings related to the posting that matched:
04-Mar-20 Safeway Expenses:Cash $20.00 $20.00 Assets:Checking $-85.00 $-65.00
Useful for displaying how close your postings meet your budget. --add-budget also shows unbudgeted postings, while --unbudgeted shows only those. --forecast VEXPR is a related option that projects your budget into the future, showing how it will affect future balances. See Budgeting and Forecasting.
Limit which postings take part in the calculations of a report.
Change the value expression used to calculate the “value” column in
the register
report, the amount used to calculate account
totals in the balance
report, and the values printed in the
equity
report. See Value Expressions.
Set the value expression used for the “totals” column in the
register
and balance
reports.
Next: Commodity reporting, Previous: Report filtering, Up: Detailed Option Description [Contents][Index]
These options affect only the output, but not which postings are used to create it:
Cause transactions in a register
report with multiple
postings to be collapsed into a single, subtotaled transaction.
Cause all transactions in a register
report to be collapsed
into a single, subtotaled transaction.
Report subtotals by payee.
Include even empty accounts in the balance
report.
Report posting totals by the week. The week begins on whichever day of the week begins the month containing that posting. To set a specific begin date, use a period string, such as ‘weekly from DATE’.
Report posting totals by month.
Report posting totals by year. For more complex periods, use --period.
Option described above.
Report posting totals for each day of the week. This is an easy way to see if weekend spending is more than on weekdays.
Sort a report by comparing the values determined using the value
expression VEXPR. For example, using ‘-S "-abs(total)"’ in
the balance
report will sort account balances from greatest to
least, using the absolute value of the total. For more on how to use
value expressions, see Value Expressions.
Produce a pivot table around the TAG provided. This requires meta data using valued tags.
Cause the default register
report to assume 132 columns
instead of 80.
Cause only the first INT transactions to be printed. This is different from using the command-line utility head, which would limit to the first INT postings. --tail INT outputs only the last INT transactions. Both options may be used simultaneously. If a negative amount is given, it will invert the meaning of the flag (instead of the first five transactions being printed, for example, it would print all but the first five).
Tell Ledger to pass its output to the given FILE pager program;
very useful when the output is especially long. This behavior can be
made the default by setting the LEDGER_PAGER
environment variable.
Tell Ledger to not pass its output to a pager program; useful when a pager is set by default.
Report the average posting value.
Report each posting’s deviation from the average. It is only meaningful
in the register
and prices
reports.
Show account subtotals in the balance
report as percentages of
the parent account.
Change the register
report so that it prints nothing but the
date and the value column, and the latter without commodities. This is
only meaningful if the report uses a single commodity. This data can
then be fed to other programs, which could plot the date, analyze it,
etc.
Change the register
report so that it prints nothing but the
date and total columns, without commodities.
Limit which postings or accounts are actually displayed in a report. They might still be calculated, and be part of the running total of a register report, for example, but they will not be displayed. This is useful for seeing last month’s checking postings, against a running balance which includes all posting values:
$ ledger -d "d>=[last month]" reg checking
The output from this command is very different from the following, whose running total includes only postings from the last month onward:
$ ledger -p "last month" reg checking
Which is more useful depends on what you’re looking to know: the total amount for the reporting range (using --period PERIOD_EXPRESSION (-p)), or simply a display restricted to the reporting range (using --display EXPR (-d)).
Change the basic date format used by reports. The default uses a date
like ‘2004/08/01’, which represents the default date format of
%Y/%m/%d
. To change the way dates are printed in general, the
easiest way is to put --date-format DATE_FORMAT in the
Ledger initialization file ~/.ledgerrc (or the file referred to
by LEDGER_INIT
).
Set the reporting format for whatever report ledger is about to make. See Format Strings. There are also specific format commands for each report type:
Define the output format for the balance
report. The default
(defined in report.h is:
"%(ansify_if( justify(scrub(display_total), 20, 20 + int(prepend_width), true, color), bold if should_bold)) %(!options.flat ? depth_spacer : \"\") %-(ansify_if( ansify_if(partial_account(options.flat), blue if color), bold if should_bold))\n%/ %$1\n%/ %(prepend_width ? \" \" * int(prepend_width) : \"\") --------------------\n"
Define the format for the cleared report. The default is:
"%(justify(scrub(get_at(display_total, 0)), 16, 16 + int(prepend_width), true, color)) %(justify(scrub(get_at(display_total, 1)), 18, 36 + int(prepend_width), true, color)) %(latest_cleared ? format_date(latest_cleared) : \" \") %(!options.flat ? depth_spacer : \"\") %-(ansify_if(partial_account(options.flat), blue if color))\n%/ %$1 %$2 %$3\n%/ %(prepend_width ? \" \" * int(prepend_width) : \"\") ---------------- ---------------- ---------\n"
Define the output format for the register
report. The default
(defined in report.h is:
"%(ansify_if( ansify_if(justify(format_date(date), int(date_width)), green if color and date > today), bold if should_bold)) %(ansify_if( ansify_if(justify(truncated(payee, int(payee_width)), int(payee_width)), bold if color and !cleared and actual), bold if should_bold)) %(ansify_if( ansify_if(justify(truncated(display_account, int(account_width), int(abbrev_len)), int(account_width)), blue if color), bold if should_bold)) %(ansify_if( justify(scrub(display_amount), int(amount_width), 3 + int(meta_width) + int(date_width) + int(payee_width) + int(account_width) + int(amount_width) + int(prepend_width), true, color), bold if should_bold)) %(ansify_if( justify(scrub(display_total), int(total_width), 4 + int(meta_width) + int(date_width) + int(payee_width) + int(account_width) + int(amount_width) + int(total_width) + int(prepend_width), true, color), bold if should_bold))\n%/ %(justify(\" \", int(date_width))) %(ansify_if( justify(truncated(has_tag(\"Payee\") ? payee : \" \", int(payee_width)), int(payee_width)), bold if should_bold)) %$3 %$4 %$5\n"
Set the format for csv
reports. The default is:
"%(quoted(date)), %(quoted(code)), %(quoted(payee)), %(quoted(display_account)), %(quoted(commodity(scrub(display_amount)))), %(quoted(quantity(scrub(display_amount)))), %(quoted(cleared ? \"*\" : (pending ? \"!\" : \"\"))), %(quoted(join(note | xact.note)))\n"
Set the format for amount plots, using the --amount-data (-j) option. The default is:
"%(format_date(date, \"%Y-%m-%d\")) %(quantity(scrub(display_amount)))\n"
Set the format for total plots, using the --total-data (-J) option. The default is:
"%(format_date(date, \"%Y-%m-%d\")) %(quantity(scrub(display_total)))\n"
Set the format expected for the historical price file. The default is:
"P %(datetime) %(display_account) %(scrub(display_amount))\n"
Set the format for the prices
report. The default is:
"%(date) %-8(display_account) %(justify(scrub(display_amount), 12, 2 + 9 + 8 + 12, true, color))\n"
Next: Environment variables, Previous: Output customization, Up: Detailed Option Description [Contents][Index]
These options affect how commodity values are displayed:
Set the file that is used for recording downloaded commodity prices. It is always read on startup, to determine historical prices. Other settings can be placed in this file manually, to prevent downloading quotes for a specific commodity, for example. This is done by adding a line like the following:
; Don't download quotes for the dollar, or timelog values N $ N h
Note: Ledger NEVER writes output to files. You are responsible for updating the price-db file. The best way is to have your price download script maintain this file.
The format of the file can be changed by telling ledger to use the --pricedb-format FORMAT_STRING you define.
Set the expected freshness of price quotes, in INT minutes. That is, if the last known quote for any commodity is older than this value, and if --download is being used, then the Internet will be consulted again for a newer price. Otherwise, the old price is still considered to be fresh enough.
Cause quotes to be automagically downloaded, as needed, by running
a script named getquote and expecting that script to return
a value understood by ledger. A sample implementation of
a getquote script, implemented in Perl, is provided in the
distribution. Downloaded quote price are then appended to the price
database, usually specified using the environment variable
LEDGER_PRICE_DB
.
There are several different ways that ledger can report the totals it displays. The most flexible way to adjust them is by using value expressions, and the --amount EXPR (-t) and --total VEXPR (-T) options. However, there are also several “default” reports, which will satisfy most users’ basic reporting needs:
Report commodity totals (this is the default).
Report the cost basis for all postings.
Use the last known value for commodities to calculate final values.
Report the net gain/loss for all commodities in the report that have a price history.
Often you will be more interested in the value of your entire holdings, in your preferred currency. It might be nice to know you hold 10,000 shares of PENNY, but you are more interested in whether or not that is worth $1000.00 or $10,000.00. However, the current day value of a commodity can mean different things to different people, depending on the accounts involved, the commodities, the nature of the transactions, etc.
When you specify --market (-V), or --exchange COMMODITY (-X), you are requesting that some or all of the commodities be valuated as of today (or whatever --now DATE is set to). But what does such a valuation mean? This meaning is governed by the presence of a VALUE meta-data property, whose content is an expression used to compute that value.
If no VALUE property is specified, each posting is assumed to have a default, as if you’d specified a global, automated transaction as follows:
= expr true ; VALUE:: market(amount, date, exchange)
This definition emulates the present day behavior of --market (-V) and --exchange COMMODITY (-X) (in the case of ‘-X’, the requested commodity is passed via the string ‘exchange’ above).
One thing many people have wanted to do is to fixate the valuation of old European currencies in terms of the Euro after a certain date:
= expr commodity == "DM" ; VALUE:: date < [Jun 2008] ? market(amount, date, exchange) : 1.44 EUR
This says: If --now DATE is some old date, use market prices as they were at that time; but if --now DATE is past June 2008, use a fixed price for converting Deutsch Mark to Euro.
Or how about never re-valuating commodities used in Expenses, since they cannot have a different future value:
= /^Expenses:/ ; VALUE:: market(amount, post.date, exchange)
This says the future valuation is the same as the valuation at the time
of posting. post.date
equals the posting’s date, while just ’date’ is
the value of --now DATE (defaults to today).
Or how about valuating miles based on a reimbursement rate during a specific time period:
= expr commodity == "miles" and date >= [2007] and date < [2008] ; VALUE:: market($1.05, date, exchange)
In this case, miles driven in 2007 will always be valuated at $1.05 each. If you use ‘-X EUR’ to expressly request all amounts in Euro, Ledger shall convert $1.05 to Euro by whatever means are appropriate for dollars.
Note that you can have a valuation expression specific to a particular posting or transaction, by overriding these general defaults using specific meta-data:
2010-12-26 Example Expenses:Food $20 ; Just to be silly, always valuate *these* $20 as 30 DM, no matter what ; the user asks for with -V or -X ; VALUE:: 30 DM Assets:Cash
This example demonstrates that your value expression should be as symbolic as possible, using terms like ’amount’ and ’date’, rather than specific amounts and dates. Also, you should pass the amount along to the function ’market’ so it can be further revalued if the user has asked for a specific currency.
Or, if it better suits your accounting, you can be less symbolic, which allows you to report most everything in EUR if you use ‘-X EUR’, except for certain accounts or postings which should always be valuated in another currency. For example:
= /^Assets:Brokerage:CAD$/ ; Always report the value of commodities in this account in ; terms of present day dollars, despite what was asked for ; on the command-line VALUE:: market(amount, date, ‘$’)
Ledger presently has no way of handling such things as FIFO and LIFO.
If you specify an unadorned commodity name, like AAPL, it will balance against itself. If --lots are not being displayed, then it will appear to balance against any lot of AAPL.
If you specify an adorned commodity, like AAPL {$10.00}, it will also balance against itself, and against any AAPL if --lots is not specified. But if you do specify --lot-prices, for example, then it will balance against that specific price for AAPL.
Normally when you use --exchange COMMODITY (-X) to request that amounts be reported in a specific commodity, Ledger uses these values:
register
report, use the value of that commodity on
the date of the posting being reported, with a ‘<Revalued>’ posting
added at the end if today’s value is different from the value of the
last posting.
balance
report, use the value of that commodity as of
today.
You can now specify --historical (-H) to ask that all valuations for any amount be done relative to the date that amount was encountered.
You can also now use --exchange COMMODITY (-X) (and --historical (-H)) in conjunction with --basis (-B) and --price (-I), to see valuation reports of just your basis costs or lot prices.
Finally, sometimes, you may seek to only report one (or some subset) of the commodities in terms of another commodity. In this situation, you can use the syntax --exchange COMMODITY1:COMMODITY2 to request that ledger always display COMMODITY1 in terms of COMMODITY2, but you want no other commodities to be automatically displayed in terms of COMMODITY2 without additional --exchange options. For example, if you wanted to report EUR and BTC in terms of USD, but report all other commodities without conversion to USD, you could use: --exchange EUR:USD --exchange BTC:USD.
Previous: Commodity reporting, Up: Detailed Option Description [Contents][Index]
Every option to ledger may be set using an environment variable if the
option has a long name. For example setting the environment variable
‘LEDGER_DATE_FORMAT
="%d.%m.%Y"’ will have the same effect as specifying
‘--date-format '%d.%m.%Y'’ on the command-line. Options on the
command-line always take precedence over environment variable settings, however.
Note that you may also permanently specify option values by placing option settings in the file ~/.ledgerrc one option per line, for example:
--pager /bin/cat
Previous: Detailed Option Description, Up: Command-Line Syntax [Contents][Index]
A period expression indicates a span of time, or a reporting interval, or both. Ledger’s end dates are always exclusive, imagine the date is followed by 00:00:00 time. They are instants in time not entire days.  As for the begin time, it can be either of:
from <SPEC> since <SPEC>
The end time can be either of:
to <SPEC> until <SPEC>
Where SPEC can be any of:
2004 2004/10 2004/10/1 10/1 october oct this week # or day, month, quarter, year next week last week
The beginning and ending can be given at the same time, if it spans a single period. In that case, just use SPEC by itself. In that case, the period ‘oct’, for example, will cover all the days in October. The possible forms are:
<SPEC> in <SPEC>
Here are a few examples of period expressions:
monthly monthly in 2004 weekly from oct weekly from last month from sep to oct from 10/1 to 10/5 monthly until 2005 from apr until nov last oct weekly last august
Next: Time Keeping, Previous: Command-Line Syntax, Up: Top [Contents][Index]
| • Budgeting: | ||
| • Forecasting: |
Next: Forecasting, Previous: Budgeting and Forecasting, Up: Budgeting and Forecasting [Contents][Index]
Keeping a budget allows you to pay closer attention to your income and expenses, by reporting how far your actual financial activity is from your expectations.
To start keeping a budget, put some periodic transactions (see Periodic Transactions) at the top of your ledger file. A periodic transaction is almost identical to a regular transaction, except that it begins with a tilde and has a period expression in place of a payee. For example:
~ Monthly Expenses:Rent $500.00 Expenses:Food $450.00 Expenses:Auto:Gas $120.00 Expenses:Insurance $150.00 Expenses:Phone $125.00 Expenses:Utilities $100.00 Expenses:Movies $50.00 Expenses $200.00 ; all other expenses Assets ~ Yearly Expenses:Auto:Repair $500.00 Assets
These two periodic transactions give the usual monthly expenses, as well as one typical yearly expense. For help on finding out what your average monthly expenses are for any category, use a command like:
$ ledger -p "this year" --monthly --average register ^expenses
The reported totals are the current year’s average for each account.
Once these periodic transactions are defined, creating a budget report is as easy as adding --budget to the command-line. For example, a typical monthly expense report would be:
$ ledger --monthly register ^expenses
To see the same report balanced against your budget, use:
$ ledger --budget --monthly register ^expenses
A budget report includes only those accounts that appear in the budget. To see all expenses balanced against the budget, use --add-budget. You can even see only the unbudgeted expenses using --unbudgeted:
$ ledger --unbudgeted --monthly register ^expenses
You can also use these flags with the balance
command.
Previous: Budgeting, Up: Budgeting and Forecasting [Contents][Index]
Sometimes it’s useful to know what your finances will look like in the future, such as determining when an account will reach zero. Ledger makes this easy to do, using the same periodic transactions as are used for budgeting. An example forecast report can be generated with:
$ ledger --file drewr3.dat --forecast "T>{\$-500.00}" register ^assets ^liabilities
This report continues outputting postings until the running total is greater than $-500.00. A final posting is always shown, to inform you what the total afterwards would be.
Forecasting can also be used with the balance
report,
but by date only, and not against the running total:
$ ledger --forecast "d<[2010]" bal ^assets ^liabilities
Next: Value Expressions, Previous: Budgeting and Forecasting, Up: Top [Contents][Index]
Ledger directly supports “timelog” entries, which have this form:
i 2013/03/28 22:13:00 ACCOUNT[ PAYEE] o 2013/03/29 03:39:00
This records a check-in to the given ACCOUNT, and a check-out. You can be checked-in to multiple accounts at a time, if you wish, and they can span multiple days (use --day-break to break them up in the report). The number of seconds between check-in and check-out is accumulated as time to that ACCOUNT. If the checkout uses a capital ‘O’, the transaction is marked “cleared”. You can use an optional PAYEE for whatever meaning you like.
Now, there are a few ways to generate this information. You can use the timeclock.el package, which is part of Emacs. Or you can write a simple script in whichever language you prefer to emit similar information. Or you can use Org mode’s time-clocking abilities and the org2tc script developed by John Wiegley.
These timelog entries can appear in a separate file, or directly in your main ledger file. The initial ‘i’ and ‘o’ characters count as Ledger “directives”, and are accepted anywhere that ordinary transactions are valid.
Next: Format Strings, Previous: Time Keeping, Up: Top [Contents][Index]
Ledger uses value expressions to make calculations for many different purposes:
Value expressions support most simple math and logic operators, in addition to a set of functions and variables.
Display predicates are also very handy with register reports, to constrain which transactions are printed. For example, the following command shows only transactions from the beginning of the current month, while still calculating the running balance based on all transactions:
$ ledger -d "d>[this month]" register checking
The advantage of this command’s complexity is that it prints the running total in terms of all transactions in the register. The following, simpler command is similar, but totals only the displayed postings:
$ ledger -b "this month" register checking
| • Variables: | ||
| • Functions: | ||
| • Operators: | ||
| • Complex expressions: |
Next: Functions, Previous: Value Expressions, Up: Value Expressions [Contents][Index]
Below are the one letter variables available in any value expression.
For the register
and print
commands, these variables
relate to individual postings, and sometimes the account affected by a
posting. For the balance
command, these variables relate to
accounts, often with a subtle difference in meaning. The use of each
variable for both is specified.
t
This maps to whatever the user specified with --amount
EXPR (-t). In a register
report, --amount
EXPR (-t) changes the value column; in a balance
report, it has no meaning by default. If --amount EXPR
(-t) was not specified, the current report style’s value expression is
used.
T
This maps to whatever the user specified with --total VEXPR (-T). In a register report, --total VEXPR (-T) changes the totals column; in a balance report, this is the value given for each account. If --total VEXPR (-T) was not specified, the current report style’s value expression is used.
m
This is always the present moment/date.
| • Posting/account details: | ||
| • Calculated totals: |
Next: Calculated totals, Previous: Variables, Up: Variables [Contents][Index]
d
A posting’s date, as the number of seconds past the epoch. This is always “today” for an account.
a
The posting’s amount; the balance of an account, without considering children.
b
The cost of a posting; the cost of an account, without its children.
v
The market value of a posting or an account, without its children.
g
The net gain (market value minus cost basis), for a posting or an account, without its children. It is the same as ‘v-b’.
l
The depth (“level”) of an account. If an account has one parent, its depth is one.
n
The index of a posting, or the count of postings affecting an account.
X
‘1’ if a posting’s transaction has been cleared, ‘0’ otherwise.
R
‘1’ if a posting is not virtual, ‘0’ otherwise.
Z
‘1’ if a posting is not automated, ‘0’ otherwise.
Previous: Posting/account details, Up: Variables [Contents][Index]
O
The total of all postings seen so far, or the total of an account and all its children.
N
The total count of postings affecting an account and all its children.
Next: Operators, Previous: Variables, Up: Value Expressions [Contents][Index]
The available one letter functions are:
-
Negates the argument.
U
The absolute (unsigned) value of the argument.
S
Strips the commodity from the argument.
P
The present market value of the argument. The syntax ‘P(x,d)’ is supported, which yields the market value at time ‘d’. If no date is given, then the current moment is used.
Next: Complex expressions, Previous: Functions, Up: Value Expressions [Contents][Index]
The operators, in order of precedence, are:
* /
+ -
! < > =
& | ?:
| • Unary Operators: | ||
| • Binary Operators: |
Next: Binary Operators, Previous: Operators, Up: Operators [Contents][Index]
not
(!
)
neg
Previous: Unary Operators, Up: Operators [Contents][Index]
==
<
<=
>
>=
and
or
+
-
*
/
QUERY
COLON
CONS
SEQ
DEFINE
LOOKUP
LAMBDA
CALL
MATCH
Previous: Operators, Up: Value Expressions [Contents][Index]
More complicated expressions are possible using:
"amount == COMMODITY AMOUNT"
The amount can be any kind of amount supported by ledger, with or without a commodity. Use this for decimal values.
/REGEX/
account =~ /REGEX/
A regular expression that matches against an account’s full name. If a posting, this will match against the account affected by the posting.
@/REGEX/
expr payee =~ /REGEX/
A regular expression that matches against a transaction’s payee name.
%/REGEX/
expr has_tag(/REGEX/)
expr has_tag('TAG')
A regular expression (REGEX) or string (TAG) that checks for the tags of a transaction.
tag(REGEX) =~ /REGEX/
A regular expression that matches a transaction’s tags against its values.
expr date =~ /REGEX/
Useful for specifying a date in plain terms. For example, you could say ‘expr date =~ /2014/’.
expr comment =~ /REGEX/
A regular expression that matches against a posting’s comment
field. This searches only a posting’s field, not the transaction’s note
or comment field. For example, ledger reg "expr" "comment =~
/landline/"
will match:
2014/1/29 Phone bill Assets:Checking $50.00 Expenses:Phone $-50.00 ; landline bill
but will not match:
2014/1/29 Phone bill ; landline bill ; landline bill Assets:Checking $50.00 Expenses:Phone $-50.00
To match the latter, use ‘ledger reg "expr" "note =~ /landline/"’ instead.
expr note =~ /REGEX/
A regular expression that matches against a transaction’s note field. This searches all comments in the transaction, including comments on individual postings. Thus, ‘ledger reg "expr" "note =~ /landline/"’ will match both all the three examples below:
2014/1/29 Phone bill Assets:Checking $50.00 Expenses:Phone $-50.00 ; landline bill
2014/1/29 Phone bill ; landline bill Assets:Checking $50.00 Expenses:Phone $-50.00
2014/1/29 Phone bill ; landline bill Assets:Checking $50.00 Expenses:Phone $-50.00
(EXPR)
A sub-expression is nested in parenthesis. This can be useful passing more complicated arguments to functions, or for overriding the natural precedence order of operators.
expr base =~ /REGEX/
A regular expression that matches against an account’s base name. If a posting, this will match against the account affected by the posting.
expr code =~ /REGEX/
A regular expression that matches against the transaction code (the text that occurs between parentheses before the payee).
expr any(KEYWORD =~ /REGEX/)
The any
keyword is used to specify that at least one posting of
the transaction must match the expression in brackets. For example,
‘ledger -f d reg expr "any(account =~ /Assets:/)"’ can be used to
display all transactions which involve at least one ‘Assets:’
account.
expr all(KEYWORD =~ /REGEX/)
The all
keyword is used to specify that all postings of a
transactions must match the expression in brackets. For example,
‘ledger -f d reg expr "all(account =~ /Assets:/)"’ can be used to
display all transactions where all accounts are ‘Assets:’.
The query
command can be used to see how Ledger interprets
your query. This can be useful if you are not getting the results you
expect (see Pre-Commands).
| • Miscellaneous: |
Previous: Complex expressions, Up: Complex expressions [Contents][Index]
The following Ledger journal data (saved as expr.dat) is used to explain the behaviour of the functions and variables below:
2015/01/16 * (C0D3) Payee Assets:Cash ¤ -123,45 ; Payee: PiggyBank Expenses:Office Supplies
Return the absolute value of the given value, e.g. amount.
$ ledger -f expr.dat --format "%(account) %(abs(amount))\n" reg assets
Assets:Cash ¤ 123,45
Render the given expression as a string, applying the proper ANSI escape codes to display it in the given color if bool is true. It typically checks the value of the option --color. Since ANSI escape codes include non-printable character sequences, such as escape ^[ the following example may not appear as the final result on the command-line.
$ ledger -f expr.dat --format "%(ansify_if(account, blue, options.color))\n" reg
[34mAssets:Cash[0m [34mExpenses:Office Supplies[0m
Return the next integer of value toward +infinity.
$ ledger -f expr.dat --format "%(account) %(ceiling(amount))\n" reg
Assets:Cash ¤ -123,00 Expenses:Office Supplies ¤ 124,00
Return the transaction code, the string between the parenthesis after the date.
$ ledger -f expr.dat --format "%(account) %(code)\n" reg assets
Assets:Cash C0D3
$ ledger -f expr.dat --format "%(account) %(commodity)\n" reg
Assets:Cash ¤ Expenses:Office Supplies ¤
$ ledger -f expr.dat --format "%(date) %(account)\n" reg assets
2015/01/16 Assets:Cash
UNDOCUMENTED! Please help by contributing documentation for this feature.
UNDOCUMENTED! Please help by contributing documentation for this feature.
Return the next integer of value toward -infinity.
$ ledger -f expr.dat --format "%(account) %(floor(amount))\n" reg
Assets:Cash ¤ -124,00 Expenses:Office Supplies ¤ 123,00
Return the date as a string using format. See
strftime (3)
for format string details.
$ ledger -f expr.dat --format "%(format_date(date, '%A, %B %d. %Y'))\n" reg assets
Friday, January 16. 2015
Return the datetime as a string using format. Refer to
strftime (3)
for format string details.
Return the value in sequence at index. The first element is index 0. For internal use only.
Right or left justify the string representing value. The width of the field in the first line is given by first_width. For subsequent lines the width is given by latter_width. If latter_width=-1, then first_width is used for all lines. If right_justify=true then the field is right justified within the width of the field. If it is false, then the field is left justified and padded to the full width of the field. If colorize is true, then ledger will honor color settings.
$ ledger -f expr.dat --format "»%(justify(account, 30, 30, true))«\n" reg
» Assets:Cash« » Expenses:Office Supplies«
Return the price of value at datetime. Note that datetime
must be surrounded by brackets in order to be parsed correctly,
e.g. [2012/03/23]
.
A variable that allows access to the values of the given command-line options
using the long option names, e.g. to see whether --daily or -D
was given use option.daily
.
$ ledger -f expr.dat -X $ -D --format "%(options.daily) %(options.exchange)\n" reg assets
true $
Return the percentage of value_a in relation to value_b (used as 100%)
$ ledger -f expr.dat --format "%(percent(amount, 200))\n" reg
-61.73% 61.73%
Surround expression with double-quotes. If expression contains a double-quote, it will be escaped with a backslash.
$ ledger -f expr.dat --format "%(quoted(account)) %(quoted(amount))\n" reg
"Assets:Cash" "¤ -123,45" "Expenses:Office Supplies" "¤ 123,45"
Return value rounded to n digits. Does not affect formatting.
$ ledger -f expr.dat --format "%(account) %(roundto(amount, 1))\n" reg
Assets:Cash ¤ -123,40 Expenses:Office Supplies ¤ 123,50
Clean value using various transformations such as round
, stripping
value annotations, and more.
Return true if expression given to --bold-if evaluates to true. For internal use only.
Return the integer value for value.
$ ledger -f expr.dat --format "%(1 + to_int('1'))\n%(2,5 + int(2,5))\n" reg assets
2 4.5
$ ledger -f expr.dat --now 2015/01/01 --format "%(today)\n" reg assets
2015/01/01
Trim leading and trailing whitespace from value.
$ ledger -f expr.dat --format "»%(trim(' Trimmed '))«\n" reg assets
»Trimmed«
Truncate string to total_len ensuring that each account is at least account_len long.
Next: Extending with Python, Previous: Value Expressions, Up: Top [Contents][Index]
| • Format String Basics: | ||
| • Format String Structure: | ||
| • Format Expressions: | ||
| • Balance format: | ||
| • Formatting Functions and Codes: |
Next: Format String Structure, Previous: Format Strings, Up: Format Strings [Contents][Index]
Format strings may be used to change the output format of reports. They are specified by passing a formatting string to the --format FORMAT_STRING (-F) option. Within that string, constructs are allowed which make it possible to display the various parts of an account or posting in custom ways.
There are several additional flags that allow you to define formats for specific reports. These are useful to define in your configuration file and will allow you to run ledger reports from the command-line without having to enter a new format for each command.
Next: Format Expressions, Previous: Format String Basics, Up: Format Strings [Contents][Index]
Within a format string, a substitution is specified using a percent ‘%’ character. The basic format of all substitutions is:
%[-][MIN WIDTH][.MAX WIDTH](VALEXPR)
If the optional minus sign ‘-’ follows the percent character ‘%’, whatever is substituted will be left justified. The default is right justified. If a minimum width is given next, the substituted text will be at least that wide, perhaps wider. If a period and a maximum width is given, the substituted text will never be wider than this, and will be truncated to fit. Here are some examples:
%-20P
A transaction’s payee, left justified and padded to 20 characters wide.
%20P
The same, right justified, at least 20 chars wide.
%.20P
The same, no more than 20 chars wide.
The expression following the format constraints can be a single letter, or an expression enclosed in parentheses or brackets.
Next: Balance format, Previous: Format String Structure, Up: Format Strings [Contents][Index]
For demonstration purposes the journal data from expr.dat is used. The allowable expressions are:
%
Inserts a percent sign.
$ ledger -f expr.dat --format "%%\n" reg assets
%
t
Inserts the results of the value expression specified by --amount EXPR (-t). If --amount EXPR (-t) was not specified, the current report style’s value expression is used.
T
Inserts the results of the value expression specified by --total VEXPR (-T). If --total VEXPR (-T) was not specified, the current report style’s value expression is used.
(EXPR)
Inserts the amount resulting from the value expression given in parentheses. To insert five times the total value of an account, for example, one could say ‘%12(5*O)’. Note: It’s important to put the five first in that expression, so that the commodity doesn’t get stripped from the total.
$ ledger -f expr.dat --format "%12(5*O)\n" reg assets
¤ -617,25
[DATEFMT]
Inserts the result of formatting a posting’s date with a date format
string, exactly like those supported by strftime (3)
. For
example: ‘%[%Y/%m/%d %H:%M:%S]’.
S
Insert the path name of the file from which the transaction’s data was
read. Only sensible in a register
report.
$ ledger -f ~/journal.dat --format "%S\n" reg assets
/home/jwiegley/journal.dat
B
Inserts the beginning character position of that transaction within the file.
$ ledger -f expr.dat --format "%B\n" reg assets
26
b
Inserts the beginning line of that transaction within the file.
$ ledger -f expr.dat --format "%b\n" reg assets
2
E
Inserts the ending character position of that transaction within the file.
$ ledger -f expr.dat --format "%E\n" reg assets
90
e
Inserts the ending line of that transaction within the file.
$ ledger -f expr.dat --format "%e\n" reg assets
3
D
Returns the date according to the default format.
d
Returns the date according to the default format. If the transaction
has an effective date, it prints ACTUAL_DATE=EFFECTIVE_DATE
.
X
If a posting has been cleared, this returns a 1, otherwise returns 0.
Y
This is the same as ‘%X’, except that it only displays a state character if all of the member postings have the same state.
C
Inserts the transaction code. This is the value specified between parentheses on the first line of the transaction.
$ ledger -f expr.dat --format "%C\n" reg assets
(C0D3)
P
Inserts the payee related to a posting.
$ ledger -f expr.dat --format "%P\n" reg assets
PiggyBank
A
Inserts the full name of an account.
$ ledger -f expr.dat --format "%A\n" reg
Assets:Cash Expenses:Office Supplies
N
Inserts the note associated with a posting, if one exists.
$ ledger -f expr.dat --format "%N\n" reg assets
Payee: PiggyBank
/
The ‘%/’ construct is special. It separates a format string between what is printed for the first posting of a transaction, and what is printed for all subsequent postings. If not used, the same format string is used for all postings.
$ ledger -f expr.dat --format "%P\n%/%A\n" reg
PiggyBank Expenses:Office Supplies
Next: Formatting Functions and Codes, Previous: Format Expressions, Up: Format Strings [Contents][Index]
As an example of how flexible the --format FORMAT_STRING strings can be, the default balance format looks like this (the various functions are described later):
"%(justify(scrub(display_total), 20, -1, true, color))" " %(!options.flat ? depth_spacer : \"\")" "%-(ansify_if(partial_account(options.flat), blue if color))\n%/" "%$1\n%/" "--------------------\n"
Previous: Balance format, Up: Format Strings [Contents][Index]
| • Field Widths: | ||
| • Colors: | ||
| • Quantities and Calculations: | ||
| • Date Functions: | ||
| • Date and Time Format Codes: | ||
| • Text Formatting: | ||
| • Data File Parsing Information: |
Next: Colors, Previous: Formatting Functions and Codes, Up: Formatting Functions and Codes [Contents][Index]
The following codes return the width allocated for the specific fields. The defaults can be changed using the corresponding command-line options:
date_width
payee_width
account_width
amount_width
total_width
Next: Quantities and Calculations, Previous: Field Widths, Up: Formatting Functions and Codes [Contents][Index]
The character-based formatting ledger can do is limited to the ANSI terminal character colors and font highlights in a normal TTY session.
red | magenta | bold |
green | cyan | underline |
yellow | white | blink |
blue | black |
Next: Date Functions, Previous: Colors, Up: Formatting Functions and Codes [Contents][Index]
amount_expr
abs
commodity
display_amount
display_total
floor
get_at
is_seq
market
percent
price
quantity
rounded
truncated
total_expr
top_amount
to_boolean
to_int
to_amount
to_balance
unrounded
Next: Date and Time Format Codes, Previous: Quantities and Calculations, Up: Formatting Functions and Codes [Contents][Index]
The following functions allow you to manipulate and format dates.
date
Return the date of the current transaction.
format_date(date, "FORMAT_STRING")
Format the date using the given format string.
now
Return the current date and time. If the --now DATE option is defined it will return that value.
today
Return the current date. If the --now DATE option is defined it will return that value.
to_datetime
Convert a string to a date-time value.
to_date
Convert a string to date value.
value_date
| • Date and Time Format Codes: |
Next: Text Formatting, Previous: Date Functions, Up: Formatting Functions and Codes [Contents][Index]
Date and time format are specified as strings of single letter codes preceded by percent signs. Any separator, or no separator can be specified.
| • Days: | ||
| • Weekdays: | ||
| • Month: | ||
| • Miscellaneous Date Codes: |
Next: Weekdays, Previous: Date and Time Format Codes, Up: Date and Time Format Codes [Contents][Index]
Dates are formed from a combination of day, month and year codes, in whatever order you prefer:
%Y
Four digit year.
%y
Two digit year.
%m
Two digit month.
%d
Two digit date.
So "%Y%m%d"
yields ‘20111214’ which provides a date that
is simple to sort on.
Next: Month, Previous: Days, Up: Date and Time Format Codes [Contents][Index]
You can have additional weekday information in your date with ‘%A’ as
%m-%d-%Y %A
yields ‘02-10-2010 Wednesday’.
%A %m-%d-%Y
yields ‘Wednesday 02-10-2010’.
These are options you can select for weekday
%a
weekday, abbreviated Wed.
%A
weekday, full Wednesday.
%d
day of the month (dd), zero padded up to 10.
%e
day of the month (dd), no leading zero up to 10.
%j
day of year, zero padded 000–366.
%u
day of week starting with Monday (1), i.e. mtwtfss
3.
%w
day of week starting with Sunday (0), i.e. smtwtfs
3.
Next: Miscellaneous Date Codes, Previous: Weekdays, Up: Date and Time Format Codes [Contents][Index]
You can have additional month information in your date with ‘%B’ as
%m-%d-%Y %B
yields ‘02-10-2010 February’.
%B %m-%d-%Y
yields ‘February 02-10-2010’.
These are options you can select for month
%m
‘mm’ month as two digits.
%b
Locale’s abbreviated month, for example ‘02’ might be abbreviated as ‘Feb’.
%B
Locale’s full month, variable length, e.g. February.
Previous: Month, Up: Date and Time Format Codes [Contents][Index]
Additional date format parameters which can be used:
%U
week number Sunday as first day of week, ranging 01–53.
%W
week number Monday as first day of week, ranging 01–53.
%V
week of the year, ranging 01–53.
%C
century, ranging 00–99.
%D
yields %m/%d/%y
as in ‘02/10/10’.
%x
locale’s date representation, as ‘02/10/2010’ for the U.S.
%F
yields %Y-%m-%d
as in ‘2010-02-10’.
Next: Data File Parsing Information, Previous: Date and Time Format Codes, Up: Formatting Functions and Codes [Contents][Index]
The following format functions allow you limited formatting of text:
ansify_if(value, color)
Surrounds the string representing value with ANSI codes to give it
color
on an TTY display. Has no effect if directed to a file.
justify(value, first_width, latter_width, right_justify, colorize)
Right or left justify the string representing value
. The width
of the field in the first line is given by first_width
. For
subsequent lines the width is given by latter_width
. If
latter_width=-1
, then first_width
is use for all lines.
If right_justify=true
then the field is right justify within
the width of the field. If it is false
, then the field is left
justified and padded to the full width of the field. If
colorize
is true, then ledger will honor color settings.
join(STR)
Replaces line feeds in STR
with ‘\n’.
quoted(STR)
Return STR
surrounded by double quotes, ‘"STR"’.
strip(value)
Values can have numerous annotations, such as effective dates and lot
prices. strip
removes these annotations.
Previous: Text Formatting, Up: Formatting Functions and Codes [Contents][Index]
The following format strings provide locational metadata regarding the coordinates of entries in the source data file(s) that generated the posting.
filename
the name of the ledger data file from whence the posting came, abbreviated ‘S’.
beg_pos
character position in filename
where entry for posting begins,
abbreviated ‘B’.
end_pos
character position in filename
where entry for posting ends,
abbreviated ‘E’.
beg_line
line number in filename
where entry for posting begins,
abbreviated ‘b’.
end_line
line number in filename
where entry for posting ends,
abbreviated ‘e’.
Next: Ledger for Developers, Previous: Format Strings, Up: Top [Contents][Index]
Python can be used to extend your Ledger experience. But first, a word must be said about Ledger’s data model, so that other things make sense later.
| • Basic data traversal: | ||
| • Raw versus Cooked: | ||
| • Queries: | ||
| • Embedded Python: | ||
| • Amounts: |
Next: Raw versus Cooked, Previous: Extending with Python, Up: Extending with Python [Contents][Index]
Every interaction with Ledger happens in the context of a Session. Even if you don’t create a session manually, one is created for you by the top-level interface functions. The Session is where objects live like the Commodities that Amounts refer to.
To make a Session useful, you must read a Journal into it, using the
function ‘read_journal
‘. This reads Ledger data from the given
file, populates a Journal object within the current Session, and
returns a reference to that Journal object.
Within the Journal live all the Transactions, Postings, and other objects related to your data. There are also AutomatedTransactions and PeriodicTransactions, etc.
Here is how you would traverse all the postings in your data file:
import ledger for xact in ledger.read_journal("sample.dat").xacts(): for post in xact.posts(): print "Transferring %s to/from %s" % (post.amount, post.account)
Next: Queries, Previous: Basic data traversal, Up: Extending with Python [Contents][Index]
Ledger data exists in one of two forms: raw and cooked. Raw objects are what you get from a traversal like the above, and represent exactly what was seen in the data file. Consider this journal:
= true (Assets:Cash) $100 2012-03-01 KFC Expenses:Food $100 Assets:Credit
In this case, the raw regular transaction in this file is:
2012-03-01 KFC Expenses:Food $100 Assets:Credit
While the cooked form is:
2012-03-01 KFC Expenses:Food $100 Assets:Credit $-100 (Assets:Cash) $100
So the easy way to think about raw vs. cooked is that raw is the unprocessed data, and cooked has had all considerations applied.
When you traverse a Journal by iterating over its transactions, you are generally looking at raw data. In order to look at cooked data, you must generate a report of some kind by querying the journal:
for post in ledger.read_journal("sample.dat").query("food"): print "Transferring %s to/from %s" % (post.amount, post.account)
The reason why queries iterate over postings instead of transactions is
that queries often return only a “slice” of the transactions they
apply to. You can always get at a matching posting’s transaction by
looking at its xact
member:
last_xact = None for post in ledger.read_journal("sample.dat").query(""): if post.xact != last_xact: for post in post.xact.posts(): print "Transferring %s to/from %s" % (post.amount, post.account) last_xact = post.xact
This query ends up reporting every cooked posting in the Journal, but does it transaction-wise. It relies on the fact that an unsorted report returns postings in the exact order they were parsed from the journal file.
Next: Embedded Python, Previous: Raw versus Cooked, Up: Extending with Python [Contents][Index]
The Journal.query() method accepts every argument you can specify on the command-line, including --options.
Since a query “cooks” the journal it applies to, only one query may be active for that journal at a given time. Once the query object is gone (after the for loop), then the data reverts back to its raw state.
Next: Amounts, Previous: Queries, Up: Extending with Python [Contents][Index]
You can embed Python into your data files using the ’python’ directive:
python import os def check_path(path_value): print "%s => %s" % (str(path_value), os.path.isfile(str(path_value))) return os.path.isfile(str(path_value)) tag PATH assert check_path(value) 2012-02-29 KFC ; PATH: somebogusfile.dat Expenses:Food $20 Assets:Cash
Any Python functions you define this way become immediately available as valexpr functions.
Previous: Embedded Python, Up: Extending with Python [Contents][Index]
When numbers come from Ledger, like post.amount, the type of the value is Amount. It can be used just like an ordinary number, except that addition and subtraction are restricted to amounts with the same commodity. If you need to create sums of multiple commodities, use a Balance. For example:
total = Balance() for post in ledger.read_journal("sample.dat").query(""): total += post.amount print total
Next: Major Changes from version 2.6, Previous: Extending with Python, Up: Top [Contents][Index]
| • Internal Design: | ||
| • Journal File Format for Developers: | ||
| • Developer Commands: | ||
| • Ledger Development Environment: |
Next: Journal File Format for Developers, Previous: Ledger for Developers, Up: Ledger for Developers [Contents][Index]
Ledger is developed as a tiered set of functionality, where lower tiers know nothing about the higher tiers. In fact, multiple libraries are built during the development the process, and link unit tests to these libraries, so that it is a link error for a lower tier to violate this modularity.
Those tiers are:
There’s lots of general utility in Ledger for doing time parsing, using Boost.Regex, error handling, etc. It’s all done in a way that can be reused in other projects as needed.
A numerical abstraction combining multi-precision rational numbers (via GMP) with commodities. These structures can be manipulated like regular numbers in either C++ or Python (as Amount objects).
Commodities are all owned by a commodity pool, so that future parsing of amounts can link to the same commodity and established a consistent price history and record of formatting details.
Adds the concept of multiple amounts with varying commodities. Supports simple arithmetic, and multiplication and division with non-commoditized values.
Amounts have prices, and these are kept in a data graph which the amount code itself is only dimly aware of (there’s three points of access so an amount can query its revalued price on a given date).
Often the higher layers in Ledger don’t care if something is an amount
or a balance, they just want to add stuff to it or print it. For this,
I created a type-erasure class, value_t/Value, into which many things
can be stuffed and then operated on. They can contain amounts,
balances, dates, strings, etc. If you try to apply an operation between
two values that makes no sense (like dividing an amount by a balance),
an error occurs at runtime, rather than at compile-time (as would happen
if you actually tried to divide an amount_t
by
a balance_t
).
This is the core data type for the value expression language.
The next layer up adds functions and operators around the Value concept. This lets you apply transformations and tests to Values at runtime without having to bake it into C++. The set of functions available is defined by each object type in Ledger (posts, accounts, transactions, etc.), though the core engine knows nothing about these. At its base, it only knows how to apply operators to values, and how to pass them to and receive them from functions.
Expressions can be onerous to type at the command-line, so there’s a shorthand for reporting called “query expressions”. These add no functionality of their own, but are purely translated from the input string down to the corresponding value expression, for example the input string ‘cash’ is translated to ‘(account =~ /cash/)’. This is a convenience layer.
Format strings let you interpolate value expressions into strings, with
the requirement that any interpolated value have a string
representation. Really all this does is calculate the value expression
in the current report context, call the resulting value’s
to_string()
method, and stuffs the result into the output string.
It also provides printf-like behavior, such as min/max width, right/left
justification, etc.
Next is a base type shared by anything that can appear in a journal: an item_t. It contains details common to all such parsed entities, like what file and line it was found on, etc.
The most numerous object found in a Journal, postings are a type of item that contain an account, an amount, a cost, and metadata. There are some other complications, like the account can be marked virtual, the amount could be an expression, etc.
Postings are owned by transactions, always. This subclass of item_t
knows about the date, the payee, etc. If a date or metadata tag is
requested from a posting and it doesn’t have that information, the
transaction is queried to see if it can provide it.
Postings are also shared by accounts, though the actual memory is managed by the transaction. Each account knows all the postings within it, but contains relatively little information of its own.
 This is the go-to object for
querying and reporting on your data.
There is a textual parser, wholly contained in textual.cc, which knows how to parse text into journal objects, which then get “finalized” and added to the journal. Finalization is the step that enforces the double-entry guarantee.
Every journal object is “iterable”, and these iterators are defined in iterators.h and iterators.cc. This iteration logic is kept out of the basic journal objects themselves for the sake of modularity.
Another abstraction isolated to its own layer, this class encapsulating the comparison of journal objects, based on whatever value expression the user passed to --sort VEXPR.
Many reports bring pseudo-journal objects into existence, like postings
which report totals in a ‘Total’ account. These objects are
created and managed by a temporaries_t
object, which gets used in
many places by the reporting filters.
There is an option handling subsystem used by many of the layers further down. It makes it relatively easy for me to add new options, and to have those option settings immediately accessible to value expressions.
Every journal object is owned by a session, with the session providing support for that object. In GUI terms, this is the Controller object for the journal Data object, where every document window would be a separate session. They are all owned by the global scope.
Every time you create any report output, a report object is created to determine what you want to see. In the Ledger REPL, a new report object is created every time a command is executed. In CLI mode, only one report object ever comes into being, as Ledger immediately exits after displaying the results.
The way Ledger generates data is this: it asks the session for the current journal, and then creates an iterator applied to that journal. The kind of iterator depends on the type of report.
This iterator is then walked, and every object yielded from the iterator is passed to an “item handler”, whose type is directly related to the type of the iterator.
There are many, many item handlers, which can be chained together. Each one receives an item (post, account, xact, etc.), performs some action on it, and then passes it down to the next handler in the chain. There are filters which compute the running totals; that queue and sort all the input items before playing them back out in a new order; that filter out items which fail to match a predicate, etc. Almost every reporting feature in Ledger is related to one or more filters. Looking at filters.h, there are over 25 of them defined currently.
How filters get wired up, and in what order, is a complex process based on all the various options specified by the user. This is the job of the chain logic, found entirely in chain.cc. It took a really long time to get this logic exactly right, which is why I haven’t exposed this layer to the Python bridge yet.
Although filters are great and all, in the end you want to see stuff. This is the job of special “leaf” filters called output modules. They are implemented just like a regular filter, but they don’t have a “next” filter to pass the data on down to. Instead, they are the end of the line and must do something with the item that results in the user seeing something on their screen or in a file.
Select queries know a lot about everything, even though they implement their logic by implementing the user’s query in terms of all the other features thus presented. Select queries have no functionality of their own, they are simple a shorthand to provide access to much of Ledger’s functionality via a cleaner, more consistent syntax.
There is a master object which owns every other objects, and this is Ledger’s global scope. It creates the other objects, provides REPL behavior for the command-line utility, etc. In GUI terms, this is the Application object.
This creates the global scope object, performs error reporting, and handles command-line options which must precede even the creation of the global scope, such as --debug CODE.
And that’s Ledger in a nutshell. All the rest are details, such as which value expressions each journal item exposes, how many filters currently exist, which options the report and session scopes define, etc.
Next: Developer Commands, Previous: Internal Design, Up: Ledger for Developers [Contents][Index]
This chapter offers a complete description of the journal data format, suitable for implementers in other languages to follow. For users, the chapter on keeping a journal is less extensive, but more typical of common usage (see Keeping a Journal).
Data is collected in the form of transactions which occur in one or more journal files. Each transaction, in turn, is made up of one or more postings, which describe how amounts flow from one account to another. Here is an example of the simplest of journal files:
2010/05/31 Just an example Expenses:Some:Account $100.00 Income:Another:Account
In this example, there is a transaction date, a payee, or description of the transaction, and two postings. The postings show movement of one hundred dollars from an account within the Income hierarchy, to the specified expense account. The name and meaning of these accounts is arbitrary, with no preferences implied, although you will find it useful to follow standard accounting practices (see Principles of Accounting with Ledger).
Since an amount is missing from the second posting, it is assumed to be the inverse of the first. This guarantees the cardinal rule of double-entry accounting: the sum of every transaction must balance to zero, or it is in error. Whenever Ledger encounters a null posting in a transaction, it uses it to balance the remainder.
It is also typical, though not enforced, to think of the first posting as the destination, and the final as the source. Thus, the amount of the first posting is typically positive. Consider:
2010/05/31 An income transaction Assets:Checking $1,000.00 Income:Salary 2010/05/31 An expense transaction Expenses:Dining $100.00 Assets:Checking
| • Comments and meta-data: | ||
| • Specifying Amounts: | ||
| • Posting costs: | ||
| • Primary commodities: |
Next: Specifying Amounts, Previous: Journal File Format for Developers, Up: Journal File Format for Developers [Contents][Index]
Comments are generally started using a ‘;’. However, in order to increase compatibility with other text manipulation programs and methods three additional comment characters are valid if used at the beginning of a line: ‘#’, ‘|’, and ‘*’.
Next: Posting costs, Previous: Comments and meta-data, Up: Journal File Format for Developers [Contents][Index]
The heart of a journal is the amounts it records, and this fact is reflected in the diversity of amount expressions allowed. All of them are covered here, though it must be said that sometimes, there are multiple ways to achieve a desired result.
Note: It is important to note that there must be at least two spaces between the end of the account and the beginning of the amount (including a commodity designator).
| • Integer Amounts: | ||
| • Commoditized Amounts: |
Next: Commoditized Amounts, Previous: Specifying Amounts, Up: Specifying Amounts [Contents][Index]
In the simplest form, bare decimal numbers are accepted:
2010/05/31 An income transaction Assets:Checking 1000.00 Income:Salary
Such amounts may only use an optional period for a decimal point. These are referred to as integer amounts or uncommoditized amounts. In most ways they are similar to commoditized amounts, but for one significant difference: They always display in reports with full precision. More on this in a moment. For now, a word must be said about how Ledger stores numbers.
Every number parsed by Ledger is stored internally as an infinite-precision rational value. Floating-point math is never used, as it cannot be trusted to maintain precision of values. So, in the case of ‘1000.00’ above, the internal value is ‘100000/100’.
While rational numbers are great at not losing precision, the question arises: How should they be displayed? A number like ‘100000/100’ is no problem, since it represents a clean decimal fraction. But what about when the number ‘1/1’ is divided by three? How should one print ‘1/3’, an infinitely repeating decimal?
Ledger gets around this problem by rendering rationals into decimal at the last possible moment, and only for display. As such, some rounding must, at times, occur. If this rounding would affect the calculation of a running total, special accommodation postings are generated to make you aware it has happened. In practice, it happens rarely, but even then it does not reflect adjustment of the internal amount, only the displayed amount.
What has still not been answered is how Ledger rounds values. Should ‘1/3’ be printed as ‘0.33’ or ‘0.33333’? For commoditized amounts, the number of decimal places is decided by observing how each commodity is used; but in the case of integer amounts, an arbitrary factor must be chosen. Initially, this factor is six. Thus, ‘1/3’ is printed back as ‘0.333333’. Further, this rounding factor becomes associated with each particular value, and is carried through mathematical operations. For example, if that particular number were multiplied by itself, the decimal precision of the result would be twelve. Addition and subtraction do not affect precision.
Since each integer amount retains its own display precision, this is called full precision, as opposed to commoditized amounts, which always look to their commodity to know what precision they should round to, and so use commodity precision.
Previous: Integer Amounts, Up: Specifying Amounts [Contents][Index]
A commoditized amount is an integer amount which has an associated commodity. This commodity can appear before or after the amount, and may or may not be separated from it by a space. Most characters are allowed in a commodity name, except for the following:
.,;:?!
-+*/^&|=
<>[]()
{}
@
And yet, any of these may appear in a commodity name if it is surrounded by double quotes, for example:
100 "EUN+133"
If a quoted commodity is found, it is displayed in quotes as well, to avoid any confusion as to which part is the amount, and which part is the commodity.
Another feature of commoditized amounts is that they are reported back in the same form as parsed. If you specify dollar amounts using ‘$100’, they will print the same; likewise with ‘100 $’ or ‘$100.000’. You may even use decimal commas, such as ‘$100,00’, or thousand-marks, as in ‘$10,000.00’.
These display characteristics become associated with the commodity, with the result being that all amounts of the same commodity are reported consistently. Where this is most noticeable is the display precision, which is determined by the most precise value seen for a given commodity—in most cases.
Ledger makes a distinction between observed amounts and unobserved amounts. An observed amount is critiqued by Ledger to determine how amounts using that commodity should be displayed; unobserved amounts are significant in their value only—no matter how they are specified, it does not change how other amounts in that commodity will be displayed.
An example of this is found in cost expressions, covered next.
Next: Primary commodities, Previous: Specifying Amounts, Up: Journal File Format for Developers [Contents][Index]
You have seen how to specify either a commoditized or an integer amount for a posting. But what if the amount you paid for something was in one commodity, and the amount received was another? There are two main ways to express this:
2010/05/31 Farmer's Market Assets:My Larder 100 apples Assets:Checking -$20.00
In this example, you have paid twenty dollars for one hundred apples. The cost to you is twenty cents per apple, and Ledger calculates this implied cost for you. You can also make the cost explicit using a cost amount:
2010/05/31 Farmer's Market Assets:My Larder 100 apples @ $0.200000 Assets:Checking
Here the per-unit cost is given explicitly in the form of a cost amount; and since cost amounts are unobserved, the use of six decimal places has no effect on how dollar amounts are displayed in the final report. You can also specify the total cost:
2010/05/31 Farmer's Market Assets:My Larder 100 apples @@ $20 Assets:Checking
These three forms have identical meaning. In most cases the first is preferred, but the second two are necessary when more than two postings are involved:
2010/05/31 Farmer's Market Assets:My Larder 100 apples @ $0.200000 Assets:My Larder 100 pineapples @ $0.33 Assets:My Larder 100 "crab apples" @ $0.04 Assets:Checking
Here the implied cost is ‘$57.00’, which is entered into the null posting automatically so that the transaction balances.
Previous: Posting costs, Up: Journal File Format for Developers [Contents][Index]
In every transaction involving more than one commodity, there is always one which is the primary commodity. This commodity should be thought of as the exchange commodity, or the commodity used to buy and sell units of the other commodity. In the fruit examples above, dollars are the primary commodity. This is decided by Ledger based on the placement of the commodity in the transaction:
2010/05/31 Sample Transaction Expenses 100 secondary Assets -50 primary 2010/05/31 Sample Transaction Expenses 100 secondary @ 0.5 primary Assets 2010/05/31 Sample Transaction Expenses 100 secondary @@ 50 primary Assets
The only case where knowledge of primary versus secondary comes into play is in reports that use the --market (-V) or --basis (-B) options. With these, only primary commodities are shown.
If a transaction uses only one commodity, this commodity is also considered a primary. In fact, when Ledger goes about ensuring that all transactions balance to zero, it only ever asks this of primary commodities.
Next: Ledger Development Environment, Previous: Journal File Format for Developers, Up: Ledger for Developers [Contents][Index]
• echo : | ||
• reload : | ||
• source : | ||
| • Debug Options: | ||
| • Pre-Commands: |
Next: reload
, Previous: Developer Commands, Up: Developer Commands [Contents][Index]
echo
This command simply echoes its argument back to the output.
Next: source
, Previous: echo
, Up: Developer Commands [Contents][Index]
reload
Forces ledger to reload any journal files. This function exists to support external programs controlling a running ledger process and does nothing for a command-line user.
Next: Debug Options, Previous: reload
, Up: Developer Commands [Contents][Index]
source
The source
command takes a journal file as an argument and
parses it checking for errors; no other reports are generated, and no
other arguments are necessary. Ledger will return success if no errors
are found.
Next: Pre-Commands, Previous: source
, Up: Developer Commands [Contents][Index]
These options are primarily for Ledger developers, but may be of some use to a user trying something new.
Ignore init files and environment variables for the ledger run.
If Ledger has been built with debug options this will provide extra data during the run. The following are the available CODES to debug:
account.display | draft.xact | option.names |
account.sorted | expr.calc | org.next_amount |
amount.commodities | expr.compile | org.next_total |
amount.convert | expr.merged.compile | parser.error |
amount.is_zero | filters.changed_value | pool.commodities |
amount.parse | filters.changed_value.rounding | post.assign |
amount.price | filters.collapse | python.init |
amount.refs | filters.forecast | python.interp |
amount.roundto | filters.interval | query.mask |
amount.truncate | filters.revalued | report.predicate |
amount.unround | format.abbrev | scope.search |
annotate.less | format.expr | scope.symbols |
archive.journal | generate.post | select.parse |
auto.columns | generate.post.string | textual.include |
budget.generate | history.find | textual.parse |
commodity.annotated.strip | history.map | timelog |
commodity.annotations | item.meta | times.epoch |
commodity.compare | ledger.read | times.interval |
commodity.download | ledger.validate | times.parse |
commodity.exchange | lookup | value.sort |
commodity.price.find | lookup.account | value.storage.refcount |
commodity.prices.add | mask.match | xact.extend |
commodity.prices.find | memory.debug | xact.extend.cleared |
csv.mappings | op.memory | xact.extend.fail |
csv.parse | option.args | xact.finalize |
Enable tracing. The INT specifies the level of trace desired:
LOG_OFF | 0 |
LOG_CRIT | 1 |
LOG_FATAL | 2 |
LOG_ASSERT | 3 |
LOG_ERROR | 4 |
LOG_VERIFY | 5 |
LOG_WARN | 6 |
LOG_INFO | 7 |
LOG_EXCEPT | 8 |
LOG_DEBUG | 9 |
LOG_TRACE | 10 |
LOG_ALL | 11 |
Print detailed information on the execution of Ledger.
Enable additional assertions during run-time. This causes a significant slowdown. When combined with --debug CODE ledger will produce memory trace information.
Verify that every constructed object is properly destructed. This is for debugging purposes only.
Print version information and exit.
Previous: Debug Options, Up: Developer Commands [Contents][Index]
Pre-commands are useful when you aren’t sure how a command or option will work. The difference between a pre-command and a regular command is that pre-commands ignore the journal data file completely, nor is the user’s init file read.
eval VEXPR
Evaluate the given value expression against the model transaction.
format FORMAT_STRING
Print details of how ledger uses the given formatting description and apply it against a model transaction.
generate
Randomly generates syntactically valid Ledger data from a seed. Used by the ‘GenerateTests’ harness for development testing.
parse VEXPR
expr VEXPR
Print details of how ledger uses the given value expression description and apply it against a model transaction.
period PERIOD_EXPRESSION
Evaluate the given period and report how Ledger interprets it:
$ ledger period "this year" --now 2011-01-01
--- Period expression tokens --- TOK_THIS: this TOK_YEAR: year END_REACHED: <EOF> --- Before stabilization --- range: in year 2011 --- After stabilization --- range: in year 2011 start: 11-Jan-01 finish: 12-Jan-01 --- Sample dates in range (max. 20) --- 1: 11-Jan-01
query
args
Evaluate the given arguments and report how Ledger interprets it against the following model transaction:
$ ledger query "/Book/"
--- Input arguments --- ("/Book/") --- Context is first posting of the following transaction --- 2004/05/27 Book Store ; This note applies to all postings. :SecondTag: Expenses:Books 20 BOOK @ $10 ; Metadata: Some Value ; Typed:: $100 + $200 ; :ExampleTag: ; Here follows a note describing the posting. Liabilities:MasterCard $-200.00 --- Input expression --- (account =~ /Book/) --- Text as parsed --- (account =~ /Book/) --- Expression tree --- 0x7fd639c0da40 O_MATCH (1) 0x7fd639c10170 IDENT: account (1) 0x7fd639c10780 VALUE: /Book/ (1) --- Compiled tree --- 0x7fd639c10520 O_MATCH (1) 0x7fd639c0d6c0 IDENT: account (1) 0x7fd639c0d680 FUNCTION (1) 0x7fd639c10780 VALUE: /Book/ (1) --- Calculated value --- true
script
UNDOCUMENTED! Please help by contributing documentation for this feature.
template
Shows the insertion template that the xact
sub-command
generates. This is a debugging command.
Previous: Developer Commands, Up: Ledger for Developers [Contents][Index]
| • acprep build configuration tool: | ||
| • Testing Framework: |
Next: Testing Framework, Previous: Ledger Development Environment, Up: Ledger Development Environment [Contents][Index]
Previous: acprep build configuration tool, Up: Ledger Development Environment [Contents][Index]
Ledger source ships with a fairly complete set of tests to verify that
all is well, and no old errors have resurfaced. Tests are run
individually with ctest. All tests can be run using make
check
or ninja check
depending on which build tool you prefer.
Once built, the ledger executable resides under the build subdirectory in the source tree. Tests are built and stored in the test subdirectory for the build. For example, ~/ledger/build/ledger/opt/test.
| • Running Tests: | ||
| • Writing Tests: |
Next: Writing Tests, Previous: Testing Framework, Up: Testing Framework [Contents][Index]
The complete test suite can be run from the build directory using the
check option for the build tool you use. For example, make
check
. The entire test suit lasts around a minute for the optimized
built and many times longer for the debug version. While developing
and debugging, running individual tests can save a great deal of time.
Individual tests can be run from the test subdirectory of the
build location. To execute a single test use ctest -V -R regex
,
where the regex matches the name of the test you want to build.
There are nearly 300 tests stored under the test subdirectory
in the main source distribution. They are broken into two broad
categories, baseline and regression. To run the 5FBF2ED8 test,
for example, issue ctest -V -R "5FB"
.
Previous: Running Tests, Up: Testing Framework [Contents][Index]
To write a new test first decide to which broad category the test belongs:
baseline or regression. Depending on the category tests are named differently
baseline tests are prefixed with their type, e.g. ‘cmd’
(see Baseline Test Types for valid types), whereas regressions are either
named after the bug id, e.g. ‘1234.test’ or uuid ‘91416D62.test’.
In case several test files belong to the same bug number the files by appending
_X
where ‘X’ is the number of the test, e.g. ‘1234_1.test’,
‘1234_2.test’.
cmd
Ledger commands like register
or balance
dir
Ledger directives like account
or alias
feat
Ledger features such as balance assertions in journal file
opt
Ledger options such as --period or --format
A ledger test file contains three sections:
Ledger has a special command directive for tests, everything between
test
and end test
is treated like a comment, so every
Ledger test is automatically a valid Ledger file.
The test scripts take the remainder of the test
line and use
it as command-line arguments for ledger, the text enclosed in test
and end test
is expected output, for example:
; This is the journal data year 2014 12/24 (C0d3) Santa Claus Assets:Bank ¤ -150,00 Expenses:Presents ; The following line specifies the ledger command-line options for this test and ; everything between the next line and `end test` specifies the expected output test reg --payee=code 14-Dec-24 C0d3 Assets:Bank ¤ -150,00 ¤ -150,00 14-Dec-24 C0d3 Expenses:Presents ¤ 150,00 0 end test
When it is necessary to test for errors printed to stderr
redirect
the test output by adding ->
to the test
line and match the
expected error text in an __ERROR__
section:
2014/01/01 * Acme Corporation Assets:Bank:Checking ¤ 1.000,00 [Fund:Vacation] ¤ 300,00 [Fund:Studies] ¤ 600,00 Income:Salary ¤ -2.000,00 test reg -> __ERROR__ While parsing file "$FILE", line 5: While balancing transaction from "$FILE", lines 1-5: > 2014/01/01 * Acme Corporation > Assets:Bank:Checking ¤ 1.000,00 > [Fund:Vacation] ¤ 300,00 > [Fund:Studies] ¤ 600,00 > Income:Salary ¤ -2.000,00 Unbalanced remainder is: ¤ -100,00 Amount to balance against: ¤ 1.900,00 Error: Transaction does not balance end test
A special $FILE
variable can be used to match the journal filename
used during the test.
To add new tests to the test suite use the rebuild_cache option for the
build tool you use, for example make rebuild_cache
, now the
new tests can be run as documented in Running Tests.
Next: Example Journal File, Previous: Ledger for Developers, Up: Top [Contents][Index]
The following have been removed from Ledger 3.0:
bal
in 3.0 does what ‘-s
bal’ did in 2.x. To see 2.6 behavior, use --collapse (-n)
option in 3.0, like ‘bal -n’. The --subtotal (-s) option
no longer has any effect on balance reports.
The following are deprecated in Ledger 3.0:
LEDGER
is now LEDGER_FILE
,
LEDGER_INIT
is now LEDGER_INIT_FILE
,
PRICE_HIST
is now LEDGER_PRICE_DB
,
PRICE_EXP
is now LEDGER_PRICE_EXP
.
Next: Miscellaneous Notes, Previous: Major Changes from version 2.6, Up: Top [Contents][Index]
The following journal file is included with the source distribution of ledger. It is called drewr3.dat and exhibits many ledger features, include automatic and virtual transactions,
; -*- ledger -*- = /^Income/ (Liabilities:Tithe) 0.12 ;~ Monthly ; Assets:Checking $500.00 ; Income:Salary ;~ Monthly ; Expenses:Food $100 ; Assets 2010/12/01 * Checking balance Assets:Checking $1,000.00 Equity:Opening Balances 2010/12/20 * Organic Co-op Expenses:Food:Groceries $ 37.50 ; [=2011/01/01] Expenses:Food:Groceries $ 37.50 ; [=2011/02/01] Expenses:Food:Groceries $ 37.50 ; [=2011/03/01] Expenses:Food:Groceries $ 37.50 ; [=2011/04/01] Expenses:Food:Groceries $ 37.50 ; [=2011/05/01] Expenses:Food:Groceries $ 37.50 ; [=2011/06/01] Assets:Checking $ -225.00 2010/12/28=2011/01/01 Acme Mortgage Liabilities:Mortgage:Principal $ 200.00 Expenses:Interest:Mortgage $ 500.00 Expenses:Escrow $ 300.00 Assets:Checking $ -1000.00 2011/01/02 Grocery Store Expenses:Food:Groceries $ 65.00 Assets:Checking 2011/01/05 Employer Assets:Checking $ 2000.00 Income:Salary 2011/01/14 Bank ; Regular monthly savings transfer Assets:Savings $ 300.00 Assets:Checking 2011/01/19 Grocery Store Expenses:Food:Groceries $ 44.00 ; hastag: not block Assets:Checking 2011/01/25 Bank ; Transfer to cover car purchase Assets:Checking $ 5,500.00 Assets:Savings ; :nobudget: apply tag hastag: true apply tag nestedtag: true 2011/01/25 Tom's Used Cars Expenses:Auto $ 5,500.00 ; :nobudget: Assets:Checking 2011/01/27 Book Store Expenses:Books $20.00 Liabilities:MasterCard end tag 2011/12/01 Sale Assets:Checking:Business $ 30.00 Income:Sales end tag