diff options
176 files changed, 3478 insertions, 6715 deletions
diff --git a/.dir-locals.el b/.dir-locals.el index 4f6af924..edafaded 100644 --- a/.dir-locals.el +++ b/.dir-locals.el @@ -1,6 +1,5 @@ ((nil . ((tab-width . 2) (sentence-end-double-space . t) - (fill-column . 8) (bug-reference-url-format . "http://bugs.ledger-cli.org/show_bug.cgi?id=%s"))) (c-mode . ((c-file-style . "ledger") @@ -107,3 +107,14 @@ contrib/non-profit-audit-reports/tests/general-ledger.txt contrib/non-profit-audit-reports/tests/MANIFEST contrib/non-profit-audit-reports/general-ledger.zip /wiki/ +doc/ledger-mode.info +doc/ledger3.info-1 +doc/ledger3.info-2 +CTestTestfile.cmake +.ninja_deps +.ninja_log +build.ninja +rules.ninja +Testing/Temporary +/MathTests +/UtilTests diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..eed18531 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,14 @@ +language: cpp +compiler: + - clang + - gcc +install: "./acprep dependencies" +before_script: "./acprep opt make --python" +script: + - "./acprep check -- --output-on-failure" + - "PYTHONPATH=. python python/demo.py" +notifications: + email: + on_success: change + on_failure: change + irc: "chat.freenode.net#ledger" diff --git a/CMakeLists.txt b/CMakeLists.txt index fc2ef2bb..c60cdce2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,8 +4,8 @@ PROJECT(ledger) set(Ledger_VERSION_MAJOR 3) set(Ledger_VERSION_MINOR 0) -set(Ledger_VERSION_PATCH 0) -set(Ledger_VERSION_DATE 20130529) +set(Ledger_VERSION_PATCH 1) +set(Ledger_VERSION_DATE 20140327) enable_testing() @@ -46,6 +46,10 @@ endif() find_package(PythonInterp) # Used for running tests if(USE_PYTHON) + if(NOT BUILD_LIBRARY) + message(ERROR "Building the python module requires BUILD_LIBRARY=ON.") + endif() + set(Python_ADDITIONAL_VERSIONS 2.7 2.6) find_package(PythonLibs) if(PYTHONLIBS_FOUND) @@ -232,9 +236,6 @@ find_opt_library_and_header(EDIT_PATH histedit.h EDIT_LIB edit HAVE_EDIT) ######################################################################## macro(add_ledger_library_dependencies _target) - if(BUILD_LIBRARY) - target_link_libraries(${_target} libledger) - endif() target_link_libraries(${_target} ${MPFR_LIB}) target_link_libraries(${_target} ${GMP_LIB}) if(HAVE_EDIT) @@ -11,22 +11,10 @@ almost certainly going to run into problems. In future, you can run 'acprep update' again and again, and it will keep you updated to the very latest version. -I further recommend building both debug and optimized versions of Ledger, in a -subdirectory of your source tree named 'build' (which acprep will manage for -you, you simply need to create it): +Now install it: - $ mkdir build - $ ./acprep opt make - $ ./acprep debug make - -Now install the optimized version: - - $ cd build/ledger/opt $ sudo make install -but know that you have 'build/ledger/debug' available for testing and -for more useful bug reports. - =============================================================================== COMMON CONFIGURE/BUILD PROBLEMS =============================================================================== @@ -66,19 +54,12 @@ it's usually fairly obvious where things have gone astray. GNU/Linux system (or Debian-based system such as Ubuntu), something like this should work (as root): - # aptitude update - # for name in \ - cmake libboost-dev libboost-date-time-dev libboost-doc \ - libboost-dbg libboost-filesystem-dev libboost-graph-dev \ - libboost-iostreams-dev libboost-program-options-dev \ - libboost-python-dev libboost-regex-dev \ - libboost-serialization-dev libboost-signals-dev \ - libboost-test-dev libboost-thread-dev libboost-wave-dev \ - libmpfr-dev libmpfr-dbg libmpfr-doc; \ - do \ - aptitude install ${name}; \ - done - + sudo apt-get install build-essential cmake autopoint texinfo python-dev \ + zlib1g-dev libbz2-dev libgmp3-dev gettext libmpfr-dev \ + libboost-date-time-dev libboost-filesystem-dev \ + libboost-graph-dev libboost-iostreams-dev \ + libboost-python-dev libboost-regex-dev libboost-test-dev + ---------------------------------------------------------------------- - Q: Configure fails saying it can't find boost_regex @@ -1,3 +1,5 @@ +[![Build Status](https://travis-ci.org/ledger/ledger.png?branch=master)](https://travis-ci.org/ledger/ledger) + # Ledger: Command-Line Accounting Ledger is a powerful, double-entry accounting system that is accessed from the @@ -26,6 +28,13 @@ Now try your first ledger command: ./ledger -f test/input/sample.dat reg +For help on keeping your journal have a look at the +[documentation](http://www.ledger-cli.org/docs.html) and the +[wiki](http://wiki.ledger-cli.org/) (Also see the “Resources” section at the +end of this file). An emacs mode for ledger files can be found in the `lisp` +directory and a vim plugin is located in the [ledger/vim-ledger +repository](https://github.com/ledger/vim-ledger). + ## To the Rest If you're reading this file, you have in your hands the Bleeding Edge. This @@ -66,6 +75,7 @@ current `master` branch: <tr><td>Boost</td><td>1.35</td><td></td></tr> <tr><td>GMP</td><td>4.2.2</td><td></td></tr> <tr><td>MPFR</td><td>2.4.0</td><td></td></tr> +<tr><td>utfcpp</td><td>2.3.4</td><td></td></tr> <tr><td>gettext</td><td>0.17</td><td><em>optional</em></td></tr> <tr><td>libedit</td><td>20090111-3.0</td><td><em>optional</em></td></tr> <tr><td>Python</td><td>2.4</td><td><em>optional</em></td></tr> @@ -112,9 +122,9 @@ following packages (current as of Ubuntu 12.04): Or, for Ubuntu Karmic: sudo apt-get install build-essential cmake texinfo python-dev zlib1g-dev - libbz2-dev libgmp3-dev bjam gettext cvs libboost1.40-dev - libboost-regex1.40-dev libboost-date-time1.40-dev - libboost-filesystem1.40-dev libmpfr-dev + libbz2-dev libgmp3-dev bjam gettext cvs libboost-dev + libboost-regex-dev libboost-date-time-dev + libboost-filesystem-dev libmpfr-dev ### Debian @@ -125,11 +135,11 @@ Debian wheezy (7.0) contains all components needed to build ledger. You can install all required build dependencies using the following command: - sudo apt-get install build-essential cmake autopoint texinfo python-dev - zlib1g-dev libbz2-dev libgmp3-dev gettext libmpfr-dev - libboost-date-time1.49-dev libboost-filesystem1.49-dev - libboost-graph1.49-dev libboost-iostreams1.49-dev - libboost-python1.49-dev libboost-regex1.49-dev libboost-test1.49-dev + sudo apt-get install build-essential cmake autopoint texinfo python-dev \ + zlib1g-dev libbz2-dev libgmp3-dev gettext libmpfr-dev \ + libboost-date-time-dev libboost-filesystem-dev \ + libboost-graph-dev libboost-iostreams-dev \ + libboost-python-dev libboost-regex-dev libboost-test-dev ## Building @@ -140,7 +150,7 @@ footwork for you: ./acprep update # or, if you want to use the Boost libraries with suffix -mt, install in # $HOME/local and build with 2 processes in parallel - ./acprep update --boost-suffix=-mt -- --prefix=$HOME/local -j2 + ./acprep update --boost-suffix=-mt --prefix=$HOME/local -j2 Please read the contents of `config.log` if the configure step fails. Also, see the `help` subcommand to `acprep`, which explains some of its many @@ -61,13 +61,26 @@ def which(program): return None class BoostInfo(object): - def dependencies(system): - if system == 'darwin': + def dependencies(self, system): + if system == 'darwin-homebrew': + return [ 'boost' ] + + if system == 'darwin-macports': return [ 'boost-jam', 'boost', '+python27+universal' ] if system == 'centos': return [ 'boost-devel' ] + elif system == 'ubuntu-saucy' or system == 'ubuntu-precise': + return [ 'autopoint', + 'libboost-dev', + 'libboost-test-dev', + 'libboost-regex-dev', + 'libboost-date-time-dev', + 'libboost-filesystem-dev', + 'libboost-iostreams-dev', + 'libboost-python-dev' ] + elif system == 'ubuntu-lucid': return [ 'bjam', 'autopoint', 'libboost-dev', @@ -526,7 +539,16 @@ class PrepareBuild(CommandLineApp): 'libedit' ,'+universal', 'texlive-xetex', 'doxygen', 'graphviz', 'texinfo', 'lcov', 'sloccount' - ] + BoostInfo.dependencies('darwin') + ] + BoostInfo().dependencies('darwin-macports') + self.log.info('Executing: ' + ' '.join(packages)) + self.execute(*packages) + elif exists('/usr/local/bin/brew') or exists('/opt/local/bin/brew'): + self.log.info('Looks like you are using Homebrew on OS X') + packages = [ + 'brew', 'install', + 'cmake', 'ninja', + 'mpfr', 'gmp', + ] + BoostInfo().dependencies('darwin-homebrew') self.log.info('Executing: ' + ' '.join(packages)) self.execute(*packages) elif exists('/sw/bin/fink'): @@ -541,7 +563,44 @@ class PrepareBuild(CommandLineApp): release = open('/etc/lsb-release') info = release.read() release.close() - if re.search('karmic', info): + if re.search('saucy', info): + self.log.info('Looks like you are using APT on Ubuntu Saucy') + packages = [ + 'sudo', 'apt-get', 'install', + 'build-essential', + 'libtool', + 'cmake', + 'ninja-build', + 'zlib1g-dev', + 'libbz2-dev', + 'python-dev', + 'libgmp-dev', + 'libmpfr-dev', + 'gettext', + 'libedit-dev', + 'texinfo', + 'lcov', + 'sloccount' + ] + BoostInfo().dependencies('ubuntu-saucy') + elif re.search('precise', info): + self.log.info('Looks like you are using APT on Ubuntu Precise') + packages = [ + 'sudo', 'apt-get', 'install', + 'build-essential', + 'libtool', + 'cmake', + 'zlib1g-dev', + 'libbz2-dev', + 'python-dev', + 'libgmp-dev', + 'libmpfr-dev', + 'gettext', + 'libedit-dev', + 'texinfo', + 'lcov', + 'sloccount' + ] + BoostInfo().dependencies('ubuntu-precise') + elif re.search('karmic', info): self.log.info('Looks like you are using APT on Ubuntu Karmic') packages = [ 'sudo', 'apt-get', 'install', @@ -563,7 +622,7 @@ class PrepareBuild(CommandLineApp): 'texinfo', 'lcov', 'sloccount' - ] + BoostInfo.dependencies('ubuntu-karmic') + ] + BoostInfo().dependencies('ubuntu-karmic') elif re.search('hardy', info): self.log.info('Looks like you are using APT on Ubuntu Hardy') packages = [ @@ -901,7 +960,7 @@ class PrepareBuild(CommandLineApp): os.chdir(self.source_dir) def phase_check(self, *args): - self.log.info('Executing phase: update') + self.log.info('Executing phase: check') build_dir = self.ensure(self.build_directory()) try: self.log.debug('Changing directory to ' + build_dir) diff --git a/contrib/vim/README b/contrib/vim/README deleted file mode 100644 index a3f5a877..00000000 --- a/contrib/vim/README +++ /dev/null @@ -1,89 +0,0 @@ - -This is the ledger filetype for vim. -Copy each file to the corresponding directory in your ~/.vim directory. -Then include the following line in your .vimrc or in ~/.vim/filetype.vim - au BufNewFile,BufRead *.ldg,*.ledger setf ledger | comp ledger -You can also use a modeline like this in every ledger file - vim:filetype=ledger - -Tips and useful commands -====================================================================== - • Try account-completion (as explained below) - • :call LedgerSetDate(line('.'), 'effective') - will set today's date as the effective date of the current - transaction. You can use also 'actual' in place of 'effective' - or pass in a different date measured as seconds since 1st Jan 1970. - • :call LedgerSetTransactionState(line('.'), '*') - sets the state of the current transaction to '*'. You can - use this in custom mappings. - • :call LedgerToggleTransactionState(line('.'), ' *?!') - will toggle through the provided transaction states. - You can map this to double-clicking for example: - noremap <silent><buffer> <2-LeftMouse> - \ :call LedgerToggleTransactionState(line('.'), ' *?!')<CR> - -Configuration -====================================================================== -Include the following let-statements somewhere in your .vimrc -to modify the behaviour of the ledger filetype. - -* Number of colums that will be used to display the foldtext. - Set this when you think that the amount is too far off to the right. - let g:ledger_maxwidth = 80 - -* String that will be used to fill the space between account name - and amount in the foldtext. Set this to get some kind of lines - or visual aid. - let g:ledger_fillstring = ' -' - My special tip is to use so-called digraphs: - Press <C-K> followed by the two-characters key sequence below. - (in insert-mode) - '. = ˙ or ': = ¨ --> ˙˙˙˙˙˙ or ¨¨¨¨¨¨ - ', = ¸ --> ¸¸¸¸¸¸ - .M = · --> ······ - >> = » --> »»»»»» - All those look rather unobstrusive - and provide a good visual aid to find the correct amount. - -* If you want the account completion to be sorted by level of detail/depth - instead of alphabetical, include the following line: - let g:ledger_detailed_first = 1 - -Completion -====================================================================== -Omni completion is currently implemented for account names only. - -Accounts ----------------------------------------------------------------------- -Account names are matched by the start of every sub-level. -When you insert an account name like this: - Asse<C-X><C-O> -You will get a list of top-level accounts that start like this. - -Go ahead and try something like: - As:Ban:Che<C-X><C-O> -When you have an account like this, 'Assets:Bank:Checking' should show up. - -When you want to complete on a virtual transaction, -it's currently best to keep the cursor in front of the closing bracket. -Of course you can insert the closing bracket after calling the completion, too. - -License -====================================================================== -Copyright 2011-2009 by Johann Klähn -Copyright 2009 by Stefan Karrmann -Copyright 2005 by Wolfgang Oertl - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>. - diff --git a/contrib/vim/compiler/ledger.vim b/contrib/vim/compiler/ledger.vim deleted file mode 100644 index e9e98a8e..00000000 --- a/contrib/vim/compiler/ledger.vim +++ /dev/null @@ -1,28 +0,0 @@ -" Vim Compiler File -" Compiler: ledger -" by Johann Klähn; Use according to the terms of the GPL>=2. -" vim:ts=2:sw=2:sts=2:foldmethod=marker - -if exists("current_compiler") - finish -endif -let current_compiler = "ledger" - -if exists(":CompilerSet") != 2 - command -nargs=* CompilerSet setlocal <args> -endif - -" default value will be set in ftplugin -if ! exists("g:ledger_bin") || empty(g:ledger_bin) || ! executable(split(g:ledger_bin, '\s')[0]) - finish -endif - -" %-G throws away blank lines, everything else is assumed to be part of a -" multi-line error message. -CompilerSet errorformat=%-G,%EWhile\ parsing\ file\ \"%f\"\\,\ line\ %l:%.%#,%ZError:\ %m,%C%.%# -CompilerSet errorformat+=%tarning:\ \"%f\"\\,\ line\ %l:\ %m - -" unfortunately there is no 'check file' command, -" so we will just use a query that returns no results. ever. -exe 'CompilerSet makeprg='.substitute(g:ledger_bin, ' ', '\\ ', 'g').'\ -f\ %\ reg\ not\ ''.*''\ \>\ /dev/null' - diff --git a/contrib/vim/ftplugin/ledger.vim b/contrib/vim/ftplugin/ledger.vim deleted file mode 100644 index 0067f9f8..00000000 --- a/contrib/vim/ftplugin/ledger.vim +++ /dev/null @@ -1,639 +0,0 @@ -" Vim filetype plugin file -" filetype: ledger -" by Johann Klähn; Use according to the terms of the GPL>=2. -" vim:ts=2:sw=2:sts=2:foldmethod=marker - -if exists("b:did_ftplugin") - finish -endif - -let b:did_ftplugin = 1 - -let b:undo_ftplugin = "setlocal ". - \ "foldmethod< foldtext< ". - \ "include< comments< commentstring< omnifunc< formatprg<" - -" don't fill fold lines --> cleaner look -setl fillchars="fold: " -setl foldtext=LedgerFoldText() -setl foldmethod=syntax -setl include=^!include -setl comments=b:; -setl commentstring=;%s -setl omnifunc=LedgerComplete - -" set location of ledger binary for checking and auto-formatting -if ! exists("g:ledger_bin") || empty(g:ledger_bin) || ! executable(split(g:ledger_bin, '\s')[0]) - if executable('ledger') - let g:ledger_bin = 'ledger' - else - unlet g:ledger_bin - echoerr "ledger command not found. Set g:ledger_bin or extend $PATH ". - \ "to enable error checking and auto-formatting." - endif -endif - -if exists("g:ledger_bin") - exe 'setl formatprg='.substitute(g:ledger_bin, ' ', '\\ ', 'g').'\ -f\ -\ print' -endif - -" You can set a maximal number of columns the fold text (excluding amount) -" will use by overriding g:ledger_maxwidth in your .vimrc. -" When maxwidth is zero, the amount will be displayed at the far right side -" of the screen. -if !exists('g:ledger_maxwidth') - let g:ledger_maxwidth = 0 -endif - -if !exists('g:ledger_fillstring') - let g:ledger_fillstring = ' ' -endif - -" If enabled this will list the most detailed matches at the top {{{ -" of the completion list. -" For example when you have some accounts like this: -" A:Ba:Bu -" A:Bu:Bu -" and you complete on A:B:B normal behaviour may be the following -" A:B:B -" A:Bu:Bu -" A:Bu -" A:Ba:Bu -" A:Ba -" A -" with this option turned on it will be -" A:B:B -" A:Bu:Bu -" A:Ba:Bu -" A:Bu -" A:Ba -" A -" }}} -if !exists('g:ledger_detailed_first') - let g:ledger_detailed_first = 1 -endif - -" only display exact matches (no parent accounts etc.) -if !exists('g:ledger_exact_only') - let g:ledger_exact_only = 0 -endif - -" display original text / account name as completion -if !exists('g:ledger_include_original') - let g:ledger_include_original = 0 -endif - -let s:rx_amount = '\('. - \ '\%([0-9]\+\)'. - \ '\%([,.][0-9]\+\)*'. - \ '\|'. - \ '[,.][0-9]\+'. - \ '\)'. - \ '\s*\%([[:alpha:]¢$€£]\+\s*\)\?'. - \ '\%(\s*;.*\)\?$' - -function! LedgerFoldText() "{{{1 - " find amount - let amount = "" - let lnum = v:foldstart - while lnum <= v:foldend - let line = getline(lnum) - - " Skip metadata/leading comment - if line !~ '^\%(\s\+;\|\d\)' - " No comment, look for amount... - let groups = matchlist(line, s:rx_amount) - if ! empty(groups) - let amount = groups[1] - break - endif - endif - let lnum += 1 - endwhile - - let fmt = '%s %s ' - " strip whitespace at beginning and end of line - let foldtext = substitute(getline(v:foldstart), - \ '\(^\s\+\|\s\+$\)', '', 'g') - - " number of columns foldtext can use - let columns = s:get_columns() - if g:ledger_maxwidth - let columns = min([columns, g:ledger_maxwidth]) - endif - let columns -= s:multibyte_strlen(printf(fmt, '', amount)) - - " add spaces so the text is always long enough when we strip it - " to a certain width (fake table) - if strlen(g:ledger_fillstring) - " add extra spaces so fillstring aligns - let filen = s:multibyte_strlen(g:ledger_fillstring) - let folen = s:multibyte_strlen(foldtext) - let foldtext .= repeat(' ', filen - (folen%filen)) - - let foldtext .= repeat(g:ledger_fillstring, - \ s:get_columns()/filen) - else - let foldtext .= repeat(' ', s:get_columns()) - endif - - " we don't use slices[:5], because that messes up multibyte characters - let foldtext = substitute(foldtext, '.\{'.columns.'}\zs.*$', '', '') - - return printf(fmt, foldtext, amount) -endfunction "}}} - -function! LedgerComplete(findstart, base) "{{{1 - if a:findstart - let lnum = line('.') - let line = getline('.') - let b:compl_context = '' - if line =~ '^\s\+[^[:blank:];]' "{{{2 (account) - " only allow completion when in or at end of account name - if matchend(line, '^\s\+\%(\S \S\|\S\)\+') >= col('.') - 1 - " the start of the first non-blank character - " (excluding virtual-transaction and 'cleared' marks) - " is the beginning of the account name - let b:compl_context = 'account' - return matchend(line, '^\s\+[*!]\?\s*[\[(]\?') - endif - elseif line =~ '^\d' "{{{2 (description) - let pre = matchend(line, '^\d\S\+\%(([^)]*)\|[*?!]\|\s\)\+') - if pre < col('.') - 1 - let b:compl_context = 'description' - return pre - endif - elseif line =~ '^$' "{{{2 (new line) - let b:compl_context = 'new' - endif "}}} - return -1 - else - if ! exists('b:compl_cache') - let b:compl_cache = s:collect_completion_data() - let b:compl_cache['#'] = changenr() - endif - let update_cache = 0 - - let results = [] - if b:compl_context == 'account' "{{{2 (account) - let hierarchy = split(a:base, ':') - if a:base =~ ':$' - call add(hierarchy, '') - endif - - let results = LedgerFindInTree(b:compl_cache.accounts, hierarchy) - let exacts = filter(copy(results), 'v:val[1]') - - if len(exacts) < 1 - " update cache if we have no exact matches - let update_cache = 1 - endif - - if g:ledger_exact_only - let results = exacts - endif - - call map(results, 'v:val[0]') - - if g:ledger_detailed_first - let results = reverse(sort(results, 's:sort_accounts_by_depth')) - else - let results = sort(results) - endif - elseif b:compl_context == 'description' "{{{2 (description) - let results = s:filter_items(b:compl_cache.descriptions, a:base) - - if len(results) < 1 - let update_cache = 1 - endif - elseif b:compl_context == 'new' "{{{2 (new line) - return [strftime('%Y/%m/%d')] - endif "}}} - - - if g:ledger_include_original - call insert(results, a:base) - endif - - " no completion (apart from a:base) found. update cache if file has changed - if update_cache && b:compl_cache['#'] != changenr() - unlet b:compl_cache - return LedgerComplete(a:findstart, a:base) - else - unlet! b:compl_context - return results - endif - endif -endf "}}} - -function! LedgerFindInTree(tree, levels) "{{{1 - if empty(a:levels) - return [] - endif - let results = [] - let currentlvl = a:levels[0] - let nextlvls = a:levels[1:] - let branches = s:filter_items(keys(a:tree), currentlvl) - let exact = empty(nextlvls) - for branch in branches - call add(results, [branch, exact]) - if ! empty(nextlvls) - for [result, exact] in LedgerFindInTree(a:tree[branch], nextlvls) - call add(results, [branch.':'.result, exact]) - endfor - endif - endfor - return results -endf "}}} - -function! LedgerToggleTransactionState(lnum, ...) - if a:0 == 1 - let chars = a:1 - else - let chars = ' *' - endif - let trans = s:transaction.from_lnum(a:lnum) - if empty(trans) || has_key(trans, 'expr') - return - endif - - let old = has_key(trans, 'state') ? trans['state'] : ' ' - let i = stridx(chars, old) + 1 - let new = chars[i >= len(chars) ? 0 : i] - - call trans.set_state(new) - - call setline(trans['head'], trans.format_head()) -endf - -function! LedgerSetTransactionState(lnum, char) "{{{1 - " modifies or sets the state of the transaction at the cursor, - " removing the state alltogether if a:char is empty - let trans = s:transaction.from_lnum(a:lnum) - if empty(trans) || has_key(trans, 'expr') - return - endif - - call trans.set_state(a:char) - - call setline(trans['head'], trans.format_head()) -endf "}}} - -function! LedgerSetDate(lnum, type, ...) "{{{1 - let time = a:0 == 1 ? a:1 : localtime() - let trans = s:transaction.from_lnum(a:lnum) - if empty(trans) || has_key(trans, 'expr') - return - endif - - let formatted = strftime('%Y/%m/%d', time) - if has_key(trans, 'date') && ! empty(trans['date']) - let date = split(trans['date'], '=') - else - let date = [formatted] - endif - - if a:type ==? 'actual' - let date[0] = formatted - elseif a:type ==? 'effective' - if time < 0 - " remove effective date - let date = [date[0]] - else - " set effective date - if len(date) >= 2 - let date[1] = formatted - else - call add(date, formatted) - endif - endif - endif - - let trans['date'] = join(date, '=') - - call setline(trans['head'], trans.format_head()) -endf "}}} - -function! s:collect_completion_data() "{{{1 - let transactions = s:get_transactions() - let cache = {'descriptions': [], 'tags': {}, 'accounts': {}} - let accounts = [] - for xact in transactions - " collect descriptions - if has_key(xact, 'description') && index(cache.descriptions, xact['description']) < 0 - call add(cache.descriptions, xact['description']) - endif - let [t, postings] = xact.parse_body() - let tagdicts = [t] - - " collect account names - for posting in postings - if has_key(posting, 'tags') - call add(tagdicts, posting.tags) - endif - " remove virtual-transaction-marks - let name = substitute(posting.account, '\%(^\s*[\[(]\?\|[\])]\?\s*$\)', '', 'g') - if index(accounts, name) < 0 - call add(accounts, name) - endif - endfor - - " collect tags - for tags in tagdicts | for [tag, val] in items(tags) - let values = get(cache.tags, tag, []) - if index(values, val) < 0 - call add(values, val) - endif - let cache.tags[tag] = values - endfor | endfor - endfor - - for account in accounts - let last = cache.accounts - for part in split(account, ':') - let last[part] = get(last, part, {}) - let last = last[part] - endfor - endfor - - return cache -endf "}}} - -let s:transaction = {} "{{{1 -function! s:transaction.new() dict - return copy(s:transaction) -endf - -function! s:transaction.from_lnum(lnum) dict "{{{2 - let [head, tail] = s:get_transaction_extents(a:lnum) - if ! head - return {} - endif - - let trans = copy(s:transaction) - let trans['head'] = head - let trans['tail'] = tail - - " split off eventual comments at the end of line - let line = split(getline(head), '\ze\s*\%(\t\| \);', 1) - if len(line) > 1 - let trans['appendix'] = join(line[1:], '') - endif - - " parse rest of line - " FIXME (minor): will not preserve spacing (see 'join(parts)') - let parts = split(line[0], '\s\+') - if parts[0] ==# '~' - let trans['expr'] = join(parts[1:]) - return trans - elseif parts[0] ==# '=' - let trans['auto'] = join(parts[1:]) - return trans - elseif parts[0] !~ '^\d' - " this case is avoided in s:get_transaction_extents(), - " but we'll check anyway. - return {} - endif - - for part in parts - if ! has_key(trans, 'date') && part =~ '^\d' - let trans['date'] = part - elseif ! has_key(trans, 'code') && part =~ '^([^)]*)$' - let trans['code'] = part[1:-2] - elseif ! has_key(trans, 'state') && part =~ '^[[:punct:]]$' - " the first character by itself is assumed to be the state of the transaction. - let trans['state'] = part - else - " everything after date/code or state belongs to the description - break - endif - call remove(parts, 0) - endfor - - let trans['description'] = join(parts) - return trans -endf "}}} - -function! s:transaction.set_state(char) dict "{{{2 - if has_key(self, 'state') && a:char =~ '^\s*$' - call remove(self, 'state') - else - let self['state'] = a:char - endif -endf "}}} - -function! s:transaction.parse_body(...) dict "{{{2 - if a:0 == 2 - let head = a:1 - let tail = a:2 - elseif a:0 == 0 - let head = self['head'] - let tail = self['tail'] - else - throw "wrong number of arguments for parse_body()" - return [] - endif - - if ! head || tail <= head - return [] - endif - - let lnum = head - let tags = {} - let postings = [] - while lnum <= tail - let line = split(getline(lnum), '\s*\%(\t\| \);', 1) - - if line[0] =~ '^\s\+[^[:blank:];]' - " posting - let [state, rest] = matchlist(line[0], '^\s\+\([*!]\?\)\s*\(.*\)$')[1:2] - if rest =~ '\t\| ' - let [account, amount] = matchlist(rest, '^\(.\{-}\)\%(\t\| \)\s*\(.\{-}\)\s*$')[1:2] - else - let amount = '' - let account = matchstr(rest, '^\s*\zs.\{-}\ze\s*$') - endif - call add(postings, {'account': account, 'amount': amount, 'state': state}) - end - - " where are tags to be stored? - if empty(postings) - " they belong to the transaction - let tag_container = tags - else - " they belong to last posting - if ! has_key(postings[-1], 'tags') - let postings[-1]['tags'] = {} - endif - let tag_container = postings[-1]['tags'] - endif - - let comment = join(line[1:], ' ;') - if comment =~ '^\s*:' - " tags without values - for t in s:findall(comment, ':\zs[^:[:blank:]]\([^:]*[^:[:blank:]]\)\?\ze:') - let tag_container[t] = '' - endfor - elseif comment =~ '^\s*[^:[:blank:]][^:]\+:' - " tag with value - let key = matchstr(comment, '^\s*\zs[^:]\+\ze:') - if ! empty(key) - let val = matchstr(comment, ':\s*\zs.*\ze\s*$') - let tag_container[key] = val - endif - endif - let lnum += 1 - endw - return [tags, postings] -endf "}}} - -function! s:transaction.format_head() dict "{{{2 - if has_key(self, 'expr') - return '~ '.self['expr'] - elseif has_key(self, 'auto') - return '= '.self['auto'] - endif - - let parts = [] - if has_key(self, 'date') | call add(parts, self['date']) | endif - if has_key(self, 'code') | call add(parts, '('.self['code'].')') | endif - if has_key(self, 'state') | call add(parts, self['state']) | endif - if has_key(self, 'description') | call add(parts, self['description']) | endif - - let line = join(parts) - if has_key(self, 'appendix') | let line .= self['appendix'] | endif - - return line -endf "}}} -"}}} - -" Helper functions {{{1 - -function! s:get_transactions(...) "{{{2 - if a:0 == 2 - let lnum = a:1 - let end = a:2 - elseif a:0 == 0 - let lnum = 1 - let end = line('$') - else - throw "wrong number of arguments for get_transactions()" - return [] - endif - - " safe view / position - let view = winsaveview() - let fe = &foldenable - set nofoldenable - - let transactions = [] - call cursor(lnum, 0) - while lnum && lnum <= end - let trans = s:transaction.from_lnum(lnum) - if ! empty(trans) - call add(transactions, trans) - call cursor(trans['tail'], 0) - endif - let lnum = search('^[~=[:digit:]]', 'cW') - endw - - " restore view / position - let &foldenable = fe - call winrestview(view) - - return transactions -endf "}}} - -function! s:get_transaction_extents(lnum) "{{{2 - if ! (indent(a:lnum) || getline(a:lnum) =~ '^[~=[:digit:]]') - " only do something if lnum is in a transaction - return [0, 0] - endif - - " safe view / position - let view = winsaveview() - let fe = &foldenable - set nofoldenable - - call cursor(a:lnum, 0) - let head = search('^[~=[:digit:]]', 'bcnW') - let tail = search('^[^;[:blank:]]\S\+', 'nW') - let tail = tail > head ? tail - 1 : line('$') - - " restore view / position - let &foldenable = fe - call winrestview(view) - - return head ? [head, tail] : [0, 0] -endf "}}} - -function! s:findall(text, rx) " {{{2 - " returns all the matches in a string, - " there will be overlapping matches according to :help match() - let matches = [] - - while 1 - let m = matchstr(a:text, a:rx, 0, len(matches)+1) - if empty(m) - break - endif - - call add(matches, m) - endw - - return matches -endf "}}} - -" return length of string with fix for multibyte characters -function! s:multibyte_strlen(text) "{{{2 - return strlen(substitute(a:text, ".", "x", "g")) -endfunction "}}} - -" get # of visible/usable columns in current window -function! s:get_columns() " {{{2 - " As long as vim doesn't provide a command natively, - " we have to compute the available columns. - " see :help todo.txt -> /Add argument to winwidth()/ - - let columns = (winwidth(0) == 0 ? 80 : winwidth(0)) - &foldcolumn - if &number - " line('w$') is the line number of the last line - let columns -= max([len(line('w$'))+1, &numberwidth]) - endif - - " are there any signs/is the sign column displayed? - redir => signs - silent execute 'sign place buffer='.string(bufnr("%")) - redir END - if signs =~# 'id=' - let columns -= 2 - endif - - return columns -endf "}}} - -" remove spaces at start and end of string -function! s:strip_spaces(text) "{{{2 - return matchstr(a:text, '^\s*\zs\S\%(.*\S\)\?\ze\s*$') -endf "}}} - -" return only those items that start with a specified keyword -function! s:filter_items(list, keyword) "{{{2 - return filter(copy(a:list), 'v:val =~ ''^\V'.substitute(a:keyword, '\\', '\\\\', 'g').'''') -endf "}}} - -" return all lines matching an expression, returning only the matched part -function! s:grep_buffer(expression) "{{{2 - let lines = map(getline(1, '$'), 'matchstr(v:val, '''.a:expression.''')') - return filter(lines, 'v:val != ""') -endf "}}} - -function! s:sort_accounts_by_depth(name1, name2) "{{{2 - let depth1 = s:count_expression(a:name1, ':') - let depth2 = s:count_expression(a:name2, ':') - return depth1 == depth2 ? 0 : depth1 > depth2 ? 1 : -1 -endf "}}} - -function! s:count_expression(text, expression) "{{{2 - return len(split(a:text, a:expression, 1))-1 -endf "}}} diff --git a/contrib/vim/indent/ledger.vim b/contrib/vim/indent/ledger.vim deleted file mode 100644 index ce5d508d..00000000 --- a/contrib/vim/indent/ledger.vim +++ /dev/null @@ -1,46 +0,0 @@ -" Vim filetype indent file -" filetype: ledger -" by Johann Klähn; Use according to the terms of the GPL>=2. -" vim:ts=2:sw=2:sts=2:foldmethod=marker - -if exists("b:did_indent") - finish -endif -let b:did_indent = 1 - -setl autoindent -setl indentexpr=GetLedgerIndent() - -if exists("*GetLedgerIndent") - finish -endif - -function GetLedgerIndent(...) - " You can pass in a line number when calling this function manually. - let lnum = a:0 > 0 ? a:1 : v:lnum - " If this line is empty look at (the indentation of) the last line. - " Note that inside of a transaction no blank lines are allowed. - let line = getline(lnum) - let prev = getline(lnum - 1) - - if line =~ '^\s\+\S' - " Lines that already are indented (→postings, sub-directives) keep their indentation. - return &sw - elseif line =~ '^\s*$' - " Current line is empty, try to guess its type based on the previous line. - if prev =~ '^\([[:digit:]~=]\|\s\+\S\)' - " This is very likely a posting or a sub-directive. - " While lines following the start of a transaction are automatically - " indented you will have to indent the first line following a - " pre-declaration manually. This makes it easier to type long lists of - " 'account' pre-declarations without sub-directives, for example. - return &sw - else - return 0 - endif - else - " Everything else is not indented: - " start of transactions, pre-declarations, apply/end-lines - return 0 - endif -endf diff --git a/contrib/vim/syntax/ledger.vim b/contrib/vim/syntax/ledger.vim deleted file mode 100644 index c516bab0..00000000 --- a/contrib/vim/syntax/ledger.vim +++ /dev/null @@ -1,69 +0,0 @@ -" Vim syntax file -" filetype: ledger -" by Johann Klähn; Use according to the terms of the GPL>=2. -" by Stefan Karrmann; Use according to the terms of the GPL>=2. -" by Wolfgang Oertl; Use according to the terms of the GPL>=2. -" vim:ts=2:sw=2:sts=2:foldmethod=marker - -if version < 600 - syntax clear -elseif exists("b:current_sytax") - finish -endif - -" for debugging -syntax clear - -" DATE[=EDATE] [*|!] [(CODE)] DESC <-- first line of transaction -" ACCOUNT AMOUNT [; NOTE] <-- posting - -syn region ledgerTransaction start=/^[[:digit:]~=]/ skip=/^\s/ end=/^/ - \ fold keepend transparent - \ contains=ledgerTransactionDate,ledgerMetadata,ledgerPosting,ledgerTransactionExpression -syn match ledgerTransactionDate /^\d\S\+/ contained -syn match ledgerTransactionExpression /^[=~]\s\+\zs.*/ contained -syn match ledgerPosting /^\s\+[^[:blank:];][^;]*\ze\%($\|;\)/ - \ contained transparent contains=ledgerAccount,ledgerMetadata -" every space in an account name shall be surrounded by two non-spaces -" every account name ends with a tab, two spaces or the end of the line -syn match ledgerAccount /^\s\+\zs\%(\S\@<= \S\|\S\)\+\ze\%( \|\t\|\s*$\)/ contained - -syn region ledgerPreDeclaration start=/^\(account\|payee\|commodity\|tag\)/ skip=/^\s/ end=/^/ - \ keepend transparent - \ contains=ledgerPreDeclarationType,ledgerPreDeclarationName,ledgerPreDeclarationDirective -syn match ledgerPreDeclarationType /^\(account\|payee\|commodity\|tag\)/ contained -syn match ledgerPreDeclarationName /^\S\+\s\+\zs.*/ contained -syn match ledgerPreDeclarationDirective /^\s\+\zs\S\+/ contained - -syn match ledgerComment /^;.*$/ -" comments at eol must be preceeded by at least 2 spaces / 1 tab -syn region ledgerMetadata start=/\%( \|\t\|^\s\+\);/ skip=/^\s\+;/ end=/^/ - \ keepend contained contains=ledgerTag,ledgerTypedTag -syn match ledgerTag /:[^:]\+:/hs=s+1,he=e-1 contained -syn match ledgerTag /\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+:\ze[^:]\+$/ contained -syn match ledgerTypedTag /\%(\%(;\|^tag\)[^:]\+\)\@<=[^:]\+::\ze[^:]\+$/ contained - -syn region ledgerApply - \ matchgroup=ledgerStartApply start=/^apply\>/ - \ matchgroup=ledgerEndApply end=/^end\s\+apply\>/ - \ contains=ledgerApplyHead,ledgerApply,ledgerTransaction,ledgerComment -syn match ledgerApplyHead /\%(^apply\s\+\)\@<=\S.*$/ contained - -highlight default link ledgerTransactionDate Constant -highlight default link ledgerTransactionExpression Statement -highlight default link ledgerMetadata Tag -highlight default link ledgerTypedTag Keyword -highlight default link ledgerTag Type -highlight default link ledgerStartApply Tag -highlight default link ledgerEndApply Tag -highlight default link ledgerApplyHead Type -highlight default link ledgerAccount Identifier -highlight default link ledgerPreDeclarationType Type -highlight default link ledgerPreDeclarationName Identifier -highlight default link ledgerPreDeclarationDirective Type - -" syncinc is easy: search for the first transaction. -syn sync clear -syn sync match ledgerSync grouphere ledgerTransaction "^[[:digit:]~=]" - -let b:current_syntax = "ledger" diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 12f96444..2777da68 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -32,7 +32,7 @@ if(NOT BUILD_DOCS) return() endif() -set(info_files ledger.texi ledger3.texi ledger-mode.texi) +set(info_files ledger3.texi ledger-mode.texi) find_program(MAKEINFO makeinfo) find_program(TEXI2PDF texi2pdf) @@ -96,10 +96,11 @@ if(CMAKE_INSTALL_MANDIR) DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 COMPONENT doc) endif(CMAKE_INSTALL_MANDIR) -if(CMAKE_INSTALL_DOCDIR) - foreach(file ${info_files}) - get_filename_component(file_base ${file} NAME_WE) - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${file_base}.pdf - DESTINATION ${CMAKE_INSTALL_DOCDIR} COMPONENT doc OPTIONAL) - endforeach() -endif(CMAKE_INSTALL_DOCDIR) +foreach(file ${info_files}) + get_filename_component(file_base ${file} NAME_WE) + + install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${file} + DESTINATION ${CMAKE_INSTALL_INFODIR} COMPONENT doc) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${file_base}.pdf + DESTINATION ${CMAKE_INSTALL_DOCDIR} COMPONENT doc OPTIONAL) +endforeach() diff --git a/doc/ledger-mode.texi b/doc/ledger-mode.texi index 3e87d090..c8af96cb 100644 --- a/doc/ledger-mode.texi +++ b/doc/ledger-mode.texi @@ -89,6 +89,7 @@ reports and much more... * The Ledger Buffer:: * The Reconcile Buffer:: * The Report Buffer:: +* Scheduling Transactions:: * Customizing Ledger-mode:: * Generating Ledger Regression Tests:: * Embedding Example results in Ledger Documentation:: @@ -118,10 +119,10 @@ initialization file (@file{~/.emacs}, @file{~/.emacs.d/init.el}, or @file{~/.Aquamacs/Preferences.el}). @lisp -(add-to-list ’load-path - (expand-file-name "/path/to/ledger/source/lisp/")) -(load "ldg-new") -(add-to-list ’auto-mode-alist ’("\\.ledger$" . ledger-mode)) +(add-to-list 'load-path + (expand-file-name "/path/to/ledger/source/lisp/")) +(load "ledger-mode") +(add-to-list 'auto-mode-alist '("\\.ledger$" . ledger-mode)) @end lisp This sets up Emacs to automatically recognize files that end with @@ -592,7 +593,7 @@ the ledger buffer are left in that state when the account is switched. If for some reason during reconciliation your target amount changes, type @kbd{t} and enter the new target value. -@node The Report Buffer, Customizing Ledger-mode, The Reconcile Buffer, Top +@node The Report Buffer, Scheduling Transactions, The Reconcile Buffer, Top @chapter The Report Buffer @menu @@ -738,7 +739,34 @@ recent transactions at the top, type @kbd{R} in the @file{*Ledger Report*} buffer and it will reverse the order of the transactions and maintain the proper mathematical sense. -@node Customizing Ledger-mode, Generating Ledger Regression Tests, The Report Buffer, Top +@node Scheduling Transactions, Customizing Ledger-mode, The Report Buffer, Top +@chapter Scheduling Transactions + +The Ledger program provide for automating transactions but these +transaction aren't ``real'', they only exist inside a ledger session and +are not reflected in the actual data file. Many transactions are very +repetitive, but may vary slightly in the date they occur on, or the +amount. Some transactions are weekly, monthly, quarterly or annually. +Ledger mode provides a way to schedule upcoming transaction with a +flexible scheduler that allows you to specify the transactions in a +separate ledger file and calculate the upcoming occurences of those +transactions. You can then copy the transactions into your live data +file. + +@menu +* Specifying Upcoming Transactions:: +@end menu + +@node Specifying Upcoming Transactions +@section Specifying Upcoming Transactions + +The format for specifying transactions is identical to Ledger's file +format with the exception of the date field. The data field is modified +by surrounding it with brackets and using wild cards to specity free +months or years. + + +@node Customizing Ledger-mode, Generating Ledger Regression Tests, Scheduling Transactions, Top @chapter Customizing Ledger-mode @menu diff --git a/doc/ledger.1 b/doc/ledger.1 index 659d3fbb..46c7a68e 100644 --- a/doc/ledger.1 +++ b/doc/ledger.1 @@ -182,7 +182,7 @@ Invert the value of amounts shown. .It Fl \-market Pq Fl V Show current market values for all amounts. This is determined in a somewhat magical fashion. It is probably more straightforward to use -.Fl \-exchange Pq Fl X . +.Fl \-exchange Ar commodity Pq Fl X . .It Fl \-period Ar time-period Pq Fl p Show postings only for the given .Ar time-period . @@ -281,193 +281,586 @@ transactions they are contained in. See the manual for more information. .Pp .Bl -tag -width -indent .It Fl \-abbrev-len Ar INT +Set the minimum length an account can be abbreviated to if it doesn't +fit inside the +.Nm account-width . +If +.Ar INT +is zero, then the +account name will be truncated on the right. If +.Ar INT +is greater +than +.Nm 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. .It Fl \-account Ar STR +Prepend +.Ar STR +to all accounts reported. That is, the option +.Nm --account Personal +would tack +.Nm Personal: +to the beginning of every account reported in a balance report or register report. .It Fl \-account-width Ar INT +Set the width of the account column in the +.Nm register +report +to +.Ar INT +characters. .It Fl \-actual Pq Fl L +Report only real transactions, with no automated or virtual +transactions used. .It Fl \-add-budget +Show only un-budgeted postings. .It Fl \-amount Ar EXPR Pq Fl t +Apply the given value expression to the posting amount. Using +.Nm --amount Ar EXPR +you can apply an +arbitrary transformation to the postings. .It Fl \-amount-data Pq Fl j +On a register report print only the dates and amount of postings. +Useful for graphing and spreadsheet applications. .It Fl \-amount-width Ar INT +Set the width in characters of the amount column in the +.Nm register +report. .It Fl \-anon +Anonymize registry output, mostly for sending in bug reports. .It Fl \-args-only .It Fl \-auto-match .It Fl \-aux-date +Show auxiliary dates for all calculations. +Alias for +.Fl \-effective .It Fl \-average Pq Fl A +Print average values over the number of transactions instead of +running totals. .It Fl \-balance-format Ar FMT +Specify the format to use for the +.Nm balance +report. .It Fl \-base .It Fl \-basis Pq Fl B +Report the cost basis on all posting. +Alias for +.Fl \-cost .It Fl \-begin Ar DATE Pq Fl b +Specify the start +.Ar DATE +of all calculations. Transactions before +that date will be ignored. .It Fl \-bold-if Ar EXPR +Print the entire line in bold if the given value expression is true. .It Fl \-budget +Only display budgeted items. In a register report this +displays transaction in the budget, in a balance report this displays +accounts in the budget. .It Fl \-budget-format Ar FMT +Specify the format to use for the +.Nm budget +report. .It Fl \-by-payee Pq Fl P +Group postings in the register report by common payee names. .It Fl \-cache Ar FILE .It Fl \-check-payees +Enable strict and pedantic checking for payees as well as accounts, +commodities and tags. .It Fl \-cleared Pq Fl C +Display only cleared postings. .It Fl \-cleared-format Ar FMT +Specify the format to use for the +.Nm cleared +report .It Fl \-collapse Pq Fl n +By default ledger prints all accounts in an account tree. With +.Fl \-collapse +it prints only the top level account specified. .It Fl \-collapse-if-zero +Collapse the account display only if it has a zero balance. .It Fl \-color +Use color if the terminal supports it. +Alias for +.Fl \-ansi .It Fl \-columns Ar INT +Specify the width of the +.Nm register +report in characters. .It Fl \-cost -See +Report the cost basis on all posting. +Alias for .Fl \-basis . .It Fl \-count +Direct ledger to report the number of items when appended to the +commodities, accounts or payees command. .It Fl \-csv-format Ar FMT +Specify the format to use for the +.Nm csv +report .It Fl \-current Pq Fl c -.It Fl \-daily +Shorthand for +.Nm --limit 'date <= today' . +.It Fl \-daily Pq Fl D +Shorthand for +.Nm --period 'daily' . .It Fl \-date Ar EXPR +Transform the date of the transaction using +.Ar EXPR . .It Fl \-date-format Ar DATEFMT Pq Fl y +Specify the format ledger should use to print dates. .It Fl \-datetime-format Ar FMT .It Fl \-date-width Ar INT +Specify the width, in characters, of the date column in the +.Nm register +report. .It Fl \-day-break .It Fl \-dc +Display register or balance in debit/credit format If you use +.Fl \-dc +with either the register (reg) or balance (bal) commands, +you will now get separate columns for debits and credits. .It Fl \-debug Ar STR +If Ledger has been built with debug options this will provide extra +data during the run. .It Fl \-decimal-comma +Direct Ledger to parse journals using the European standard comma as +decimal separator, vice a period. .It Fl \-depth Ar INT +Limit the depth of the account tree. In a balance report, for example, +a +.Fl \-depth 2 +statement will print balances only for account with +two levels, i.e. +.Nm Expenses:Entertainment +but not +.Nm Expenses:entertainemnt:Dining . +This is a display predicate, which +means it only affects display, not the total calculations. .It Fl \-deviation Pq Fl D +Report each posting’s deviation from the average. It is only meaningful +in the register and prices reports. .It Fl \-display Ar EXPR Pq Fl d +Display lines that satisfy the expression +.Ar EXPR . .It Fl \-display-amount Ar EXPR +Apply a transformation to the +.Nm displayed +amount. This occurs after +calculations occur. .It Fl \-display-total Ar EXPR +Apply a transformation to the +.Nm displayed +total. This occurs after +calculations occur. .It Fl \-dow +Group transactions by the days of the week. +Alias for +.Fl \-days-of-week .It Fl \-download +Cause quotes to be automagically downloaded, as needed, by running +a script named +.Nm getquote +and expecting that script to return +a value understood by ledger. A sample implementation of +a +.Nm 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 +.Nm LEDGER_PRICE_DB . .It Fl \-empty Pq Fl E -.It Fl \-end Pq Fl e +Include empty accounts in report. +.It Fl \-end Ar DATE Pq Fl e +Specify the end +.Ar DATE +for a transaction to be considered in the +report. .It Fl \-equity +Related to the +.Nm equity +command. Gives current account balances in the form of a register +report. .It Fl \-exact -.It Fl \-exchange Ar COMM Oo , COMM, ... Oc Pq Fl X +.It Fl \-exchange Ar COMMODITY Oo , COMM, ... Oc Pq Fl X +Display values in terms of the given +.Ar COMMODITY . +The latest available price is used. .It Fl \-explicit .It Fl \-file Ar FILE +Read +.Ar FILE +as a ledger file. .It Fl \-first Ar INT -See +Print the first +.Ar INT +entries. Opposite of +.Fl \-tail Ar INT . +Alias for .Fl \-head . .It Fl \-flat +Force the full names of accounts to be used in the balance report. The +balance report will not use an indented tree. .It Fl \-force-color +Output TTY color codes even if the TTY doesn't support them. Useful +for TTYs that don't advertise their capabilities correctly. .It Fl \-force-pager +Force Ledger to paginate its output. .It Fl \-forecast-while Ar EXPR -(Also -.Fl \-forecast -). +Continue forecasting while +.Ar VEXPR +is true. +Alias for +.Fl \-forecast . .It Fl \-forecast-years Ar INT +Forecast at most +.Ar INT +years into the future. .It Fl \-format Ar FMT Pq Fl F -.It Fl \-full-help +Use the given format string +.Ar FMT +to print output. .It Fl \-gain Pq Fl G +Report net gain or loss for commodities that have a price history. .It Fl \-generated +Include auto-generated postings (such as those from automated +transactions) in the report, in cases where you normally wouldn't want +them. .It Fl \-group-by Ar EXPR +Group transaction together in the +.Nm register +report. +.Ar EXPR +can be anything, although most common would be +.Nm payee +or +.Nm commodity . +The +.Nm tags() +function is also useful here. .It Fl \-group-title-format Ar FMT +Set the format for the headers that separate reports section of +a grouped report. Only has effect with a +.Fl \-group-by Ar EXPR +register report. .It Fl \-head Ar INT +Print the first +.Ar INT +entries. Opposite of +.Fl \-tail Ar INT . +Alias for +.Fl \-first .It Fl \-help -.It Fl \-help-calc -.It Fl \-help-comm -.It Fl \-help-disp +Print a summary of all the options, and what they are used for. This +can be a handy way to remember which options do what. This help screen +is also printed if ledger is run without a command. .It Fl \-immediate -.It Fl \-import Ar STR +Instruct ledger to evaluate calculations immediately rather than lazily. .It Fl \-init-file Ar FILE +Causes +.Nm 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 +the command-line, but put each option on its own line. .It Fl \-inject Ar STR +TODO .It Fl \-input-date-format Ar DATEFMT +Specify the input date format for journal entries. .It Fl \-invert +Change the sign of all reported values. .It Fl \-last Ar INT -See +Report only the last +.Ar INT +entries. Only useful on a register +report. +Alias for .Fl \-tail . .It Fl \-leeway Ar INT Pq Fl Z +Alias for +.Fl \-price-expr . .It Fl \-limit Ar EXPR Pq Fl l +Limit postings in calculations. .It Fl \-lot-dates +Report the date on which each commodity in a balance report was +purchased. .It Fl \-lot-notes +Report the tag attached to each commodity in a balance report. .It Fl \-lot-prices +Report the price at which each commodity in a balance report was +purchased. .It Fl \-lots +Report the date and price at which each commodity was purchased in +a balance report. .It Fl \-lots-actual .It Fl \-market Pq Fl V +Use the latest market value for all commodities. .It Fl \-master-account Ar STR +Prepend all account names with +.Ar STR .It Fl \-meta Ar EXPR +In the register report, prepend the transaction with the value of the given +.Ar TAG . .It Fl \-meta-width Ar INT +Specify the width of the Meta column used for the +.Fl \-meta Ar TAG +options. .It Fl \-monthly Pq Fl M +Shorthand for +.Fl \-period 'monthly' . +.It Fl \-no-aliases +Aliases are completely ignored. .It Fl \-no-color -.It Fl \-no-pager +Suppress any color TTY output. .It Fl \-no-rounding +Don't output +.Nm <Rounding> +postings. Note that this will cause the +running total to often not add up! It's main use is for +.Fl \-amount-data Pq Fl j +and +.Fl \-total-data Pq Fl J +reports. .It Fl \-no-titles +Suppress the output of group titles. .It Fl \-no-total +Suppress printing the final total line in a balance report. .It Fl \-now Ar DATE +Define the current date in case to you to do calculate in the past or +future using +.Fl \-current . .It Fl \-only Ar EXPR +This is a postings predicate that applies after certain transforms have +been executed, such as periodic gathering. .It Fl \-options +Display the options in effect for this Ledger invocation, along with +their values and the source of those values. .It Fl \-output Ar FILE Pq Fl o +Redirect the output of ledger to the file defined in +.Ar FILE . .It Fl \-pager Ar STR +Specify the pager program to use as +.Ar STR . .It Fl \-payee +Sets a value expression for formatting the payee. In the +.Nm register +report this prevents the second entry from having +a date and payee for each transaction. .It Fl \-payee-width Ar INT +Set the number of columns dedicated to the payee in the register +report to +.Ar INT . .It Fl \-pedantic +Accounts, tags or commodities not previously declared will cause errors. .It Fl \-pending -.It Fl \-percent Pq Fl \% +Use only postings that are marked pending. +.It Fl \-percent Pq Fl \b'%' +Calculate the percentage value of each account in a balance reports. +Only works for account that have a single commodity. .It Fl \-period Ar PERIOD Pq Fl p +Define a period expression that sets the time period during which +transactions are to be accounted. For a +.Nm 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. .It Fl \-period-sort +Sort the posting within transactions using the given value expression. .It Fl \-permissive .It Fl \-pivot Ar STR +Produce a balance pivot report +.Nm around +the given +.Ar TAG . .It Fl \-plot-amount-format Ar FMT +Define the output format for an amount data plot. .It Fl \-plot-total-format Ar FMT +Define the output format for a total data plot. .It Fl \-prepend-format Ar FMT +Prepend +.Ar STR +to every line of the output. .It Fl \-prepend-width Ar INT +Reserve +.Ar INT +spaces at the beginning of each line of the output. .It Fl \-price Pq Fl I +Use the price of the commodity purchase for performing calculations. .It Fl \-price-db Ar FILE -.It Fl \-price-exp Ar STR -See -.Fl \-leeway . +.It Fl \-price-exp Ar STR Pq Fl Z +Set the expected freshness of price quotes, in +.Ar INT +minutes. That +is, if the last known quote for any commodity is older than this value, +and if +.Fl \-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. +Alias for +.Fl \-leeway Ar INT Pq Fl Z .It Fl \-prices-format Ar FMT .It Fl \-pricedb-format Ar FMT .It Fl \-primary-date +Show primary dates for all calculations. Alias for +.Fl \-actual-dates .It Fl \-quantity Pq Fl O +Report commodity totals (this is the default). .It Fl \-quarterly +Synonym for +\Fl \-period 'quarterly' . .It Fl \-raw -For use only with the +In the .Nm print -command, it causes Ledger to print out matching entries exactly as they -appeared in the original journal file. +report, show transactions using the exact same syntax as +specified by the user in their data file. Don't do any massaging or +interpreting. Can be useful for minor cleanups, like just aligning +amounts. .It Fl \-real Pq Fl R +Account using only real transactions ignoring virtual and automatic +transactions. +.It Fl \-recursive-aliases +Causes ledger to try to expand aliases recursively, i.e. try to expand +the result of an earlier expansion again, until no more expansions apply. .It Fl \-register-format Ar FMT +Define the output format for the +.Nm register +report. .It Fl \-related Pq Fl r +In a register report show the related account. This is the other +.Nm side +of the transaction. .It Fl \-related-all +Show all postings in a transaction, similar to +.Fl \-related +but show +.Nm both sides +of each transaction. .It Fl \-revalued .It Fl \-revalued-only .It Fl \-revalued-total Ar EXPR .It Fl \-rich-data .It Fl \-seed Ar INT -.It Fl \-script +Set the random seed to +.Ar INT +for the +.Nm generate +command. Used as part of development testing. +.It Fl \-script Ar FILE +Execute a ledger script. .It Fl \-sort Ar EXPR Pq Fl S +Sort the register report based on the value expression given to sort. .It Fl \-sort-all .It Fl \-sort-xacts +Sort the posting within transactions using the given value expression. .It Fl \-start-of-week Ar STR +Tell ledger to use a particular day of the week to start its "weekly" +summary. +.Fl \-start-of-week=1 +specifies Monday as the start of the week. .It Fl \-strict +Accounts, tags or commodities not previously declared will cause warnings. .It Fl \-subtotal Pq Fl s +Report register as a single subtotal. .It Fl \-tail Ar INT +Report only the last +.Ar INT +entries. Only useful on a register report. Alias for +.Fl \-last Ar INT .It Fl \-time-report -.It Fl \-total Ar EXPR +.It Fl \-total Ar EXPR Pq Fl T +Define a value expression used to calculate the total in reports. .It Fl \-total-data Pq Fl J +Show only dates and totals to format the output for plots. .It Fl \-total-width Ar INT +Set the width of the total field in the register report. .It Fl \-trace Ar INT -.It Fl \-truncate +Enable tracing. The +.Ar INT +specifies the level of trace desired. +.It Fl \-truncate Ar CODE +Indicates how truncation should happen when the contents of columns +exceed their width. Valid arguments are +.Nm leading , Nm middle , +and +.Nm trailing . +The default is smarter than any of these three, +as it considers sub-names within the account name (that style is +called "abbreviate"). .It Fl \-unbudgeted +Show only un-budgeted postings. .It Fl \-uncleared Pq Fl U +Use only uncleared transactions in calculations and reports. .It Fl \-unrealized .It Fl \-unrealized-gains +Allow the user to specify what account name should be used for +unrealized gains. Defaults to +.Nm "Equity:Unrealized Gains" . +Often set in one's +.Nm ~/.ledgerrc +file to change the default. .It Fl \-unrealized-losses +Allow the user to specify what account name should be used for +unrealized gains. Defaults to +.Nm "Equity:Unrealized Losses" . +Often set in one's +.Nm ~/.ledgerrc +file to change the default. .It Fl \-unround +Perform all calculations without rounding and display results to full +precision. +.It Fl \-values .It Fl \-value-expr Ar EXPR .It Fl \-verbose +Print detailed information on the execution of Ledger. .It Fl \-verify +Enable additional assertions during run-time. This causes a significant +slowdown. When combined with +.Fl \-debug Ar CODE +ledger will produce memory trace information. .It Fl \-verify-memory .It Fl \-version +Print version information and exit. .It Fl \-weekly Pq Fl W +Synonym for +.Fl \-period 'weekly' . .It Fl \-wide Pq Fl w +Assume 132 columns instead of 80. .It Fl \-yearly Pq Fl Y +Synonym for +.Fl \-period 'yearly' . .El .Pp -.Sh PRECOMMANDS +.Sh PRE-COMMANDS +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. .Pp .Bl -tag -width -indent -.It Nm args +.It Nm args / query +Evaluate the given arguments and report how Ledger interprets it against +the following model transaction. .It Nm eval +Evaluate the given value expression against the model transaction. .It Nm format -.It Nm parse +Print details of how ledger uses the given formatting description and +apply it against a model transaction. +.It Nm parse / expr +Print details of how ledger uses the given value expression description +and apply it against a model transaction. +.It Nm generate +Randomly generates syntactically valid Ledger data from a seed. Used +by the GenerateTests harness for development testing. .It Nm period -.It Nm python +Evaluate the given period and report how Ledger interprets it. +.It Nm script .It Nm template +Shows the insertion template that the +.Nm xact sub-command generates. +This is a debugging command. .El .Pp .Sh QUERIES diff --git a/doc/ledger.texi b/doc/ledger.texi deleted file mode 100644 index 8389c383..00000000 --- a/doc/ledger.texi +++ /dev/null @@ -1,4108 +0,0 @@ -\input texinfo @c -*-texinfo-*- - -@setfilename ledger.info -@settitle Ledger: Command-Line Accounting - -@dircategory User Applications -@copying -Copyright (c) 2003-2010, John Wiegley. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -- Neither the name of New Artisans LLC nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -@end copying - -@documentencoding UTF-8 - -@iftex -@finalout -@end iftex - -@titlepage -@title Ledger: Command-Line Accounting -@author John Wiegley -@end titlepage - -@direntry -* Ledger: (ledger). Command Line Accounting -@end direntry - -@contents - -@ifnottex -@node Top, Introduction, (dir), (dir) -@top Overview - -@insertcopying -@end ifnottex - -@menu -* Introduction:: -* Quick Reference:: -* Ledger Tutorial:: -* Ledger in Practice:: -@end menu - -@ifnottex -@section Copyright -@insertcopying -@end ifnottex - -@node Introduction, Quick Reference, Top, Top -@chapter Introduction - -Ledger is an accounting tool with the moxie to exist. It provides no -bells or whistles, and returns the user to the days before user -interfaces were even a twinkling in their father's CRT. - -What it does offer is a double-entry accounting ledger with all the -flexibility and muscle of its modern day cousins, without any of the -fat. Think of it as the Bran Muffin of accounting tools. - -To use it, you need to start keeping a ledger. This is the basis of -all accounting, and if you haven't started yet, now is the time to -learn. The little booklet that comes with your checkbook is a ledger, -so we'll describe double-entry accounting in terms of that. - -A checkbook ledger records debits (subtractions, or withdrawals) and -credits (additions, or deposits) with reference to a single account: -the checking account. Where the money comes from, and where it goes -to, are described in the payee field, where you write the person or -company's name. The ultimate aim of keeping a checkbook ledger is to -know how much money is available to spend. That's really the aim of -all ledgers. - -What computers add is the ability to walk through these postings, -and tell you things about your spending habits; to let you devise -budgets and get control over your spending; to squirrel away money -into virtual savings account without having to physically move money -around; etc. As you keep your ledger, you are recording information -about your life and habits, and sometimes that information can start -telling you things you aren't aware of. Such is the aim of all good -accounting tools. - -The next step up from a checkbook ledger, is a ledger that keeps track -of all your accounts, not just checking. In such a ledger, you record -not only who gets paid---in the case of a debit---but where the money -came from. In a checkbook ledger, its assumed that all the money -comes from your checking account. But in a general ledger, you write -posting two-lines: the source account and target account. -@emph{There must always be a debit from at least one account for every -credit made to another account}. This is what is meant by -``double-entry'' accounting: the ledger must always balance to zero, -with an equal number of debits and credits. - -For example, let's say you have a checking account and a brokerage -account, and you can write checks from both of them. Rather than keep -two checkbooks, you decide to use one ledger for both. In this -general ledger you need to record a payment to Pacific Bell for your -monthly phone bill. The cost is $23.00, let's say, and you want to -pay it from your checking account. In the general ledger you need to -say where the money came from, in addition to where it's going to. -Such a transaction might look like this: - -@smallexample -9/29 Pacific Bell $23.00 $23.00 - Checking $-23.00 0 -@end smallexample - -The posting must balance to $0: $23 went to Pacific Bell, $23 came -from Checking. There is nothing left over to be accounted for, since -the money has simply moved from one account to another. This is the -basis of double-entry accounting: that money never pops in or out of -existence; it is always a posting from one account to another. - -Keeping a general ledger is the same as keeping two separate ledgers: -One for Pacific Bell and one for Checking. In that case, each time a -payment is written into one, you write a corresponding withdrawal into -the other. This makes it easier to write in a ``running balance'', -since you don't have to look back at the last time the account was -referenced---but it also means having a lot of ledger books, if you -deal with multiple accounts. - -Enter the beauty of computerized accounting. The purpose of the -Ledger program is to make general ledger accounting simple, by keeping -track of the balances for you. Your only job is to enter the -postings. If a posting does not balance, Ledger displays an -error and indicates the incorrect posting.@footnote{In some -special cases, it automatically balances this transaction for you.} - -In summary, there are two aspects of Ledger use: updating the ledger -data file, and using the Ledger tool to view the summarized result of -your transactions. - -And just for the sake of example---as a starting point for those who -want to dive in head-first---here are the ledger transactions from above, -formatting as the ledger program wishes to see them: - -@smallexample -2004/09/29 Pacific Bell - Expenses:Pacific Bell $23.00 - Assets:Checking -@end smallexample - -The account balances and registers in this file, if saved as -@file{ledger.dat}, could be reported using: - -@example -$ ledger -f ledger.dat balance -$ ledger -f ledger.dat register checking -$ ledger -f ledger.dat register bell -@end example - -@section More introduction - -The most important part of accounting is keeping a good ledger. If -you have a good ledger, tools can be written to work whatever -mathematically tricks you need to better understand your spending -patterns. Without a good ledger, no tool, however smart, can help -you. - -The Ledger program aims at making ledger transaction as simple as possible. -Since it is a command-line tool, it does not provide a user interface -for keeping a ledger. If you like, you may use GnuCash to maintain -your ledger, in which case the Ledger program will read GnuCash's data -files directly. In that case, read the GnuCash manual now, and skip -to the next chapter. - -If you are not using GnuCash, but a text editor to maintain your -ledger, read on. Ledger has been designed to make data transaction as -simple as possible, by keeping the ledger format easy, and also by -automagically determining as much information as possible based on the -nature of your transactions. - -For example, you do not need to tell Ledger about the accounts you -use. Any time Ledger sees a posting involving an account it knows -nothing about, it will create it. If you use a commodity that is new -to Ledger, it will create that commodity, and determine its display -characteristics (placement of the symbol before or after the amount, -display precision, etc) based on how you used the commodity in the -posting. - -Here is the Pacific Bell example from above, given as a Ledger -posting: - -@smallexample -9/29 Pacific Bell - Expenses:Utilities:Phone $23.00 - Assets:Checking $-23.00 -@end smallexample - -As you can see, it is very similar to what would be written on paper, -minus the computed balance totals, and adding in account names that -work better with Ledger's scheme of things. In fact, since Ledger is -smart about many things, you don't need to specify the balanced -amount, if it is the same as the first line: - -@smallexample -9/29 Pacific Bell - Expenses:Utilities:Phone $23.00 - Assets:Checking -@end smallexample - -For this transaction, Ledger will figure out that $-23.00 must come from -@samp{Assets:Checking} in order to balance the transaction. - -@section Building the program - -Ledger is written in ANSI C++, and should compile on any platform. It -depends on the GNU multiprecision integer library (libgmp), and the -Perl regular expression library (libpcre). It was developed using GNU -make and gcc 3.3, on a PowerBook running OS/X. - -To build and install once you have these libraries on your system, -enter these commands: - -@example -./configure && make install -@end example - -@section Getting help - -If you need help on how to use Ledger, or run into problems, you can -just the Ledger mailing list at the following Web address: - -@example -https://lists.sourceforge.net/lists/listinfo/ledger-discuss -@end example - -You can also find help at the @samp{#ledger} channel on the IRC server -@samp{irc.freenode.net}. - -@node Quick Reference, Ledger Tutorial, Introduction, Top -@chapter Quick Reference - -This chapter describes ledger's features and serves as a quick -reference. You may wish to survey this to get an overview before diving -in to the @ref{Ledger Tutorial} and more detailed examples that follow. - -Ledger has a very simple command-line interface, named---enticing -enough---@command{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: - -@example -ledger [OPTIONS...] COMMAND [ARGS...] -@end example - -Command options must always precede the command word. 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 @command{transaction} 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 @samp{--}. For example, the -following balance command reports account totals for rent, food and -movies, but only those whose payee matches Freddie: - -@example -ledger bal rent food movies -- freddie -@end example - -There are many, many command options available with the -@command{ledger} command, and it takes a while to master them. -However, none of them are required to use the basic reporting -commands. - -@menu -* Commands:: -* Options:: -* Period expressions:: -* Format strings:: -* Value expressions:: -* File format:: -@end menu - -@node Commands, Options, Quick Reference, Quick Reference -@section Commands - -@subsection balance - -The @command{balance} command reports the current balance of all -accounts. It accepts a list of optional regexps, which confine the -balance report to the matching accounts. If an account contains -multiple types of commodities, each commodity's total is reported -separately. - -@subsection register - -The @command{register} command displays all the postings occurring -in a single account, line by line. The account regexp must be -specified as the only argument to this command. If any regexps occur -after the required account name, the register will contain only those -postings that match. Very useful for hunting down a particular -posting. - -The output from @command{register} is very close to what a typical -checkbook, or single-account ledger, would look like. It also shows a -running balance. The final running balance of any register should -always be the same as the current balance of that account. - -If you have Gnuplot installed, you may plot the amount or running -total of any register by using the script @file{report}, which is -included in the Ledger distribution. The only requirement is that you -add either @option{-j} or @option{-J} to your register command, in -order to plot either the amount or total column, respectively. - -@subsection print - -The @command{print} command prints out ledger transactions in a textual -format that can be parsed by Ledger. They will be properly formatted, -and output in the most economic form possible. The ``print'' command -also takes a list of optional regexps, which will cause only those -postings which match in some way to be printed. - -The @command{print} command can be a handy way to clean up a ledger -file whose formatting has gotten out of hand. - -@subsection output - -The @command{output} command is very similar to the @command{print} -command, except that it attempts to replicate the specified ledger -file exactly. The format of the command is: - -@example -ledger -f FILENAME output FILENAME -@end example - -Where @file{FILENAME} is the name of the ledger file to output. The -reason for specifying this command is that only transactions contained -within that file will be output, and not an included transactions (as can -happen with the @command{print} command). - -@subsection xml - -The @command{xml} command outputs results similar to what -@command{print} and @command{register} display, but as an XML form. -This data can then be read in and processed. Use the -@option{--totals} option to include the running total with each -posting. - -@subsection emacs - -The @command{emacs} command outputs results in a form that can be read -directly by Emacs Lisp. The format of the sexp is: - -@example -((BEG-POS CLEARED DATE CODE PAYEE - (ACCOUNT AMOUNT)...) ; list of postings - ...) ; list of transactions -@end example - -@subsection equity - -The @command{equity} command prints out accounts balances as if they -were transactions. This makes it easy to establish the starting balances -for an account, such as when @ref{Archiving previous years}. - -@subsection prices - -The @command{prices} command displays the price history for matching -commodities. The @option{-A} flag is useful with this report, to -display the running average price, or @option{-D} to show each price's -deviation from that average. - -There is also a @command{pricesdb} command which outputs the same -information as @command{prices}, but does in a format that can be -parsed by Ledger. - -@subsection xact - -The @command{xact} commands 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: - -@smallexample -2004/03/15 * Viva Italiano - Expenses:Food $12.45 - Expenses:Tips $2.55 - Liabilities:MasterCard $-15.00 -@end smallexample - -Now it's @samp{2004/4/9}, and you've just eating at @samp{Viva -Italiano} again. The exact amounts are different, but the overall -form is the same. With the @command{xact} command you can type: - -@example -ledger xact 2004/4/9 viva food 11 tips 2.50 -@end example - -This produces the following output: - -@smallexample -2004/04/09 Viva Italiano - Expenses:Food $11.00 - Expenses:Tips $2.50 - Liabilities:MasterCard $-13.50 -@end smallexample - -It works by finding a past posting matching the regular expression -@samp{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 @samp{1}. - -There is a shell script in the distribution's @file{scripts} directory -called @file{xact}, which simplifies the task of adding a new transaction -to your ledger. It launches @command{vi} to confirm that the transaction -looks appropriate. - -Here are a few more examples of the @command{xact} command, assuming -the above journal transaction: - -@example -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" -@end example - -@node Options, Period expressions, Commands, Quick Reference -@section Options - -With all of the reports, command-line options are useful to modify the -output generated. These command-line options always occur before the -command word. This is done to distinguish options from exclusive -regular expressions, which also begin with a dash. The basic form for -most commands is: - -@example -ledger [OPTIONS] COMMAND [REGEXPS...] [-- [REGEXPS...]] -@end example - -The @var{OPTIONS} and @var{REGEXPS} expressions are both optional. -You could just use @samp{ledger balance}, without any options---which -prints a summary of all accounts. But for more specific reporting, or -to change the appearance of the output, options are needed. - -@subsection Basic options - -These are the most basic command options. Most likely, the user will -want to set them using environment variables (see @ref{Options}), -instead of using actual command-line options: - -@option{--help} (@option{-h}) prints a summary of all the options, and -what they are used for. This can be a handy way to remember which -options do what. This help screen is also printed if ledger is run -without a command. - -@option{--version} (@option{-v}) prints 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. - -@option{--file FILE} (@option{-f FILE}) reads FILE as a ledger file. -This command may be used multiple times. -Typically, the environment variable -@env{LEDGER_FILE} is set, rather than using this command-line option. - -@option{--output FILE} (@option{-o FILE}) redirects output from any -command to @var{FILE}. By default, all output goes to standard -output. - -@option{--init-file FILE} (@option{-i FILE}) 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 the command-line, but put each -option on it's own line. Here's an example init file: - -@smallexample ---price-db ~/finance/.pricedb ---cache /tmp/ledger-cache - -; ~/.ledgerrc ends here -@end smallexample - -Option settings on the command-line or in the environment always take -precedence over settings in the init file. - -@option{--cache FILE} identifies FILE as the default binary cache -file. That is, if the ledger files to be read are specified using the -environment variable @env{LEDGER_FILE}, then whenever a command is -finished a binary copy will be written to the specified cache, to -speed up the loading time of subsequent queries. This filename can -also be given using the environment variable @env{LEDGER_CACHE}, or by -putting the option into your init file. The @option{--no-cache} -option causes Ledger to always ignore the binary cache. - -@option{--account NAME} (@option{-a NAME}) specifies the default -account which QIF file postings are assumed to relate to. - -@subsection Report filtering - -These options change which postings affect the outcome of a -report, in ways other than just using regular expressions: - -@option{--current}(@option{-c}) displays only transactions occurring on or -before the current date. - -@option{--begin DATE} (@option{-b DATE}) constrains the report to -transactions on or after @var{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 @option{--display} to constrain what is -displayed). - -@option{--end DATE} (@option{-e DATE}) constrains the report so that -transactions on or after @var{DATE} are not considered. The ending date -is inclusive. - -@option{--period STR} (@option{-p STR}) sets the reporting period -to @var{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 using period expressions, see -@ref{Period expressions}. - -@option{--period-sort EXPR} sorts the postings within each -reporting period using the value expression @var{EXPR}. This is most -often useful when reporting monthly expenses, in order to view the -highest expense categories at the top of each month: - -@example -ledger -M --period-sort -At reg ^Expenses -@end example - -@option{--cleared} (@option{-C}) displays only postings whose transaction -has been marked ``cleared'' (by placing an asterix to the right of the -date). - -@option{--uncleared} (@option{-U}) displays only postings whose -transaction has not been marked ``cleared'' (i.e., if there is no asterix to -the right of the date). - -@option{--real} (@option{-R}) displays only real postings, not -virtual. (A virtual posting is indicated by surrounding the -account name with parentheses or brackets; see the section on using -virtual postings for more information). - -@option{--actual} (@option{-L}) displays only actual postings, and -not those created due to automated postings. - -@option{--related} (@option{-r}) displays 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: - -@smallexample -2004/03/20 Safeway - Expenses:Food $65.00 - Expenses:Cash $20.00 - Assets:Checking $-85.00 -@end smallexample - -And the register command was: - -@example -ledger -r register food -@end example - -The following would be output, showing the postings related to the -posting that matched: - -@smallexample -2004/03/20 Safeway Expenses:Cash $-20.00 $-20.00 - Assets:Checking $85.00 $65.00 -@end smallexample - -@option{--budget} is useful for displaying how close your postings -meet your budget. @option{--add-budget} also shows unbudgeted -postings, while @option{--unbudgeted} shows only those. -@option{--forecast} is a related option that projects your budget into -the future, showing how it will affect future balances. -@xref{Budgeting and forecasting}. - -@option{--limit EXPR} (@option{-l EXPR}) limits which postings -take part in the calculations of a report. - -@option{--amount EXPR} (@option{-t EXPR}) changes the value expression -used to calculate the ``value'' column in the @command{register} -report, the amount used to calculate account totals in the -@command{balance} report, and the values printed in the -@command{equity} report. @xref{Value expressions}. - -@option{--total EXPR} (@option{-T EXPR}) sets the value expression -used for the ``totals'' column in the @command{register} and -@command{balance} reports. - -@subsection Output customization - -These options affect only the output, but not which postings are -used to create it: - -@option{--collapse} (@option{-n}) causes transactions in a -@command{register} report with multiple postings to be collapsed -into a single, subtotaled transaction. - -@option{--subtotal} (@option{-s}) causes all transactions in a -@command{register} report to be collapsed into a single, subtotaled -transaction. - -@option{--by-payee} (@option{-P}) reports subtotals by payee. - -@option{--comm-as-payee} (@option{-x}) changes the payee of every -posting to be the commodity used in that posting. This can be -useful when combined with other options, such as @option{-s}. - -@option{--empty} (@option{-E}) includes even empty accounts in the -@command{balance} report. - -@option{--weekly} (@option{-W}) reports 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 @samp{weekly from DATE}. @option{--monthly} -(@option{-M}) reports posting totals by month; @option{--yearly} -(@option{-Y}) reports posting totals by year. For more complex -period, using the @option{--period} option described above. - -@option{--dow} reports postings totals for each day of the week. -This is an easy way to see if weekend spending is more than on -weekdays. - -@option{--sort EXPR} (@option{-S EXPR}) sorts a report by comparing -the values determined using the value expression @var{EXPR}. For -example, using @option{-S -UT} 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 @ref{Value -expressions}. - -@option{--wide} (@option{-w}) causes the default @command{register} -report to assume 132 columns instead of 80. - -@option{--head} causes only the first N transactions to be printed. This -is different from using the command-line utility @command{head}, which -would limit to the first N postings. @option{--tail} outputs only -the last N 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). - -@option{--pager} tells Ledger to pass its output to the given pager -program---very useful when the output is especially long. This -behavior can be made the default by setting the @env{LEDGER_PAGER} -environment variable. - -@option{--average} (@option{-A}) reports the average posting -value. - -@option{--deviation} (@option{-D}) reports each posting's -deviation from the average. It is only meaningful in the -@command{register} and @command{prices} reports. - -@option{--percentage} (@option{-%}) shows account subtotals in the -@command{balance} report as percentages of the parent account. - -@option{--totals} include running total information in the -@command{xml} report. - -@option{--amount-data} (@option{-j}) changes the @command{register} -report so that it outputs 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. - -@option{--total-data} (@option{-J}) changes the @command{register} -report so that it outputs nothing but the date and totals column, -without commodities. - -@option{--display EXPR} (@option{-d EXPR}) limits which postings -or accounts or 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: - -@example -ledger -d "d>=[last month]" reg checking -@end example - -The output from this command is very different from the following, -whose running total includes only postings from the last month -onward: - -@example -ledger -p "last month" reg checking -@end example - -Which is more useful depends on what you're looking to know: the total -amount for the reporting range (@option{-p}), or simply a display -restricted to the reporting range (using @option{-d}). - -@option{--date-format STR} (@option{-y STR}) changes the basic date -format used by reports. The default uses a date like 2004/08/01, -which represents the default date format of @samp{%Y/%m/%d}. To -change the way dates are printed in general, the easiest way is to put -@option{--date-format FORMAT} in the Ledger initialization file -@file{~/.ledgerrc} (or the file referred to by @env{LEDGER_INIT}). - -@option{--format STR} (@option{-F STR}) sets the reporting format for -whatever report ledger is about to make. @xref{Format strings}. -There are also specific format commands for each report type: - -@itemize -@item @option{--balance-format STR} -@item @option{--register-format STR} -@item @option{--print-format STR} -@item @option{--plot-amount-format STR} (-j @command{register}) -@item @option{--plot-total-format STR} (-J @command{register}) -@item @option{--equity-format STR} -@item @option{--prices-format STR} -@item @option{--wide-register-format STR} (-w @command{register}) -@end itemize - -@subsection Commodity reporting - -These options affect how commodity values are displayed: - -@option{--price-db FILE} sets 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, for -example. This is done by adding a line like the following: - -@example -; Don't download quotes for the dollar, or timelog values -N $ -N h -@end example - -@option{--price-exp MINS} (@option{-L MINS}) sets the expected -freshness of price quotes, in minutes. That is, if the last known -quote for any commodity is older than this value---and if -@option{--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. - -@option{--download} (@option{-Q}) causes quotes to be automagically -downloaded, as needed, by running a script named @command{getquote} -and expecting that script to return a value understood by ledger. A -sample implementation of a @command{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 @env{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 @option{-t} and @option{-T} options. However, -there are also several ``default'' reports, which will satisfy most -users basic reporting needs: - -@table @code -@item -O, --quantity -Reports commodity totals (this is the default) - -@item -B, --basis -Reports the cost basis for all postings. - -@item -V, --market -Reports the last known market value for all commodities. - -@item -G --gain -Reports the net gain/loss for all commodities in the report that have -a price history. -@end table - -@subsection Environment variables - -Every option to ledger may be set using an environment variable. If -an option has a long name such @option{--this-option}, setting the -environment variable @env{LEDGER_THIS_OPTION} will have the same -affect as specifying that option 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 @file{~/.ledgerrc}, for example: - -@example ---cache /tmp/.mycache ---pager /bin/cat - -@end example - -@node Period expressions, Format strings, Options, Quick Reference -@section Period expressions - -A period expression indicates a span of time, or a reporting interval, -or both. The full syntax is: - -@example -[INTERVAL] [BEGIN] [END] -@end example - -The optional @var{INTERVAL} part may be any one of: - -@example -every day -every week -every monthly -every quarter -every year -every N days # N is any integer -every N weeks -every N months -every N quarters -every N years -daily -weekly -biweekly -monthly -bimonthly -quarterly -yearly -@end example - -After the interval, a begin time, end time, both or neither may be -specified. As for the begin time, it can be either of: - -@example -from <SPEC> -since <SPEC> -@end example - -The end time can be either of: - -@example -to <SPEC> -until <SPEC> -@end example - -Where @var{SPEC} can be any of: - -@example -2004 -2004/10 -2004/10/1 -10/1 -october -oct -this week # or day, month, quarter, year -next week -last week -@end example - -The beginning and ending can be given at the same time, if it spans a -single period. In that case, just use @var{SPEC} by itself. In that -case, the period @samp{oct}, for example, will cover all the days in -october. The possible forms are: - -@example -<SPEC> -in <SPEC> -@end example - -Here are a few examples of period expressions: - -@example -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 -@end example - -@node Format strings, Value expressions, Period expressions, Quick Reference -@section Format strings - -Format strings may be used to change the output format of reports. -They are specified by passing a formatting string to the -@option{--format} (@option{-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. - -Within a format strings, a substitution is specified using a percent -character (@samp{%}). The basic format of all substitutions is: - -@example -%[-][MIN WIDTH][.MAX WIDTH]EXPR -@end example - -If the optional minus sign (@samp{-}) 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: - -@example -%-P a transaction's payee, left justified -%20P The same, right justified, at least 20 chars wide -%.20P The same, no more than 20 chars wide -%-.20P Left justified, maximum twenty chars wide -@end example - -The expression following the format constraints can be a single -letter, or an expression enclosed in parentheses or brackets. The -allowable expressions are: - -@table @code -@item % -Inserts a percent sign. - -@item t -Inserts the results of the value expression specified by @option{-t}. -If @option{-t} was not specified, the current report style's value -expression is used. - -@item T -Inserts the results of the value expression specified by @option{-T}. -If @option{-T} was not specified, the current report style's value -expression is used. - -@item | -Inserts a single space. This is useful if a width is specified, for -inserting a certain number of spaces. - -@item _ -Inserts a space for each level of an account's depth. That is, if an -account has two parents, this construct will insert two spaces. If a -minimum width is specified, that much space is inserted for each level -of depth. Thus @samp{%5_}, for an account with four parents, will -insert twenty spaces. - -@item (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 @samp{%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. - -@item [DATEFMT] -Inserts the result of formatting a posting's date with a date -format string, exactly like those supported by @code{strftime}. For -example: @samp{%[%Y/%m/%d %H:%M:%S]}. - -@item S -Insert the pathname of the file from which the transaction's data was read. - -@item B -Inserts the beginning character position of that transaction within the file. - -@item b -Inserts the beginning line of that transaction within the file. - -@item E -Inserts the ending character position of that transaction within the file. - -@item e -Inserts the ending line of that transaction within the file. - -@item D -By default, this is the same as @samp{%[%Y/%m%/d]}. The date format -used can be changed at any time with the @option{-y} flag, however. -Using @samp{%D} gives the user more control over the way dates are -output. - -@item d -This is the same as the @samp{%D} option, unless the transaction has an -effective date, in which case it prints -@samp{[ACTUAL_DATE=EFFECTIVE_DATE]}. - -@item X -If a posting has been cleared, this inserts @samp{*} followed by a -space; otherwise nothing is inserted. - -@item Y -This is the same as @samp{%X}, except that it only displays a state -character if all of the member postings have the same state. - -@item C -Inserts the checking number for a transaction, in parentheses, followed by -a space; if none was specified, nothing is inserted. - -@item P -Inserts the payee related to a posting. - -@item a -Inserts the optimal short name for an account. This is normally used -in balance reports. It prints a parent account's name if that name -has not been printed yet, otherwise it just prints the account's name. - -@item A -Inserts the full name of an account. - -@item W -This is the same as @samp{%A}, except that it first displays the -posting's state @emph{if the transaction's posting states are not -all the same}, followed by the full account name. This is offered as -a printing optimization, so that combined with @samp{%Y}, only the -minimum amount of state detail is printed. - -@item o -Inserts the ``optimized'' form of a posting's amount. This is -used by the print report. In some cases, this inserts nothing; in -others, it inserts the posting amount and its cost. It's use is -not recommend unless you are modifying the print report. - -@item n -Inserts the note associated with a posting, preceded by two spaces -and a semi-colon, if it exists. Thus, no none becomes an empty -string, while the note @samp{foo} is substituted as @samp{ ; foo}. - -@item N -Inserts the note associated with a posting, if one exists. - -@item / -The @samp{%/} 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. -@end table - -@node Value expressions, File format, Format strings, Quick Reference -@section Value expressions - -Value expressions are an expression language used by Ledger to -calculate values used by the program for many different purposes: - -@enumerate -@item -The values displayed in reports -@item -For predicates (where truth is anything non-zero), to determine which -postings are calculated (@option{-l}) or displayed (@option{-d}). -@item -For sorting criteria, to yield the sort key. -@item -In the matching criteria used by automated postings. -@end enumerate - -Value expressions support most simple math and logic operators, in -addition to a set of one letter functions and variables. A function's -argument is whatever follows it. The following is a display predicate -that I use with the @command{balance} command: - -@example -ledger -d /^Liabilities/?T<0:UT>100 balance -@end example - -The effect is that account totals are displayed only if: 1) A -Liabilities account has a total less than zero; or 2) the absolute -value of the account's total exceeds 100 units of whatever commodity -contains. If it contains multiple commodities, only one of them must -exceed 100 units. - -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: - -@example -ledger -d "d>[this month]" register checking -@end example - -This advantage to 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: - -@example -ledger -b "this month" register checking -@end example - -@subsection Variables - -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. - -@table @code -@item t -This maps to whatever the user specified with @option{-t}. In a -register report, @option{-t} changes the value column; in a balance -report, it has no meaning by default. If @option{-t} was not -specified, the current report style's value expression is used. - -@item T -This maps to whatever the user specified with @option{-T}. In a -register report, @option{-T} changes the totals column; in a balance -report, this is the value given for each account. If @option{-T} was -not specified, the current report style's value expression is used. - -@item m -This is always the present moment/date. -@end table - -@subsubsection Posting/account details - -@table @code -@item d -A posting's date, as the number of seconds past the epoch. This -is always ``today'' for an account. - -@item a -The posting's amount; the balance of an account, without -considering children. - -@item b -The cost of a posting; the cost of an account, without its -children. - -@item v -The market value of a posting, or an account without its children. - -@item g -The net gain (market value minus cost basis), for a posting or an -account without its children. It is the same as @samp{v-b}. - -@item l -The depth (``level'') of an account. If an account has one parent, -it's depth is one. - -@item n -The index of a posting, or the count of postings affecting an -account. - -@item X -1 if a posting's transaction has been cleared, 0 otherwise. - -@item R -1 if a posting is not virtual, 0 otherwise. - -@item Z -1 if a posting is not automated, 0 otherwise. -@end table - -@subsubsection Calculated totals - -@table @code -@item O -The total of all postings seen so far, or the total of an account -and all its children. - -@item N -The total count of postings affecting an account and all its -children. - -@item B -The total cost of all postings seen so far; the total cost of an -account and all its children. - -@item V -The market value of all postings seen so far, or of an account and -all its children. - -@item G -The total net gain (market value minus cost basis), for a series of -postings, or an account and its children. It is the same as -@samp{V-B}. -@end table - -@subsection Functions - -The available one letter functions are: - -@table @code -@item - -Negates the argument. - -@item U -The absolute (unsigned) value of the argument. - -@item S -Strips the commodity from the argument. - -@item A -The arithmetic mean of the argument; @samp{Ax} is the same as -@samp{x/n}. - -@item P -The present market value of the argument. The syntax @samp{P(x,d)} is -supported, which yields the market value at time @samp{d}. If no date -is given, then the current moment is used. -@end table - -@subsection Operators - -The binary and ternary operators, in order of precedence, are: - -@enumerate -@item @samp{* /} -@item @samp{+ -} -@item @samp{! < > =} -@item @samp{& | ?:} -@end enumerate - -@subsection Complex expressions - -More complicated expressions are possible using: - -@table @code -@item NUM -A plain integer represents a commodity-less amount. - -@item @{AMOUNT@} -An amount in braces can be any kind of amount supported by ledger, -with or without a commodity. Use this for decimal values. - -@item /REGEXP/ -@item W/REGEXP/ -A regular expression that matches against an account's full name. If -a posting, this will match against the account affected by the -posting. - -@item //REGEXP/ -@item p/REGEXP/ -A regular expression that matches against a transaction's payee name. - -@item ///REGEXP/ -@item w/REGEXP/ -A regular expression that matches against an account's base name. If -a posting, this will match against the account affected by the -posting. - -@item c/REGEXP/ -A regular expression that matches against the transaction code (the text -that occurs between parentheses before the payee name). - -@item e/REGEXP/ -A regular expression that matches against a posting's note, or -comment field. - -@item (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. - -@item [DATE] -Useful specifying a date in plain terms. For example, you could say -@samp{[2004/06/01]}. -@end table - -@node File format, , Value expressions, Quick Reference -@section File format - -The ledger file format is quite simple, but also very flexible. It -supports many options, though typically the user can ignore most of -them. They are summarized below. - -The initial character of each line determines what the line means, and -how it should be interpreted. Allowable initial characters are: - -@table @code -@item NUMBER -A line beginning with a number denotes a transaction. It may be followed -by any number of lines, each beginning with whitespace, to denote the -transaction's account postings. The format of the first line is: - -@example -DATE[=EDATE] [*|!] [(CODE)] DESC -@end example - -If @samp{*} appears after the date (with optional effective date), it -indicates the transaction is ``cleared'', which can mean whatever the user -wants it to mean. If @samp{!} appears after the date, it indicates d -the transaction is ``pending''; i.e., tentatively cleared from the user's -point of view, but not yet actually cleared. If a @samp{CODE} appears -in parentheses, it may be used to indicate a check number, or the type -of the posting. Following these is the payee, or a description of -the posting. - -The format of each following posting is: - -@example - ACCOUNT AMOUNT [; NOTE] -@end example - -Note that there must be at least two spaces between @samp{ACCOUNT} and -@samp{AMOUNT}. The @samp{ACCOUNT} may be surrounded by parentheses if it -is a virtual posting or square brackets if it is a virtual posting that -must balance. The @samp{AMOUNT} can be followed by a per-unit -posting cost, by specifying @samp{@@ AMOUNT}, or a complete -posting cost with @samp{@@@@ AMOUNT}. Lastly, the @samp{NOTE} may -specify an actual and/or effective date for the posting by using -the syntax @samp{[ACTUAL_DATE]} or @samp{[=EFFECTIVE_DATE]} or -@samp{[ACTUAL_DATE=EFFECtIVE_DATE]}. - -@item = -An automated transaction. A value expression must appear after the equal -sign. - -After this initial line there should be a set of one or more -postings, just as if it were normal transaction. If the amounts of the -postings have no commodity, they will be applied as modifiers to -whichever real posting is matched by the value expression. - -@item ~ -A period transaction. A period expression must appear after the tilde. - -After this initial line there should be a set of one or more -postings, just as if it were normal transaction. - -@item ! -A line beginning with an exclamation mark denotes a command directive. -It must be immediately followed by the command word. The supported -commands are: - -@table @samp -@item !include -Include the stated ledger file. - -@item !account -The account name is given is taken to be the parent of all -postings that follow, until @samp{!end} is seen. - -@item !end -Ends an account block. -@end table - -@item ; -A line beginning with a colon indicates a comment, and is ignored. - -@item Y -If a line begins with a capital Y, it denotes the year used for all -subsequent transactions that give a date without a year. The year should -appear immediately after the Y, for example: @samp{Y2004}. This is -useful at the beginning of a file, to specify the year for that file. -If all transactions specify a year, however, this command has no effect. - -@item P -Specifies a historical price for a commodity. These are usually found -in a pricing history file (see the @option{-Q} option). The syntax -is: -@example -P DATE SYMBOL PRICE -@end example - -@item N SYMBOL -Indicates that pricing information is to be ignored for a given -symbol, nor will quotes ever be downloaded for that symbol. Useful -with a home currency, such as the dollar ($). It is recommended that -these pricing options be set in the price database file, which -defaults to @file{~/.pricedb}. The syntax for this command is: -@example -N SYMBOL -@end example - -@item D AMOUNT -Specifies the default commodity to use, by specifying an amount in the -expected format. The @command{transaction} command will use this commodity -as the default when none other can be determined. This command may be -used multiple times, to set the default flags for different -commodities; whichever is seen last is used as the default commodity. -For example, to set US dollars as the default commodity, while also -setting the thousands flag and decimal flag for that commodity, use: -@example -D $1,000.00 -@end example - -@item C AMOUNT1 = AMOUNT2 -Specifies a commodity conversion, where the first amount is given to -be equivalent to the second amount. The first amount should use the -decimal precision desired during reporting: -@example -C 1.00 Kb = 1024 bytes -@end example - -@item i, o, b, h -These four relate to timeclock support, which permits ledger to read -timelog files. See the timeclock's documentation for more info on the -syntax of its timelog files. -@end table - -@node Ledger Tutorial, Ledger in Practice, Quick Reference, Top -@chapter Ledger Tutorial - -This chapter presents a series of recipes, gradually introducing all of -the command-line features of Ledger. - -For the purpose of these examples, assume the environment variable -@var{LEDGER} is set to the file @file{sample.dat} (which is included -in the distribution), and that the contents of that file are: - -@smallexample -= /^Expenses:Books/ - (Liabilities:Taxes) -0.10 - -~ Monthly - Assets:Bank:Checking $500.00 - Income:Salary - -2004/05/01 * Checking balance - Assets:Bank:Checking $1,000.00 - Equity:Opening Balances - -2004/05/01 * Investment balance - Assets:Brokerage 50 AAPL @@ $30.00 - Equity:Opening Balances - -2004/05/14 * Pay day - Assets:Bank:Checking $500.00 - Income:Salary - -2004/05/27 Book Store - Expenses:Books $20.00 - Liabilities:MasterCard - -2004/05/27 (100) Credit card company - Liabilities:MasterCard $20.00 - Assets:Bank:Checking -@end smallexample - -This sample file demonstrates a basic principle of accounting which it -is recommended you follow: Keep all of your accounts under five parent -Assets, Liabilities, Income, Expenses and Equity. It is important to -do so in order to make sense out of the following examples. - -@section Checking balances - -Ledger has seven basic commands, but by far the most often used are -@command{balance} and @command{register}. To see a summary balance of -all accounts, use: - -@example -ledger bal -@end example - -@command{bal} is a short-hand for @command{balance}. This command -prints out the summary totals of the five parent accounts used in -@file{sample.dat}: - -@smallexample - $1,480.00 - 50 AAPL Assets - $-2,500.00 Equity - $20.00 Expenses - $-500.00 Income - $-2.00 Liabilities --------------------- - $-1,502.00 - 50 AAPL -@end smallexample - -None of the child accounts are shown, just the parent account totals. -We can see that in @samp{Assets} there is $1,480.00, and 50 shares of -Apple stock. There is also a negative grand total. Usually the grand -total is zero, which means that all accounts balance@footnote{It is -impossible for accounts not to balance in ledger; it reports an error -if a posting does not balance}. In this case, since the 50 shares -of Apple stock cost $1,500.00 dollars, then these two amounts balance -each other in the grand total. The extra $2.00 comes from a virtual -posting being added by the automatic transaction at the top of the file. -The transaction is virtual because the account name was surrounded by -parentheses in an automatic transaction. Automatic transactions will be -discussed later, but first let's remove the virtual posting from -the balance report by using the @option{--real} option: - -@example -ledger --real bal -@end example - -Now the report is: - -@smallexample - $1,480.00 - 50 AAPL Assets - $-2,500.00 Equity - $20.00 Expenses - $-500.00 Income --------------------- - $-1,500.00 - 50 AAPL -@end smallexample - -Since the liability was a virtual posting, it has dropped from the -report and we see that the final total is balanced. - -But we only know that it balances because @file{sample.dat} is quite -simple, and we happen to know that the 50 shares of Apple stock cost -$1,500.00. We can verify that things really balance by reporting the -Apple shares in terms of their cost, instead of their quantity. To do -this requires the @option{--basis}, or @option{-B}, option: - -@example -ledger --real -B bal -@end example - -This command reports: - -@smallexample - $2,980.00 Assets - $-2,500.00 Equity - $20.00 Expenses - $-500.00 Income -@end smallexample - -With the basis cost option, the grand total has disappeared, as it is -now zero. The confirms that the cost of everything balances to zero, -@emph{which must always be true}. Reporting the real basis cost -should never yield a remainder@footnote{If it ever does, then -generated postings are involved, which can be removed using -@option{--actual}}. - -@subsection Sub-account balances - -The totals reported by the balance command are only the topmost parent -accounts. To see the totals of all child accounts as well, use the -@option{-s} option: - -@example -ledger --real -B -s bal -@end example - -This reports: - -@smallexample - $2,980.00 Assets - $1,480.00 Bank:Checking - $1,500.00 Brokerage - $-2,500.00 Equity:Opening Balances - $20.00 Expenses:Books - $-500.00 Income:Salary -@end smallexample - -This shows that the @samp{Assets} total is made up from two child -accounts, but that the total for each of the other accounts comes from -one child account. - -Sometimes you may have a lot of children, nested very deeply, but only -want to report the first two levels. This can be done with a display -predicate, using a value expression. In the value expression, -@code{T} represents the reported total, and @code{l} is the display -level for the account: - -@example -ledger --real -B -d "T&l<=2" bal -@end example - -This reports: - -@smallexample - $2,980.00 Assets - $1,480.00 Bank - $1,500.00 Brokerage - $-2,500.00 Equity:Opening Balances - $20.00 Expenses:Books - $-500.00 Income:Salary -@end smallexample - -Instead of reporting @samp{Bank:Checking} as a child of @samp{Assets}, -it report only @samp{Bank}, since that account is a nesting level of -2, while @samp{Checking} is at level 3. - -To review the display predicate used---@code{T&l<=2}---this rather -terse expression means: Display an account only if it has a non-zero -total (@code{T}), and its nesting level is less than or equal to 2 -(@code{l<=2}). - -@subsection Specific account balances - -While reporting the totals for all accounts can be useful, most often -you will want to check the balance of a specific account or accounts. -To do this, put one or more account names after the balance command. -Since these names are really regular expressions, you can use partial -names if you wish: - -@example -ledger bal checking -@end example - -Reports: - -@smallexample - $1,480.00 Assets:Bank:Checking -@end smallexample - -Any number of names may be used: - -@example -ledger bal checking broker liab -@end example - -Reports: - -@smallexample - $1,480.00 Assets:Bank:Checking - 50 AAPL Assets:Brokerage - $-2.00 Liabilities -@end smallexample - -In this case no grand total is reported, because you are asking for -specific account balances. - -For those comfortable with regular expressions, any Perl regexp is -allowed: - -@example -ledger bal ^assets.*checking ^liab -@end example - -Reports: - -@smallexample - $1,480.00 Assets:Bank:Checking - $-2.00 Liabilities:Taxes -@end smallexample - -@section The register report - -While the @command{balance} command can be very handy for checking -account totals, by far the most powerful of Ledger's reporting tools -is the @command{register} command. In fact, internally both commands -use the same logic, but report the results differently: -@command{balance} shows the summary totals, while @command{register} -reports each posting and how it contributes to that total. - -Paradoxically, the most basic form of @command{register} is almost -never used, since it displays every posting: - -@example -ledger reg -@end example - -@command{reg} is a short-hand for @command{register}. This command -reports: - -@smallexample -2004/05/01 Checking balance Assets:Bank:Checking $1,000.00 $1,000.00 - Equity:Opening Balan.. $-1,000.00 0 -2004/05/01 Investment balance Assets:Brokerage 50 AAPL 50 AAPL - Equity:Opening Balan.. $-1,500.00 $-1,500.00 - 50 AAPL -2004/05/14 Pay day Assets:Bank:Checking $500.00 $-1,000.00 - 50 AAPL - Income:Salary $-500.00 $-1,500.00 - 50 AAPL -2004/05/27 Book Store Expenses:Books $20.00 $-1,480.00 - 50 AAPL - Liabilities:MasterCard $-20.00 $-1,500.00 - 50 AAPL - (Liabilities:Taxes) $-2.00 $-1,502.00 - 50 AAPL -2004/05/27 Credit card company Liabilities:MasterCard $20.00 $-1,482.00 - 50 AAPL - Assets:Bank:Checking $-20.00 $-1,502.00 - 50 AAPL -@end smallexample - -This rather verbose output shows every account posting in -@file{sample.dat}, and how it affects the running total. The final -total is identical to what we saw with the plain @command{balance} -command. To see how things really balance, we can use @samp{--real --B}, just as we did with @command{balance}: - -@example -ledger --real -B reg -@end example - -Reports: - -@smallexample -2004/05/01 Checking balance Assets:Bank:Checking $1,000.00 $1,000.00 - Equity:Opening Balan.. $-1,000.00 0 -2004/05/01 Investment balance Assets:Brokerage $1,500.00 $1,500.00 - Equity:Opening Balan.. $-1,500.00 0 -2004/05/14 Pay day Assets:Bank:Checking $500.00 $500.00 - Income:Salary $-500.00 0 -2004/05/27 Book Store Expenses:Books $20.00 $20.00 - Liabilities:MasterCard $-20.00 0 -2004/05/27 Credit card company Liabilities:MasterCard $20.00 $20.00 - Assets:Bank:Checking $-20.00 0 -@end smallexample - -Here we see that everything balances to zero in the end, as it must. - -@subsection Specific register queries - -The most common use of the register command is to summarize -postings based on the account(s) they affect. Using -@file{sample.dat} as as example, we could look at all book purchases -using: - -@example -ledger reg books -@end example - -Reports: - -@smallexample -2004/05/29 Book Store Expenses:Books $20.00 $20.00 -@end smallexample - -If a double-dash (@samp{--}) occurs in the list of regular -expressions, any following arguments are matched against payee names, -instead of account names: - -@example -ledger reg ^liab -- credit -@end example - -Reports: - -@smallexample -2004/05/29 Credit card company Liabilities:MasterCard $20.00 $20.00 -@end smallexample - -There are many reporting options for tailoring which postings are -found, and also how to summarize the various amounts and totals that -result. These are plumbed in greater depth below. - -@section Selecting postings - -Although the easiest way to use the register is to report all the -postings affecting a set of accounts, it can often result in more -information than you want. To cope with an ever-growing amount of -data, there are several options which can help you pinpoint your -report to include just the postings that interest you most. This is -called the ``calculation'' phase of Ledger. All of its related -options are documented under @option{--help-calc}. - -@subsection By date - -@c -c, --current show only current and past transactions (not future) - -@option{--current}(@option{-c}) displays transactions occurring on or -before the current date. Any transaction recorded for a future date will be -ignored, as if it had not been seen. This is useful if you happen to -pre-record transactions, but still wish to view your balances in terms of -what is available today. - -@c -b, --begin DATE set report begin date -@c -e, --end DATE set report end date - -@option{--begin DATE} (@option{-b DATE}) limits the report to only -those transactions occurring on or after @var{DATE}. The running total in -the register will start at zero with the first posting, even if -there are earlier transactions. - -To limit the display only, but still add earlier postings to the -running total, use the display expression @samp{-d 'd>=[DATE]'}): - -@example -ledger --basis -b may -d 'd>=[5/14]' reg ^assets -@end example - -Reports: - -@smallexample -2004/05/14 Pay day Assets:Bank:Checking $500.00 $3,000.00 -2004/05/27 Credit card company Assets:Bank:Checking $-20.00 $2,980.00 -@end smallexample - -In this example, the displayed postings start from @samp{5/14}, -but the calculated total starts from the beginning of @samp{may}. - -@option{--end DATE} (@option{-e DATE}) states when reporting should -end, both calculation and display. The ending date is inclusive. - -The @var{DATE} argument to the @option{-b} and @option{-e} options can -be rather flexible. Assuming the current date to be November 15, -2004, then all of the following are equivalent: - -@example -ledger -b oct bal -ledger -b "this oct" bal -ledger -b 2004/10 bal -ledger -b 10 bal -ledger -b last bal -ledger -b "last month" bal -@end example - -@c -p, --period STR report using the given period -@c --period-sort EXPR sort each report period's transactions by EXPR - -To constrain the report to a specific time period, use -@option{--period} (@option{-p}). A time period may have both a -beginning and an end, or neither, as well as a specified interval. -Here are a few examples: - -@example -ledger -p 2004 bal -ledger -p august bal -ledger -p "from aug to oct" bal -ledger -p "daily from 8/1 to 8/15" bal -ledger -p "weekly since august" bal -ledger -p "monthly from feb to oct" bal -ledger -p "quarterly in 2004" bal -ledger -p yearly bal -@end example - -See @ref{Period expressions} for more on syntax. Also, all of the -options @option{-b}, @option{-e} and @option{-p} may be used together, -but whatever information occurs last takes priority. An example of -such usage (in a script, perhaps) would be: - -@example -ledger -b 2004 -e 2005 -p monthly reg ^expenses -@end example - -This command is identical to: - -@example -ledger -p "monthly in 2004" reg ^expenses -@end example - -The postings within a period may be sorted using -@option{--period-sort}, which takes a value expression. This is -similar to the @option{--sort} option, except that it sorts within -each period transaction, rather than sorting all postings in the report. -See the documentation on @option{--sort} below for more details. - -@subsection By status - -By default, all regular postings are included in each report. To -limit the report to certain kinds of postings, use one or more of -the following options: - -@table @option -@item -C, --cleared -Consider only cleared postings. -@item -U, --uncleared -Consider only uncleared and pending postings. -@item -R, --real -Consider only real (non-virtual) postings. -@item -L, --actual -Consider only actual (non-automated) postings. -@end table - -Cleared postings are indicated by an asterix placed just before -the payee name in a posting. The meaning of this flag is up to -the user, but typically it means that a transaction has been seen on a -financial statement. Pending postings use an exclamation mark in -the same position, but are mainly used only by reconciling software. -Uncleared postings are for things like uncashed checks, credit -charges that haven't appeared on a statement yet, etc. - -Real postings are all non-virtual postings, where the account -name is not surrounded by parentheses or square brackets. Virtual -postings are useful for showing a transfer of money that never -really happened, like money set aside for savings without actually -transferring it from the parent account. - -Actual postings are those not generated, either as part of an -automated transaction, or a budget or forecast report. A useful of when you -might like to filter out generated postings is with a budget: - -@example -ledger --budget --actual reg ^expenses -@end example - -This command outputs all postings affecting a budgeted account, -but without subtracting the budget amount (because the generated -postings are suppressed with @option{--actual}). The report shows -how much you actually spent on budgeted items. - -@subsection By relationship - -@c -r, --related calculate report using related postings - -Normally, a register report includes only the postings that match -the regular expressions specified after the command word. For -example, to report all expenses: - -@example -ledger reg ^expenses -@end example - -This reports: - -@smallexample -2004/05/29 Book Store Expenses:Books $20.00 $20.00 -@end smallexample - -Using @option{--related} (@option{-r}) reports the postings that -did not match your query, but only in transactions that otherwise would -have matched. This has the effect of indicating where money came -from, or when to: - -@example -ledger -r reg ^expenses -@end example - -Reports: - -@smallexample -2004/05/29 Book Store Liabilities:MasterCard $20.00 $20.00 -@end smallexample - -@subsection By budget - -@c --budget generate budget transactions based on FILE - -There is more information about budgeting and forecasting in -@ref{Budgeting and forecasting}. Basically, if you have any period -transactions in your ledger file, you can use these options. A period -transaction looks like: - -@example -~ Monthly - Assets:Bank:Checking $500.00 - Income:Salary -@end example - -The difference from a regular transaction is that the first line begins with -a tilde (~), and instead of a payee there's a period expression -(@ref{Period expressions}). Otherwise, a period transaction is in every -other way the same as a regular transaction. - -With such a transaction in your ledger file, the @option{--budget} option -will report only postings that match a budgeted account. Using -@file{sample.dat} from above: - -@example -ledger --budget reg ^income -@end example - -Reports: - -@smallexample -2004/05/01 Budget transaction Income:Salary $500.00 $500.00 -2004/05/14 Pay day Income:Salary $-500.00 0 -@end smallexample - -The final total is zero, indicating that the budget matched exactly -for the reported period. Budgeting is most often helpful with period -reporting; for example, to show monthly budget results use -@option{--budget -p monthly}. - -@c --add-budget show all postings plus the budget -@c --unbudgeted show only unbudgeted postings - -The @option{--add-budget} option reports all matching postings in -addition to budget postings; while @option{--unbudgeted} shows -only those that don't match a budgeted account. To summarize: - -@table @option -@item --budget -Show postings matching budgeted accounts. -@item --unbudgeted -Show postings matching unbudgeted accounts. -@item --add-budget -Show both budgeted and unbudgeted postings together (i.e., add the -generated budget postings to the regular report). -@end table - -@c --forecast EXPR generate forecast transactions while EXPR is true - -A report with the @option{--forecast} option will add budgeted -postings while the specified value expression is true. For -example: - -@example -ledger --forecast 'd<[2005] reg ^income -@end example - -Reports: - -@smallexample -2004/05/14 Pay day Income:Salary $-500.00 $-500.00 -2004/12/01 Forecast transaction Income:Salary $-500.00 $-1,000.00 -2005/01/01 Forecast transaction Income:Salary $-500.00 $-1,500.00 -@end smallexample - -The date this report was made was November 5, 2004; the reason the -first forecast transaction is in December is that forecast transactions are only -added for the future, and they only stop after the value expression -has matched at least once, which is why the January transaction appears. A -forecast report can be very useful for determining when money will run -out in an account, or for projecting future cash flow: - -@example -ledger --forecast 'd<[2008]' -p yearly reg ^inc ^exp -@end example - -This reports balances projected income against projected expenses, -showing the resulting total in yearly intervals until 2008. For the -case of @file{sample.dat}, which has no budgeted expenses, the result -of the above command (in November 2004) is: - -@smallexample -2004/01/01 - 2004/12/31 Income:Salary $-1,000.00 $-1,000.00 - Expenses:Books $20.00 $-980.00 -2005/01/01 - 2005/12/31 Income:Salary $-6,000.00 $-6,980.00 -2006/01/01 - 2006/12/31 Income:Salary $-6,000.00 $-12,980.00 -2007/01/01 - 2007/12/31 Income:Salary $-6,000.00 $-18,980.00 -2008/01/01 - 2008/01/01 Income:Salary $-500.00 $-19,480.00 -@end smallexample - -@subsection By value expression - -@c -l, --limit EXPR calculate only postings matching EXPR - -Value expressions can be quite complex, and are treated more fully in -@ref{Value expressions}. They can be used for limiting a report with -@option{--limit} (@option{-l}). The following command report income -since august, but expenses since october: - -@example -ledger -l '(/income/&d>=[aug])|(/expenses/&d>=[oct])' reg -@end example - -The basic form of this value expression is @samp{(A&B)|(A&B)}. The -@samp{A} in each part matches against an account name with -@samp{/name/}, while each @samp{B} part compares the date of the -posting (@samp{d}) with a specified month. The resulting report -will contain only postings which match the value expression. - -@c -t, --amount EXPR use EXPR to calculate the displayed amount -@c -T, --total EXPR use EXPR to calculate the displayed total - -Another use of value expressions is to calculate the amount reported -for each line of a register report, or for computing the subtotal of -each account shown in a balance report. This example divides each -posting amount by two: - -@example -ledger -t 'a/2' reg ^exp -@end example - -The @option{-t} option doesn't affect the running total, only how the -posting amount is displayed. To change the running total, use -@option{-T}. In that case, you will likely want to use the total -(@samp{O}) instead of the amount (@samp{a}): - -@example -ledger -T 'O/2' reg ^exp -@end example - -@section Massaging register output - -Even after filtering down your data to just the postings you're -interested in, the default reporting method of one posting per -line is often still too much. To combat this complexity, it is -possible to ask Ledger to report the details to you in many different -forms, summarized in various ways. This is the ``display'' phase of -Ledger, and is documented under @option{--help-disp}. - -@subsection Summarizing - -@c -n, --collapse register: collapse transactions with multiple postings - -When multiple postings relate to a single transaction, they are reported -as part of that transaction. For example, in the case of @file{sample.dat}: - -@example -ledger reg -- book -@end example - -Reports: - -@smallexample -2004/05/29 Book Store Expenses:Books $20.00 $20.00 - Liabilities:MasterCard $-20.00 0 - (Liabilities:Taxes) $-2.00 $-2.00 -@end smallexample - -All three postings are part of one transaction, and as such the transaction -details are printed only once. To report every transaction on a single -line, use @option{-n} to collapse transactions with multiple postings: - -@example -ledger -n reg -- book -@end example - -Reports: - -@smallexample -2004/05/29 Book Store <Total> $-2.00 $-2.00 -@end smallexample - -In the balance report, @option{-n} causes the grand total not to be -displayed at the bottom of the report. - -@c -s, --subtotal balance: show sub-accounts; other: show subtotals - -If an account occurs more than once in a report, it is possible to -combine them all and report the total per-account, using @option{-s}. -For example, this command: - -@example -ledger -B reg ^assets -@end example - -Reports: - -@smallexample -2004/05/01 Checking balance Assets:Bank:Checking $1,000.00 $1,000.00 -2004/05/01 Investment balance Assets:Brokerage $1,500.00 $2,500.00 -2004/05/14 Pay day Assets:Bank:Checking $500.00 $3,000.00 -2004/05/27 Credit card company Assets:Bank:Checking $-20.00 $2,980.00 -@end smallexample - -But if the @option{-s} option is added, the result becomes: - -@smallexample -2004/05/01 - 2004/05/29 Assets:Bank:Checking $1,480.00 $1,480.00 - Assets:Brokerage $1,500.00 $2,980.00 -@end smallexample - -When account subtotaling is used, only one transaction is printed, and the -date and name reflect the range of the combined postings. - -@c -P, --by-payee show summarized totals by payee - -With @option{-P}, postings relating to the same payee are -combined. In this case, the date of the combined transaction is that of the -latest posting. - -@c -x, --comm-as-payee set commodity name as the payee, for reporting - -@option{-x} changes the payee name for each posting to be the same -as the commodity it uses. This can be especially useful combined with -other options, like @option{-P}. For example: - -@example -ledger -Px reg ^assets -@end example - -Reports: - -@smallexample -2004/05/29 $ Assets:Bank:Checking $1,480.00 $1,480.00 -2004/05/01 AAPL Assets:Brokerage 50 AAPL $1,480.00 - 50 AAPL -@end smallexample - -This reports shows the subtotal for each commodity held, and where it -is located. To see the basis cost, or initial investment, add -@option{-B}. Applied to the example above: - -@smallexample -2004/05/29 $ Assets:Bank:Checking $1,480.00 $1,480.00 -2004/05/01 AAPL Assets:Brokerage $1,500.00 $2,980.00 -@end smallexample - -@c -E, --empty balance: show accounts with zero balance - -The only other options which affect summarized totals is @option{-E}, -which works only in the balance report. In this case, it shows -matching accounts with a zero a balance, which are ordinarily -excluded. This can be useful to see all the accounts involved in a -report, even if some have no total. - -@subsection Quick periods - -Although the @option{-p} option (also @option{--period}) is much more -versatile, there are other options to make the most common period -reports easier: - -@table @option -@item -W, --weekly -Show weekly sub-totals. Same as @samp{-p weekly}. -@item -M, --monthly -Show monthly sub-totals. Same as @samp{-p monthly}. -@item -Y, --yearly -Show yearly sub-totals. Same as @samp{-p yearly}. -@end table - -@c --dow show a days-of-the-week report - -There is one kind of period report that cannot be done with -@option{-p}. This is the @option{--dow}, or ``days of the week'' -report, which shows summarized totals for each day of the week. The -following examples shows a ``day of the week'' report of income and -expenses: - -@example -ledger --dow reg ^inc ^exp -@end example - -Reports: - -@smallexample -2004/05/27 Thursdays Expenses:Books $20.00 $20.00 -2004/05/14 Fridays Income:Salary $-500.00 $-480.00 -@end smallexample - -@subsection Ordering and width - -@c -S, --sort EXPR sort report according to the value expression EXPR - -The postings displayed in a report are shown in the same order as -they appear in the ledger file. To change the order and sort a -report, use the @option{--sort} option. @option{--sort} takes a value -expression to determine the value to sort against, making it possible -to sort according to complex criteria. Here are some simple and -useful examples: - -@example -ledger --sort d reg ^exp # sort by date -ledger --sort t reg ^exp # sort by amount total -ledger --sort -t reg ^exp # reverse sort by amount total -ledger --sort Ut reg ^exp # sort by abs amount total -@end example - -For the balance report, you will want to use @samp{T} instead of -@samp{t}: - -@example -ledger --sort T reg ^exp # sort by amount total -ledger --sort -T reg ^exp # reverse sort by amount total -ledger --sort UT reg ^exp # sort by abs amount total -@end example - -The @option{--sort} options sorts all postings in a report. If -periods are used (such as @option{--monthly}), this can get somewhat -confusing. In that case, you'll probably want to sort within periods -using @option{--period-sort} instead of @option{--sort}. - -@c -w, --wide for the default register report, use 132 columns - -And if the register seems too cramped, and you have a lot of screen -real estate, you can use @option{-w} to format the report within 132 -acolumns, instead of 80. You are more likely then to see full payee -and account names, as well as properly formatted totals when -long-named commodities are used. - -If you want only the first or last N transactions to be printed---which can -be very useful for viewing the last 10 transactions in your checking -account, while also showing the cumulative balance from all -transactions---use the @option{--head} and/or @option{--tail} options. The -two options may be used simultaneously, for example: - -@example -ledger --tail 20 reg checking -@end example - -If the output from your command is very long, Ledger can output the -data to a pager utility, such as @command{more} or @command{less}: - -@example -ledger --pager /usr/bin/less reg checking -@end example - -@subsection Averages and percentages - -@c -A, --average report average posting amount - -To see the running total changed to a running average, use -@option{-A}. The final posting's total will be the overall -average of all displayed postings. The works in conjunction with -period reporting, so that you can see your monthly average expenses -with: - -@example -ledger -AM reg ^expenses:food -ledger -AMn reg ^expenses -@end example - -This works in the balance report too: - -@example -ledger -AM bal ^expenses:food -ledger -AMs bal ^expenses -@end example - -@c -D, --deviation report deviation from the average - -The @option{-D} option changes the running average into a deviation -from the running average. This only makes sense in the register -report, however. - -@example -ledger -DM reg ^expenses:food -@end example - -@c -%, --percentage report balance totals as a percentile of the parent - -In the balance report only, @option{-%} changes the reported totals -into a percentage of the parent account. This kind of report is -confusing if negative amounts are involved, and doesn't work at all if -multiple commodities occur in an account's history. It has a somewhat -limited usefulness, therefore, but in certain cases it can be handy, -such as reviewing overall expenses: - -@example -ledger -%s -S T bal ^expenses -@end example - -@subsection Reporting total data - -@c --totals in the "xml" report, include running total - -Normally in the @command{xml} report, only posting amounts are -printed. To include the running total under a @samp{<total>} tag, use -@option{--totals}. This does not affect any other report. - -@c -j, --amount-data print only raw amount data (useful for scripting) -@c -J, --total-data print only raw total data - -In the register report only, the output can be changed with -@option{-j} to show only the date and the amount---without -commodities. This only makes sense if a single commodity appears in -the report, but can be quite useful for scripting, or passing the data -to Gnuplot. To show only the date and running total, use @option{-J}. - -@subsection Display by value expression - -@c -d, --display EXPR display only postings matching EXPR - -With @option{-d} you can decide which postings (or accounts in the -balance report) are displayed, according to a value expression. The -computed total is not affected, only the display. This can be very -useful for shortening a report without changing the running total: - -@example -ledger -d 'd>=[last month]' reg checking -@end example - -This command shows the checking account's register, beginning from -last month, but with the running total reflecting the entire history -of the account. - -@subsection Change report format - -@c -y, --date-format STR use STR as the date format (default: %Y/%m/%d) - -When dates are printed in any report, the default format is -@samp{%Y/%m/%d}, which yields dates of the form @samp{YYYY/mm/dd}. -This can be changed with @option{-y}, whose argument is a -@code{strftime} string---see your system's C library documentation for -the allowable codes. Mostly you will want to use @samp{%Y}, @samp{%m} -and @samp{%d}, in whatever combination is convenient for your locale. - -@c -F, --format STR use STR as the format; for each report type, use: -@c --balance-format --register-format --print-format -@c --plot-amount-format --plot-total-format --equity-format -@c --prices-format --wide-register-format - -To change the format of the entire reported line, use @option{-F}. It -supports quite a large number of options, which are all documented in -@ref{Format strings}. In addition, each specific kind of report -(except for @command{xml}) can be changed using one of the following -options: - -@table @option -@item --balance-format -@command{balance} report. Default: -@smallexample -%20T %2_%-a\n -@end smallexample - -@item --register-format -@command{register} report. Default: -@smallexample -%D %-.20P %-.22A %12.66t %12.80T\n%/%32|%-.22A %12.66t %12.80T\n -@end smallexample - -@item --print-format -@command{print} report. Default: -@smallexample -%D %-.35P %-.38A %22.108t %22.132T\n%/%48|%-.38A %22.108t %22.132T\n -@end smallexample - -@item --plot-amount-format -@command{register} report when @option{-j} (plot amount) is used. Default: -@smallexample -%D %(St)\n -@end smallexample - -@item --plot-total-format -@command{register} report when @option{-J} (plot total) is used. Default: -@smallexample -%D %(ST)\n -@end smallexample - -@item --equity-format -@command{equity} report. Default: -@smallexample -\n%D %Y%C%P\n %-34W %12o%n\n%/ %-34W %12o%n\n -@end smallexample - -@item --prices-format -@command{prices} report. Default: -@smallexample -\n%D %Y%C%P\n%/ %-34W %12t\n -@end smallexample - -@item --wide-register-format -@command{register} report when @option{-w} (wide) is used. Default: -@smallexample -%D %-.35P %-.38A %22.108t %22.132T\n%/%48|%-.38A %22.108t %22.132T\n -@end smallexample -@end table - -@section Standard queries - -If your ledger file uses the standard top-level accounts: Assets, -Liabilities, Income, Expenses, Equity: then the following queries will -enable you to generate some typical accounting reports from your data. - -Your @emph{net worth} can be determined by balancing assets against -liabilities: - -@example -ledger bal ^assets ^liab -@end example - -By removing long-term investment and loan accounts, you can see your -current net liquidity (or liquid net worth): - -@example -ledger bal ^assets ^liab -retirement -brokerage -loan -@end example - -Balancing expenses against income yields your @emph{cash flow}, or net -profit/loss: - -@example -ledger bal ^exp ^inc -@end example - -In this case, if the number is positive it means you spent more than -you earned during the report period. - -@c ---------------------------------------------------------------------- - -The most often used command is the ``balance'' command: - -@example -export LEDGER=/home/johnw/doc/ledger.dat -ledger balance -@end example - -Here I've set my Ledger environment variable to point to where my -ledger file is hiding. Thereafter, I needn't specify it again. - -@section Reporting balance totals - -The balance command prints out the summarized balances of all my -top-level accounts, excluding sub-accounts. In order to see the -balances for a specific account, just specify a regular expression -after the balance command: - -@example -ledger balance expenses:food -@end example - -This will show all the money that's been spent on food, since the -beginning of the ledger. For food spending just this month -(September), use: - -@example -ledger -p sep balance expenses:food -@end example - -Or maybe you want to see all of your assets, in which case the -s -(show sub-accounts) option comes in handy: - -@example -ledger -s balance ^assets -@end example - -To exclude a particular account, use a regular expression with a -leading minus sign. The following will show all expenses, but without -food spending: - -@example -ledger balance expenses -food -@end example - -@section Reporting percentages - -There is no built-in way to report posting amounts or account -balances in terms of percentages - -@node Ledger in Practice, , Ledger Tutorial, Top -@chapter Ledger in Practice - -@menu -* Stating where money goes:: -* Assets and Liabilities:: -* Typical queries:: -* Budgeting and forecasting:: -* Commodities and Currencies:: -* Accounts and Inventories:: -* Understanding Equity:: -* Dealing with Petty Cash:: -* Working with multiple funds and accounts:: -* Archiving previous years:: -* Virtual postings:: -* Automated postings:: -* Using Emacs to Keep Your Ledger:: -* Using GnuCash to Keep Your Ledger:: -* Using timeclock to record billable time:: -* Using XML:: -@end menu - -@node Stating where money goes, Assets and Liabilities, Ledger in Practice, Ledger in Practice -@section Stating where money goes - -Accountants will talk of ``credits'' and ``debits'', but the meaning -is often different from the layman's understanding. To avoid -confusion, Ledger uses only subtractions and additions, although the -underlying intent is the same as standard accounting principles. - -Recall that every posting will involve two or more accounts. -Money is transferred from one or more accounts to one or more other -accounts. To record the posting, an amount is @emph{subtracted} -from the source accounts, and @emph{added} to the target accounts. - -In order to write a Ledger transaction correctly, you must determine where -the money comes from and where it goes to. For example, when you are -paid a salary, you must add money to your bank account and also -subtract it from an income account: - -@smallexample -9/29 My Employer - Assets:Checking $500.00 - Income:Salary $-500.00 -@end smallexample - -Why is the Income a negative figure? When you look at the balance -totals for your ledger, you may be surprised to see that Expenses are -a positive figure, and Income is a negative figure. It may take some -getting used to, but to properly use a general ledger you must think -in terms of how money moves. Rather than Ledger ``fixing'' the minus -signs, let's understand why they are there. - -When you earn money, the money has to come from somewhere. Let's call -that somewhere ``society''. In order for society to give you an -income, you must take money away (withdraw) from society in order to -put it into (make a payment to) your bank. When you then spend that -money, it leaves your bank account (a withdrawal) and goes back to -society (a payment). This is why Income will appear negative---it -reflects the money you have drawn from society---and why Expenses will -be positive---it is the amount you've given back. These additions and -subtractions will always cancel each other out in the end, because you -don't have the ability to create new money: it must always come from -somewhere, and in the end must always leave. This is the beginning of -economy, after which the explanation gets terribly difficult. - -Based on that explanation, here's another way to look at your balance -report: every negative figure means that that account or person or -place has less money now than when you started your ledger; and every -positive figure means that that account or person or place has more -money now than when you started your ledger. Make sense? - -@node Assets and Liabilities, Typical queries, Stating where money goes, Ledger in Practice -@section Assets and Liabilities - -Assets are money that you have, and Liabilities are money that you -owe. ``Liabilities'' is just a more inclusive name for Debts. - -An Asset is typically increased by transferring money from an Income -account, such as when you get paid. Here is a typical transaction: - -@smallexample -2004/09/29 My Employer - Assets:Checking $500.00 - Income:Salary -@end smallexample - -Money, here, comes from an Income account belonging to ``My -Employer'', and is transferred to your checking account. The money is -now yours, which makes it an Asset. - -Liabilities track money owed to others. This can happen when you -borrow money to buy something, or if you owe someone money. Here is -an example of increasing a MasterCard liability by spending money with -it: - -@smallexample -2004/09/30 Restaurant - Expenses:Dining $25.00 - Liabilities:MasterCard -@end smallexample - -The Dining account balance now shows $25 spent on Dining, and a -corresponding $25 owed on the MasterCard---and therefore shown as -$-25.00. The MasterCard liability shows up as negative because it -offsets the value of your assets. - -The combined total of your Assets and Liabilities is your net worth. -So to see your current net worth, use this command: - -@example -ledger balance ^assets ^liabilities -@end example - -Relatedly, your Income accounts show up negative, because they -transfer money @emph{from} an account in order to increase your -assets. Your Expenses show up positive because that is where the -money went to. The combined total of Income and Expenses is your cash -flow. A positive cash flow means you are spending more than you make, -since income is always a negative figure. To see your current cash -flow, use this command: - -@example -ledger balance ^income ^expenses -@end example - -Another common question to ask of your expenses is: How much do I -spend each month on X? Ledger provides a simple way of displaying -monthly totals for any account. Here is an example that summarizes -your monthly automobile expenses: - -@example -ledger -M register expenses:auto -@end example - -This assumes, of course, that you use account names like -@samp{Expenses:Auto:Gas} and @samp{Expenses:Auto:Repair}. - -@subsection Tracking reimbursable expenses - -Sometimes you will want to spend money on behalf of someone else, -which will eventually get repaid. Since the money is still ``yours'', -it is really an asset. And since the expenditure was for someone -else, you don't want it contaminating your Expenses reports. You will -need to keep an account for tracking reimbursements. - -This is fairly easy to do in ledger. When spending the money, spend -it @emph{to} your Assets:Reimbursements, using a different account for -each person or business that you spend money for. For example: - -@smallexample -2004/09/29 Circuit City - Assets:Reimbursements:Company XYZ $100.00 - Liabilities:MasterCard -@end smallexample - -This shows $100.00 spent on a MasterCard at Circuit City, with the -expense was made on behalf of Company XYZ. Later, when Company XYZ -pays the amount back, the money will transfer from that reimbursement -account back to a regular asset account: - -@smallexample -2004/09/29 Company XYZ - Assets:Checking $100.00 - Assets:Reimbursements:Company XYZ -@end smallexample - -This deposits the money owed from Company XYZ into a checking account, -presumably because they paid the amount back with a check. - -But what to do if you run your own business, and you want to keep -track of expenses made on your own behalf, while still tracking -everything in a single ledger file? This is more complex, because you -need to track two separate things: 1) The fact that the money should -be reimbursed to you, and 2) What the expense account was, so that you -can later determine where your company is spending its money. - -This kind of posting is best handled with mirrored postings in -two different files, one for your personal accounts, and one for your -company accounts. But keeping them in one file involves the same -kinds of postings, so those are what is shown here. First, the -personal transaction, which shows the need for reimbursement: - -@smallexample -2004/09/29 Circuit City - Assets:Reimbursements:Company XYZ $100.00 - Liabilities:MasterCard -@end smallexample - -This is the same as above, except that you own Company XYZ, and are -keeping track of its expenses in the same ledger file. This transaction -should be immediately followed by an equivalent transaction, which shows the -kind of expense, and also notes the fact that $100.00 is now payable -to you: - -@smallexample -2004/09/29 Circuit City - Company XYZ:Expenses:Computer:Software $100.00 - Company XYZ:Accounts Payable:Your Name -@end smallexample - -This second transaction shows that Company XYZ has just spent $100.00 on -software, and that this $100.00 came from Your Name, which must be -paid back. - -These two transactions can also be merged, to make things a little clearer. -Note that all amounts must be specified now: - -@smallexample -2004/09/29 Circuit City - Assets:Reimbursements:Company XYZ $100.00 - Liabilities:MasterCard $-100.00 - Company XYZ:Expenses:Computer:Software $100.00 - Company XYZ:Accounts Payable:Your Name $-100.00 -@end smallexample - -To ``pay back'' the reimbursement, just reverse the order of -everything, except this time drawing the money from a company asset, -paying it to accounts payable, and then drawing it again from the -reimbursement account, and paying it to your personal asset account. -It's easier shown than said: - -@smallexample -2004/10/15 Company XYZ - Assets:Checking $100.00 - Assets:Reimbursements:Company XYZ $-100.00 - Company XYZ:Accounts Payable:Your Name $100.00 - Company XYZ:Assets:Checking $-100.00 -@end smallexample - -And now the reimbursements account is paid off, accounts payable is -paid off, and $100.00 has been effectively transferred from the -company's checking account to your personal checking account. The -money simply ``waited''---in both @samp{Assets:Reimbursements:Company -XYZ}, and @samp{Company XYZ:Accounts Payable:Your Name}---until such -time as it could be paid off. - -The value of tracking expenses from both sides like that is that you -do not contaminate your personal expense report with expenses made on -behalf of others, while at the same time making it possible to -generate accurate reports of your company's expenditures. It is more -verbose than just paying for things with your personal assets, but it -gives you a very accurate information trail. - -The advantage to keep these doubled transactions together is that they -always stay in sync. The advantage to keeping them apart is that it -clarifies the transfer's point of view. To keep the postings in -separate files, just separate the two transactions that were joined above. -For example, for both the expense and the pay-back shown above, the -following four transactions would be created. Two in your personal ledger -file: - -@smallexample -2004/09/29 Circuit City - Assets:Reimbursements:Company XYZ $100.00 - Liabilities:MasterCard $-100.00 - -2004/10/15 Company XYZ - Assets:Checking $100.00 - Assets:Reimbursements:Company XYZ $-100.00 -@end smallexample - -And two in your company ledger file: - -@smallexample -!account Company XYZ - -2004/09/29 Circuit City - Expenses:Computer:Software $100.00 - Accounts Payable:Your Name $-100.00 - -2004/10/15 Company XYZ - Accounts Payable:Your Name $100.00 - Assets:Checking $-100.00 - -!end -@end smallexample - -(Note: The @samp{!account} above means that all accounts mentioned in -the file are children of that account. In this case it means that all -activity in the file relates to Company XYZ). - -After creating these transactions, you will always know that $100.00 was -spent using your MasterCard on behalf of Company XYZ, and that Company -XYZ spent the money on computer software and paid it back about two -weeks later. - -@node Typical queries, Budgeting and forecasting, Assets and Liabilities, Ledger in Practice -@section Typical queries - -A query such as the following shows all expenses since last -October, sorted by total: - -@example -ledger -b "last oct" -s -S T bal ^expenses -@end example - -From left to right the options mean: Show transactions since October, 2003; -show all sub-accounts; sort by the absolute value of the total; and -report the balance for all expenses. - -@subsection Reporting monthly expenses - -The following query makes it easy to see monthly expenses, with each -month's expenses sorted by the amount: - -@example -ledger -M --period-sort t reg ^expenses -@end example - -Now, you might wonder where the money came from to pay for these -things. To see that report, add @option{-r}, which shows the -``related account'' postings: - -@example -ledger -M --period-sort t -r reg ^expenses -@end example - -But maybe this prints too much information. You might just want to -see how much you're spending with your MasterCard. That kind of query -requires the use of a display predicate, since the postings -calculated must match @samp{^expenses}, while the postings -displayed must match @samp{mastercard}. The command would be: - -@example -ledger -M -r -d /mastercard/ reg ^expenses -@end example - -This query says: Report monthly subtotals; report the ``related -account'' postings; display only related postings whose -account matches @samp{mastercard}, and base the calculation on -postings matching @samp{^expenses}. - -This works just as well for report the overall total, too: - -@example -ledger -s -r -d /mastercard/ reg ^expenses -@end example - -The @option{-s} option subtotals all postings, just as @option{-M} -subtotaled by the month. The running total in both cases is off, -however, since a display expression is being used. - -@subsection Visualizing with Gnuplot - -If you have @command{Gnuplot} installed, you can graph any of the -above register reports. The script to do this is included in the -ledger distribution, and is named @file{scripts/report}. Install -@file{report} anywhere along your @env{PATH}, and then use -@command{report} instead of @command{ledger} when doing a register -report. The only thing to keep in mind is that you must specify -@option{-j} or @option{-J} to indicate whether Gnuplot should plot the -amount, or the running total. For example, this command plots total -monthly expenses made on your MasterCard. - -@example -report -j -M -r -d /mastercard/ reg ^expenses -@end example - -The @command{report} script is a very simple Bourne shell script, that -passes a set of scripted commands to Gnuplot. Feel free to modify the -script to your liking, since you may prefer histograms to line plots, -for example. - -@subsubsection Typical plots - -Here are some useful plots: - -@smallexample -report -j -M reg ^expenses # monthly expenses -report -J reg checking # checking account balance -report -J reg ^income ^expenses # cash flow report - -# net worth report, ignoring non-$ postings - -report -J -l "Ua>=@{\$0.01@}" reg ^assets ^liab - -# net worth report starting last February. the use of a display -# predicate (-d) is needed, otherwise the balance will start at -# zero, and thus the y-axis will not reflect the true balance - -report -J -l "Ua>=@{\$0.01@}" -d "d>=[last feb]" reg ^assets ^liab -@end smallexample - -The last report uses both a calculation predicate (@option{-l}) and a -display predicate (@option{-d}). The calculation predicates limits -the report to postings whose amount is greater than $1 (which can -only happen if the posting amount is in dollars). The display -predicate limits the transactions @emph{displayed} to just those since last -February, even those transactions from before then will be computed as part -of the balance. - -@node Budgeting and forecasting, Commodities and Currencies, Typical queries, Ledger in Practice -@section Budgeting and forecasting - -@subsection Budgeting - -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 period transactions at the top of your -ledger file. A period 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: - -@smallexample -~ 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 -@end smallexample - -These two period transactions give the usual monthly expenses, as well as -one typical yearly expense. For help on finding out what your average -monthly expense is for any category, use a command like: - -@example -ledger -p "this year" -MAs bal ^expenses -@end example - -The reported totals are the current year's average for each account. - -Once these period transactions are defined, creating a budget report is as -easy as adding @option{--budget} to the command-line. For example, a -typical monthly expense report would be: - -@example -ledger -M reg ^exp -@end example - -To see the same report balanced against your budget, use: - -@example -ledger --budget -M reg ^exp -@end example - -A budget report includes only those accounts that appear in the -budget. To see all expenses balanced against the budget, use -@option{--add-budget}. You can even see only the unbudgeted expenses -using @option{--unbudgeted}: - -@example -ledger --unbudgeted -M reg ^exp -@end example - -You can also use these flags with the @command{balance} command. - -@subsection Forecasting - -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 period transactions as are used for -budgeting. An example forecast report can be generated with: - -@example -ledger --forecast "T>@{\$-500.00@}" register ^assets ^liabilities -@end example - -This report continues outputting postings until the running total -is greater than $-500.00. A final posting is always output, to -show 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: - -@example -ledger --forecast "d<[2010]" bal ^assets ^liabilities -@end example - -@node Commodities and Currencies, Accounts and Inventories, Budgeting and forecasting, Ledger in Practice -@section Commodities and Currencies - -Ledger makes no assumptions about the commodities you use; it only -requires that you specify a commodity. The commodity may be any -non-numeric string that does not contain a period, comma, forward -slash or at-sign. It may appear before or after the amount, although -it is assumed that symbols appearing before the amount refer to -currencies, while non-joined symbols appearing after the amount refer -to commodities. Here are some valid currency and commodity -specifiers: - -@example -$20.00 ; currency: twenty US dollars -40 AAPL ; commodity: 40 shares of Apple stock -60 DM ; currency: 60 Deutsch Mark -£50 ; currency: 50 British pounds -50 EUR ; currency: 50 Euros (or use appropriate symbol) -@end example - -Ledger will examine the first use of any commodity to determine how -that commodity should be printed on reports. It pays attention to -whether the name of commodity was separated from the amount, whether -it came before or after, the precision used in specifying the amount, -whether thousand marks were used, etc. This is done so that printing -the commodity looks the same as the way you use it. - -An account may contain multiple commodities, in which case it will -have separate totals for each. For example, if your brokerage account -contains both cash, gold, and several stock quantities, the balance -might look like: - -@smallexample - $200.00 -100.00 AU - AAPL 40 - BORL 100 - FEQTX 50 Assets:Brokerage -@end smallexample - -This balance report shows how much of each commodity is in your -brokerage account. - -Sometimes, you will want to know the current street value of your -balance, and not the commodity totals. For this to happen, you must -specify what the current price is for each commodity. The price can -be any commodity, in which case the balance will be computed in terms -of that commodity. The usual way to specify prices is with a price -history file, which might look like this: - -@smallexample -P 2004/06/21 02:18:01 FEQTX $22.49 -P 2004/06/21 02:18:01 BORL $6.20 -P 2004/06/21 02:18:02 AAPL $32.91 -P 2004/06/21 02:18:02 AU $400.00 -@end smallexample - -Specify the price history to use with the @option{--price-db} option, -with the @option{-V} option to report in terms of current market -value: - -@example -ledger --price-db prices.db -V balance brokerage -@end example - -The balance for your brokerage account will be reported in US dollars, -since the prices database uses that currency. - -@smallexample -$40880.00 Assets:Brokerage -@end smallexample - -You can convert from any commodity to any other commodity. Let's say -you had $5000 in your checking account, and for whatever reason you -wanted to know many ounces of gold that would buy, in terms of the -current price of gold: - -@example -ledger -T "@{1 AU@}*(O/P@{1 AU@})" balance checking -@end example - -Although the total expression appears complex, it is simply saying -that the reported total should be in multiples of AU units, where the -quantity is the account total divided by the price of one AU. Without -the initial multiplication, the reported total would still use the -dollars commodity, since multiplying or dividing amounts always keeps -the left value's commodity. The result of this command might be: - -@smallexample -14.01 AU Assets:Checking -@end smallexample - -@subsection Commodity price histories - -Whenever a commodity is purchased using a different commodity (such as -a share of common stock using dollars), it establishes a price for -that commodity on that day. It is also possible, by recording price -details in a ledger file, to specify other prices for commodities at -any given time. Such price transactions might look like those below: - -@smallexample -P 2004/06/21 02:17:58 TWCUX $27.76 -P 2004/06/21 02:17:59 AGTHX $25.41 -P 2004/06/21 02:18:00 OPTFX $39.31 -P 2004/06/21 02:18:01 FEQTX $22.49 -P 2004/06/21 02:18:02 AAPL $32.91 -@end smallexample - -By default, ledger will not consider commodity prices when generating -its various reports. It will always report balances in terms of the -commodity total, rather than the current value of those commodities. -To enable pricing reports, use one of the commodity reporting options. - -@subsection Commodity equivalencies - -Sometimes a commodity has several forms which are all equivalent. An -example of this is time. Whether tracked in terms of minutes, hours -or days, it should be possible to convert between the various forms. -Doing this requires the use of commodity equivalencies. - -For example, you might have the following two postings, one which -transfers an hour of time into a @samp{Billable} account, and another -which decreases the same account by ten minutes. The resulting report -will indicate that fifty minutes remain: - -@smallexample -2005/10/01 Work done for company - Billable:Client 1h - Project:XYZ - -2005/10/02 Return ten minutes to the project - Project:XYZ 10m - Billable:Client -@end smallexample - -Reporting the balance for this ledger file produces: - -@smallexample - 50.0m Billable:Client - -50.0m Project:XYZ -@end smallexample - -This example works because ledger already knows how to handle seconds, -minutes and hours, as part of its time tracking support. Defining -other equivalencies is simple. The following is an example that -creates data equivalencies, helpful for tracking bytes, kilobytes, -megabytes, and more: - -@smallexample -C 1.00 Kb = 1024 b -C 1.00 Mb = 1024 Kb -C 1.00 Gb = 1024 Mb -C 1.00 Tb = 1024 Gb -@end smallexample - -Each of these definitions correlates a commodity (such as @samp{Kb}) -and a default precision, with a certain quantity of another commodity. -In the above example, kilobytes are reporetd with two decimal places -of precision and each kilobyte is equal to 1024 bytes. - -Equivalency chains can be as long as desired. Whenever a commodity -would report as a decimal amount (less than @samp{1.00}), the next -smallest commodity is used. If a commodity could be reported in terms -of a higher commodity without resulting to a partial fraction, then -the larger commodity is used. - -@node Accounts and Inventories, Understanding Equity, Commodities and Currencies, Ledger in Practice -@section Accounts and Inventories - -Since Ledger's accounts and commodity system is so flexible, you can -have accounts that don't really exist, and use commodities that no one -else recognizes. For example, let's say you are buying and selling -various items in EverQuest, and want to keep track of them using a -ledger. Just add items of whatever quantity you wish into your -EverQuest account: - -@smallexample -9/29 Get some stuff at the Inn - Places:Black's Tavern -3 Apples - Places:Black's Tavern -5 Steaks - EverQuest:Inventory -@end smallexample - -Now your EverQuest:Inventory has 3 apples and 5 steaks in it. The -amounts are negative, because you are taking @emph{from} Black's -Tavern in order to add to your Inventory account. Note that you don't -have to use @samp{Places:Black's Tavern} as the source account. You -could use @samp{EverQuest:System} to represent the fact that you -acquired them online. The only purpose for choosing one kind of -source account over another is for generate more informative reports -later on. The more you know, the better analysis you can perform. - -If you later sell some of these items to another player, the transaction -would look like: - -@smallexample -10/2 Sturm Brightblade - EverQuest:Inventory -2 Steaks - EverQuest:Inventory 15 Gold -@end smallexample - -Now you've turned 2 steaks into 15 gold, courtesy of your customer, -Sturm Brightblade. - -@node Understanding Equity, Dealing with Petty Cash, Accounts and Inventories, Ledger in Practice -@section Understanding Equity - -The most confusing transaction in any ledger will be your equity account--- -because starting balances can't come out of nowhere. - -When you first start your ledger, you will likely already have money -in some of your accounts. Let's say there's $100 in your checking -account; then add a transaction to your ledger to reflect this amount. -Where will money come from? The answer: your equity. - -@smallexample -10/2 Opening Balance - Assets:Checking $100.00 - Equity:Opening Balances -@end smallexample - -But what is equity? You may have heard of equity when people talked -about house mortgages, as ``the part of the house that you own''. -Basically, equity is like the value of something. If you own a car -worth $5000, then you have $5000 in equity in that car. In order to -turn that car (a commodity) into a cash flow, or a credit to your bank -account, you will have to debit the equity by selling it. - -When you start a ledger, you are probably already worth something. -Your net worth is your current equity. By transferring the money in -the ledger from your equity to your bank accounts, you are crediting -the ledger account based on your prior equity. That is why, when you -look at the balance report, you will see a large negative number for -Equity that never changes: Because that is what you were worth (what -you debited from yourself in order to start the ledger) before the -money started moving around. If the total positive value of your -assets is greater than the absolute value of your starting equity, it -means you are making money. - -Clear as mud? Keep thinking about it. Until you figure it out, put -@samp{-Equity} at the end of your balance command, to remove the -confusing figure from the total. - -@node Dealing with Petty Cash, Working with multiple funds and accounts, Understanding Equity, Ledger in Practice -@section Dealing with Petty Cash - -Something that stops many people from keeping a ledger at all is the -insanity of tracking small cash expenses. They rarely generate a -receipt, and there are often a lot of small postings, rather than -a few large ones, as with checks. - -One solution is: don't bother. Move your spending to a debit card, -but in general ignore cash. Once you withdraw it from the ATM, mark -it as already spent to an @samp{Expenses:Cash} category: - -@smallexample -2004/03/15 ATM - Expenses:Cash $100.00 - Assets:Checking -@end smallexample - -If at some point you make a large cash expense that you want to track, -just ``move'' the amount of the expense from @samp{Expenses:Cash} into -the target account: - -@smallexample -2004/03/20 Somebody - Expenses:Food $65.00 - Expenses:Cash -@end smallexample - -This way, you can still track large cash expenses, while ignoring all -of the smaller ones. - -@node Working with multiple funds and accounts, Archiving previous years, Dealing with Petty Cash, Ledger in Practice -@section Working with multiple funds and accounts - -There are situations when the accounts you're tracking are different -between your clients and the financial institutions where money is -kept. An example of this is working as the treasurer for a religious -institution. From the secular point of view, you might be working -with three different accounts: - -@itemize -@item Checking -@item Savings -@item Credit Card -@end itemize - -From a religious point of view, the community expects to divide its -resources into multiple ``funds'', from which it makes purchases or -reserves resources for later: - -@itemize -@item School fund -@item Building fund -@item Community fund -@end itemize - -The problem with this kind of setup is that when you spend money, it -comes from two or more places at once: the account and the fund. And -yet, the correlation of amounts between funds and accounts is rarely -one-to-one. What if the school fund has @samp{$500.00}, but -@samp{$400.00} of that comes from Checking, and @samp{$100.00} from -Savings? - -Traditional finance packages require that the money reside in only one -place. But there are really two ``views'' of the data: from the -account point of view and from the fund point of view -- yet both sets -should reflect the same overall expenses and cash flow. It's simply -where the money resides that differs. - -This situation can be handled one of two ways. The first is using -virtual postings to represent the fact that money is moving to and -from two kind of accounts at the same time: - -@smallexample -2004/03/20 Contributions - Assets:Checking $500.00 - Income:Donations - -2004/03/25 Distribution of donations - [Funds:School] $300.00 - [Funds:Building] $200.00 - [Assets:Checking] $-500.00 -@end smallexample - -The use of square brackets in the second transaction ensures that the -virtual postings balance to zero. Now money can be spent directly -from a fund at the same time as money is drawn from a physical -account: - -@smallexample -2004/03/25 Payment for books (paid from Checking) - Expenses:Books $100.00 - Assets:Checking $-100.00 - (Funds:School) $-100.00 -@end smallexample - -When reports are generated, by default they'll appear in terms of the -funds. In this case, you will likely want to mask out your -@samp{Assets} account, because otherwise the balance won't make much -sense: - -@example -ledger bal -^Assets -@end example - -If the @option{--real} option is used, the report will be in terms of -the real accounts: - -@example -ledger --real bal -@end example - -If more asset accounts are needed as the source of a posting, just -list them as you would normally, for example: - -@smallexample -2004/03/25 Payment for books (paid from Checking) - Expenses:Books $100.00 - Assets:Checking $-50.00 - Liabilities:Credit Card $-50.00 - (Funds:School) $-100.00 -@end smallexample - -The second way of tracking funds is to use transaction codes. In this -respect the codes become like virtual accounts that embrace the entire -set of postings. Basically, we are associating a transaction with a -fund by setting its code. Here are two transactions that desposit money -into, and spend money from, the @samp{Funds:School} fund: - -@smallexample -2004/03/25 (Funds:School) Donations - Assets:Checking $100.00 - Income:Donations - -2004/04/25 (Funds:School) Payment for books - Expenses:Books $50.00 - Assets:Checking -@end smallexample - -Note how the accounts now relate only to the real accounts, and any -balance or registers reports will reflect this. That the transactions -relate to a particular fund is kept only in the code. - -How does this become a fund report? By using the -@option{--code-as-payee} option, you can generate a register report -where the payee for each posting shows the code. Alone, this is -not terribly interesting; but when combined with the -@option{--by-payee} option, you will now see account subtotals for any -postings related to a specific fund. So, to see the current -monetary balances of all funds, the command would be: - -@smallexample -ledger --code-as-payee -P reg ^Assets -@end smallexample - -Or to see a particular funds expenses, the @samp{School} fund in this -case: - -@smallexample -ledger --code-as-payee -P reg ^Expenses -- School -@end smallexample - -Both approaches yield different kinds of flexibility, depending on how -you prefer to think of your funds: as virtual accounts, or as tags -associated with particular transactions. Your own tastes will decide which -is best for your situation. - -@node Archiving previous years, Virtual postings, Working with multiple funds and accounts, Ledger in Practice -@section Archiving previous years - -After a while, your ledger can get to be pretty large. While this -will not slow down the ledger program much---it's designed to process -ledger files very quickly---things can start to feel ``messy''; and -it's a universal complaint that when finances feel messy, people avoid -them. - -Thus, archiving the data from previous years into their own files can -offer a sense of completion, and freedom from the past. But how to -best accomplish this with the ledger program? There are two commands -that make it very simple: @command{print}, and @command{equity}. - -Let's take an example file, with data ranging from year 2000 until -2004. We want to archive years 2000 and 2001 to their own file, -leaving just 2003 and 2004 in the current file. So, use -@command{print} to output all the earlier transactions to a file called -@file{ledger-old.dat}: - -@smallexample -ledger -f ledger.dat -b 2000 -e 2001 print > ledger-old.dat -@end smallexample - -To delete older data from the current ledger file, use @command{print} -again, this time specifying year 2002 as the starting date: - -@example -ledger -f ledger.dat -b 2002 print > x -mv x ledger.dat -@end example - -However, now the current file contains @emph{only} postings from -2002 onward, which will not yield accurate present-day balances, -because the net income from previous years is no longer being tallied. -To compensate for this, we must append an equity report for the old -ledger at the beginning of the new one: - -@example -ledger -f ledger-old.dat equity > equity.dat -cat equity.dat ledger.dat > x -mv x ledger.dat -rm equity.dat -@end example - -Now the balances reported from @file{ledger.dat} are identical to what -they were before the data was split. - -How often should you split your ledger? You never need to, if you -don't want to. Even eighty years of data will not slow down ledger -much---and that's just using present day hardware! Or, you can keep -the previous and current year in one file, and each year before that -in its own file. It's really up to you, and how you want to organize -your finances. For those who also keep an accurate paper trail, it -might be useful to archive the older years to their own files, then -burn those files to a CD to keep with the paper records---along with -any electronic statements received during the year. In the arena of -organization, just keep in mind this maxim: Do whatever keeps you -doing it. - -@node Virtual postings, Automated postings, Archiving previous years, Ledger in Practice -@section Virtual postings - -A virtual posting is when you, in your mind, see money as moving -to a certain place, when in reality that money has not moved at all. -There are several scenarios in which this type of tracking comes in -handy, and each of them will be discussed in detail. - -To enter a virtual posting, surround the account name in -parentheses. This form of usage does not need to balance. However, -if you want to ensure the virtual posting balances with other -virtual postings in the same transaction, use square brackets. For -example: - -@smallexample -10/2 Paycheck - Assets:Checking $1000.00 - Income:Salary $-1000.00 - (Debt:Alimony) $200.00 -@end smallexample - -In this example, after receiving a paycheck an alimony debt is -increased---even though no money has moved around yet. - -@smallexample -10/2 Paycheck - Assets:Checking $1000.00 - Income:Salary $-1000.00 - [Savings:Trip] $200.00 - [Assets:Checking] $-200.00 -@end smallexample - -In this example, $200 has been deducted from checking toward savings -for a trip. It will appear as though the money has been moved from -the account into @samp{Savings:Trip}, although no money has actually -moved anywhere. - -When balances are displayed, virtual postings will be factored in. -To view balances without any virtual balances factored in, using the -@option{-R} flag, for ``reality''. - -@node Automated postings, Using Emacs to Keep Your Ledger, Virtual postings, Ledger in Practice -@section Automated postings - -As a Bahá'í, I need to compute Huqúqu'lláh whenever I acquire assets. -It is similar to tithing for Jews and Christians, or to Zakát for -Muslims. The exact details of computing Huqúqu'lláh are somewhat -complex, but if you have further interest, please consult the Web. - -Ledger makes this otherwise difficult law very easy. Just set up an -automated posting at the top of your ledger file: - -@smallexample -; This automated transaction will compute Huqúqu'lláh based on this -; journal's postings. Any that match will affect the -; Liabilities:Huququ'llah account by 19% of the value of that -; posting. - -= /^(?:Income:|Expenses:(?:Business|Rent$|Furnishings|Taxes|Insurance))/ - (Liabilities:Huququ'llah) 0.19 -@end smallexample - -This automated posting works by looking at each posting in the -ledger file. If any match the given value expression, 19% of the -posting's value is applied to the @samp{Liabilities:Huququ'llah} -account. So, if $1000 is earned from @samp{Income:Salary}, $190 is -added to @samp{Liabilities:Huqúqu'lláh}; if $1000 is spent on Rent, -$190 is subtracted. The ultimate balance of Huqúqu'lláh reflects how -much is owed in order to fulfill one's obligation to Huqúqu'lláh. -When ready to pay, just write a check to cover the amount shown in -@samp{Liabilities:Huququ'llah}. That transaction would look like: - -@smallexample -2003/01/01 (101) Baha'i Huqúqu'lláh Trust - Liabilities:Huququ'llah $1,000.00 - Assets:Checking -@end smallexample - -That's it. To see how much Huqúq is currently owed based on your -ledger transactions, use: - -@example -ledger balance Liabilities:Huquq -@end example - -This works fine, but omits one aspect of the law: that Huquq is only -due once the liability exceeds the value of 19 mithqáls of gold (which -is roughly 2.22 ounces). So what we want is for the liability to -appear in the balance report only when it exceeds the present day -value of 2.22 ounces of gold. This can be accomplished using the -command: - -@smallexample -ledger -Q -t "/Liab.*Huquq/?(a/P@{2.22 AU@}<=@{-1.0@}&a):a" -s bal liab -@end smallexample - -With this command, the current price for gold is downloaded, and the -Huqúqu'lláh is reported only if its value exceeds that of 2.22 ounces -of gold. If you wish the liability to be reflected in the parent -subtotal either way, use this instead: - -@smallexample -ledger -Q -T "/Liab.*Huquq/?(O/P@{2.22 AU@}<=@{-1.0@}&O):O" -s bal liab -@end smallexample - -In some cases, you may wish to refer to the account of whichever -posting matched your automated transaction's value expression. To do -this, use the special account name @samp{$account}: - -@smallexample -= /^Some:Long:Account:Name/ - [$account] -0.10 - [Savings] 0.10 -@end smallexample - -This example causes 10% of the matching account's total to be deferred -to the @samp{Savings} account---as a balanced virtual posting, -which may be excluded from reports by using @option{--real}. - -@node Using Emacs to Keep Your Ledger, Using GnuCash to Keep Your Ledger, Automated postings, Ledger in Practice -@section Using Emacs to Keep Your Ledger - -In the Ledger tarball is an Emacs module, @file{ledger.el}. This -module makes the process of keeping a text ledger much easier for -Emacs users. I recommend putting this at the top of your ledger file: - -@example -; -*-ledger-*- -@end example - -And this in your @file{.emacs} file, after copying @file{ledger.el} to -your @file{site-lisp} directory: - -@example -(load "ledger") -@end example - -Now when you edit your ledger file, it will be in -@command{ledger-mode}. @command{ledger-mode} adds these commands: - -@table @strong -@item C-c C-a -For quickly adding new transactions based on the form of older ones (see -previous section). - -@item C-c C-c -Toggles the ``cleared'' flag of the posting under point. - -@item C-c C-d -Delete the transaction under point. - -@item C-c C-r -Reconciles an account by displaying the postings in another -buffer, where simply hitting the spacebar will toggle the pending flag -of the posting in the ledger. Once all the appropriate -postings have been marked, press C-c C-c in the reconcile buffer -to ``commit'' the reconciliation, which will mark all of the transactions -as cleared, and display the new cleared balance in the minibuffer. - -@item C-c C-m -Set the default month for new transactions added with C-c C-a. This is -handy if you have a large number of postings to enter from a -previous month. - -@item C-c C-y -Set the default year for new transactions added with C-c C-a. This is -handy if you have a large number of postings to enter from a -previous year. -@end table - -Once you enter the reconcile buffer, there are several key commands -available: - -@table @strong -@item RET -Visit the ledger file transaction corresponding to the reconcile transaction. - -@item C-c C-c -Commit the reconcialation. This marks all of the marked postings -as ``cleared'', saves the ledger file, and then displays the new -cleared balance. - -@item C-l -Refresh the reconcile buffer by re-reading postings from the -ledger data file. - -@item SPC -Toggle the posting under point as cleared. - -@item a -Add a new transaction to the ledger data file, and refresh the reconcile -buffer to include its postings (if the transaction is added to the same -account as the one being reconciled). - -@item d -Delete the transaction related to the posting under point. Note: This -may result in multiple postings being deleted. - -@item n -Move to the next line. - -@item p -Move to the previous line. - -@item C-c C-r -@item r -Attempt to auto-reconcile the postings to the entered balance. If -it can do so, it will mark all those postings as pending that -would yield the specified balance. - -@item C-x C-s -@item s -Save the ledger data file, and show the current cleared balance for -the account being reconciled. - -@item q -Quit the reconcile buffer. -@end table - -There is also an @command{emacs} command which can be used to output -reports in a format directly @code{read}-able from Emacs Lisp. - -@node Using GnuCash to Keep Your Ledger, Using timeclock to record billable time, Using Emacs to Keep Your Ledger, Ledger in Practice -@section Using GnuCash to Keep Your Ledger - -The Ledger tool is fast and simple, but it offers no custom method for -actually editing the ledger. It assumes you know how to use a text -editor, and like doing so. There is, at least, an Emacs mode that -makes editing Ledger's data files much easier. - -You are also free to use GnuCash to maintain your ledger, and the -Ledger program for querying and reporting on the contents of that -ledger. It takes a little longer to parse the XML data format that -GnuCash uses, but the end result is identical. - -Then again, why would anyone use a Gnome-centric, multi-megabyte -behemoth to edit their data, and only a one megabyte binary to query -it? - -@node Using timeclock to record billable time, Using XML, Using GnuCash to Keep Your Ledger, Ledger in Practice -@section Using timeclock to record billable time - -The timeclock tool makes it easy to track time events, like clocking -into and out of a particular job. These events accumulate in a -timelog file. - -Each in/out event may have an optional description. If the ``in'' -description is a ledger account name, these in/out pairs may be viewed -as virtual postings, adding time commodities (hours) to that -account. - -For example, the command-line version of the timeclock tool could be -used to begin a timelog file like: - -@example -export TIMELOG=$HOME/.timelog -ti ClientOne category -sleep 10 -to waited for ten seconds -@end example - -The @file{.timelog} file now contains: - -@smallexample -i 2004/10/06 15:21:00 ClientOne category -o 2004/10/06 15:21:10 waited for ten seconds -@end smallexample - -Ledger parses this directly, as if it had seen the following transaction: - -@smallexample -2004/10/06 category - (ClientOne) 10s -@end smallexample - -In other words, the timelog event pair is seen as adding 0.00277h (ten -seconds) worth of time to the @samp{ClientOne} account. This would be -considered billable time, which later could be invoiced and credited -to accounts receivable: - -@smallexample -2004/11/01 (INV#1) ClientOne, Inc. - Receivable:ClientOne $0.10 - ClientOne -0.00277h @@ $35.00 -@end smallexample - -The above posting converts the clocked time into an invoice for -the time spent, at an hourly rate of $35. Once the invoice is paid, -the money is deposited from the receivable account into a checking -account: - -@smallexample -2004/12/01 ClientOne, Inc. - Assets:Checking $0.10 - Receivable:ClientOne -@end smallexample - -And now the time spent has been turned into hard cash in the checking -account. - -The advantage to using timeclock and invoicing to bill time is that -you will always know, by looking at the balance report, exactly how -much unbilled and unpaid time you've spent working for any particular -client. - -I like to @samp{!include} my timelog at the top of my company's -accounting ledger, with the attached prefix @samp{Billable}: - -@smallexample -; -*-ledger-*- - -; This is the ledger file for my company. But first, include the -; timelog data, entering all of the time events within the umbrella -; account "Billable". - -!account Billable -!include /home/johnw/.timelog -!end - -; Here follows this fiscal year's postings for the company. - -2004/11/01 (INV#1) ClientOne, Inc. - Receivable:ClientOne $0.10 - Billable:ClientOne -0.00277h @@ $35.00 - -2004/12/01 ClientOne, Inc. - Assets:Checking $0.10 - Receivable:ClientOne -@end smallexample - -@node Using XML, , Using timeclock to record billable time, Ledger in Practice -@section Using XML - -By 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: - -@smallexample -<?xml version="1.0"?> -<ledger> - <xact>...</xact> - <xact>...</xact> - <xact>...</xact>... -</ledger> -@end smallexample - -The data stream is enclosed in a @samp{ledger} tag, which contains a -series of one or more transactions. Each @samp{xact} describes the transaction -and contains a series of one or more postings: - -@smallexample -<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> -@end smallexample - -The date format for @samp{en:date} is always @samp{YYYY/MM/DD}. The -@samp{en:cleared} tag is optional, and indicates whether the -posting has been cleared or not. There is also an -@samp{en:pending} tag, for marking pending postings. The -@samp{en:code} and @samp{en:payee} tags both contain whatever text the -user wishes. - -After the initial transaction data, there must follow a set of postings -marked with @samp{en:postings}. Typically these postings will -all balance each other, but if not they will be automatically balanced -into an account named @samp{<Unknown>}. - -Within the @samp{en:postings} tag is a series of one or more -@samp{posting}'s, which have the following form: - -@smallexample -<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> -@end smallexample - -This is a basic posting. It may also be begin with -@samp{tr:virtual} and/or @samp{tr:generated} tags, to indicate virtual -and auto-generated postings. Then follows the @samp{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 -@samp{tr:amount}. Within this tag is a @samp{value} tag, of which -there are four different kinds, each with its own format: - -@enumerate -@item boolean -@item integer -@item amount -@item balance -@end enumerate - -The format of a boolean value is @samp{true} or @samp{false} -surrounded by a @samp{boolean} tag, for example: - -@smallexample -<boolean>true</boolean> -@end smallexample - -The format of an integer value is the numerical value surrounded by an -@samp{integer} tag, for example: - -@smallexample -<integer>12036</integer> -@end smallexample - -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: - -@table @strong -@item P -The commodity is prefixed to the value. -@item S -The commodity is separated from the value by a space. -@item T -Thousands markers are used to display the amount. -@item E -The format of the amount is European, with period used as a thousands -marker, and comma used as the decimal point. -@end table - -The actual quantity for an amount is an integer of arbitrary size. -Ledger uses the GNU multi-precision math library to handle such -values. The XML format assumes the reader to be equally capable. -Here is an example amount: - -@smallexample -<value type="amount"> - <amount> - <commodity flags="PT">$</commodity> - <quantity>90.00</quantity> - </amount> -</value> -@end smallexample - -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: - -@smallexample -<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> -@end smallexample - -That is the extent of the XML data format used by Ledger. It will -output such data if the @command{xml} command is used, and can read -the same data. - -@chapter Random things - -Whenever a commodity is exchanged for another in a posting, one of the -two is considered @emph{primary}, and the other secondary. -Primariness of a commodity is remembered, since the @option{--market} -option only renders balances into secondary commodities, never -primaries. To render primaries, use the @option{--exchange=COMMODITY} -option. - -In all of the following examples, the P commodity is considered primary -and the S is secondary (the P at the beginning of the line indicates a -price-setting directive): - -@smallexample -2009/01/01 Sample 1a - Assets:Brokerage:Stocks 100 S - Assets:Brokerage:Cash -100 P - -P 2009/01/15 00:00:00 S 2 P - -2009/02/01 Sample 2a - Assets:Brokerage:Stocks 100 S @@ 1 P - Assets:Brokerage:Cash - -P 2009/02/01 00:00:00 S 4 P - -2009/03/01 Sample 3a - Assets:Brokerage:Stocks 100 S @@@@ 100 P - Assets:Brokerage:Cash - -P 2009/03/01 00:00:00 S 8 P - -2009/04/01 Sample 4a - Assets:Brokerage:Cash 100 P - Assets:Brokerage:Stocks -100 S @{1 P@} - -P 2009/04/01 00:00:00 S 16 P -@end smallexample - -@chapter Anatomy of a journal file - -Everything begins with a journal file---the anatomy of which is covered -in detail in chapter one. To review: a @emph{journal} contains one or -more @emph{transactions}, each of which refers to two or more -@emph{postings}. A @emph{posting} specifies that a given -@emph{amount} is added to, or subtracted from, an @emph{account}. -(@emph{Accounts} may be nested hierarchically by separating the elements -using a colon). Lastly, an @emph{amount} is a figure representing a -given @emph{quantity} of a @emph{commodity}. Here follows a review of -these terms, which are all used extensively throughout this chapter: - -@table @emph -@item journal -A journal is a data file containing a series of transactions. - -@item transaction -a transaction relates a group of two or more postings, with the absolute -constraint that the total sum of a transaction's postings must equal -zero. That is, every transaction in a journal must @emph{balance} to zero. - -@item posting -Postings record how commodities are moved between accounts. If you -spent money on a movie ticket, for example, such a transaction would have two -postings: One to show how the money was taken from your wallet, and -another to show how it was applied to your movie expenses. - -@item account -An account - -@item amount - -@item quantity - -@item commodity -@end table - -@chapter Example accounting practices - -@chapter Generating useful reports - -Once you have a journal file representing a recent history of your -finances, the next step is to generate reports in order to give richer -meaning to this data. For example: Where do you spend your money? Do -you have enough to cover upcoming expenses? Are you creating or losing -net worth? Are your investment performing well? All of these questions -can be answered easily with Ledger---if you know how to ask them. - -Preparing complex reports is not a simple task, but neither is it a -difficult one. All that's required is a proper understanding of how -Ledger views your data, and how it prepares it for reporting. - -After Ledger reads a journal file, it creates an in-memory -representation reflecting the order and composition of those transactions. - -@chapter Value expressions - -@chapter Format strings - -@chapter Extensions in Python - -@chapter The design of Ledger - -The following sections discuss how Ledger is architected, from the -ground up, and will show how to use the various parts of the Ledger -library from your own scripts. Ledger essentially follows five steps in -reporting data to the user: - -@enumerate -@item Parse journal file into an internal representation -@item Perform any implied math within the journal file -@item ``Face'' this internal representation as a virtual document -@item Apply a series of transforms to the virtual document -@item Display the virtual document using a formatting command -@end enumerate - -The calculations in step two are specified by the user, such as when a -posting's value might contain mathematical operators. The -calculations in step four are implied in the transformations, for -example when the @option{--average} option is used. - -At the core, however, Ledger is basically a sophisticated calculator -with special knowledge about commoditized values. It knows what you -mean if you add ten dollars to twenty euros, and later ask for the -balance of that particular account. So it follows that first we must -discuss how Ledger deals with math, and from there move on to describing -how the steps above are achieved. - -@section Numerics - -@subsection Basic amounts - -The most fundamental type in Ledger is the amount, which may or may -not have a commodity attached to it. First, we'll deal with the bare -case, just to show how the amount type works. In C++, most all of -Ledger's internal types end in @code{_t}; in Python, the same type -name is used, but the @code{_t} suffix is dropped. Examples of usage -in both languages will be presented throughout. - - - -amount_t -commodity_t -updater_t -datetime_t -balance_t -balance_pair_t -value_t -valexpr_t -format_t -mask_t - -@section Journal Representation - -journal_t -account_t -xact_t -post_t -parser_t - -@section Reporting - -@section Terminal Interface - -@section General Utility - -@c data: foo -@smallexample -2004/05/01 * Checking balance - Assets:Bank:Checking $1,000.00 - Equity:Opening Balances -@end smallexample - -@c smex utility-1: $LEDGER -f $foo bal -@smallexample - $1,000.00 Assets:Bank:Checking - $-1,000.00 Equity:Opening Balances --------------------- - 0 -@end smallexample - -@bye diff --git a/doc/ledger3.texi b/doc/ledger3.texi index 0e22aad6..d5767efa 100644 --- a/doc/ledger3.texi +++ b/doc/ledger3.texi @@ -20,9 +20,83 @@ @c Restructuring manual ideas @c http://beyondgrep.com/documentation/ack-2.04-man.html +@c How to make documented ledger examples validate automatically. +@c +@c The test/DocTests.py script will be run along the with the other +@c tests when using ctest or acprep check. +@c The script parses the texinfo file and looks for three kinds of +@c specially marked @smallexamples, then it will run the ledger +@c command from the exmaple, and compare the results with the output +@c from the documentation. +@c +@c To specially mark a @smallexample append @c command:UUID, where +@c UUID is the first 7 digits from the commands sha1sum, e.g.: +@c +@c @smallexample @c command:CDE330A +@c $ ledger -f sample.dat reg expenses +@c @end smallexample +@c +@c Then DocTests.py will look for corresponding documented output, +@c which may appear anywhere in the file, and is marked with +@c @smallexample @c output:UUID where UUID is the UUID from the +@c corresponding ledger command example, e.g.: +@c +@c @smallexample @c output:CDE330A +@c 04-May-27 Book Store Expenses:Books $20.00 $20.00 +@c Expenses:Cards $40.00 $60.00 +@c Expenses:Docs $30.00 $90.0 +@c @end smallexample +@c +@c Now where does this data in sample.dat come from? +@c DocTests.py is a bit smart about ledger's file argument, since +@c it will check if the given filename exists in the test/input/ +@c directory. +@c +@c Sometimes the journal data for an example is specified within +@c the documentation itself, in that case the journal example data +@c needs to be specially marked as well using @smallexample @c input:UUID, +@c again with the UUID being the UUID of the corresponding ledger example +@c command. If multiple inputs with the same UUID are found they will be +@c concatenated together and given as one set of data to the example command. +@c +@c @smallexample @c input:35CB2A3 +@c 2014/02/09 The Italian Place +@c Expenses:Food:Dining $ 36.84 +@c Assets:Cash +@c @end smallexample +@c +@c @smallexample @c command:35CB2A3 +@c $ ledger -f inline.dat accounts +@c @end smallexample +@c +@c @smallexample @c output:35CB2A3 +@c Assets:Cash +@c Expenses:Food:Dining +@c @end smallexample +@c +@c To use different example commands with the same input from the documentation +@c add with_input:UUID to the example command, where UUID is the UUID of the input, +@c e.g.: +@c +@c @smallexample @c command:94FD2B6,with_input:35CB2A3 +@c $ ledger -f inline.dat bal expenses +@c @end smallexample +@c +@c @smallexample @c output:94FD2B6 +@c $ 36.84 Expenses:Food:Dining +@c @end smallexample +@c +@c Additionally DocTests.py will pass --init-file /dev/null to ledger to +@c ignore any default arguments to ledger the user running the tests +@c has configured. +@c +@c To manually run the tests in this file run: +@c $ ./test/DocTests.py -vv --ledger ./ledger --file ./doc/ledger3.texi + + @copying -Copyright @copyright{} 2003–2013, John Wiegley. All rights reserved. +Copyright @copyright{} 2003–2014, John Wiegley. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -166,9 +240,9 @@ accounting tools. The next step up from a checkbook journal, is a journal that keeps track of all your accounts, not just checking. In such a journal, you record not only who gets paid---in the case of a debit---but where the -money came from. In a checkbook journal, its assumed that all the +money came from. In a checkbook journal, it's assumed that all the money comes from your checking account. But in a general journal, you -write posting two-lines: the source account and target account. +write postings in two lines: the source account and target account. @emph{There must always be a debit from at least one account for every credit made to another account}. This is what is meant by ``double-entry'' accounting: the journal must always balance to zero, @@ -214,10 +288,10 @@ Most private people consider an account to be something that holds money at an institution for them. Ledger uses a more general definition of the word. An account is anywhere money can go. Other finance programs use ``categories'', Ledger uses accounts. So, for -example, if you buy some groceries at Trader Joe's then more groceries -at Whole Foods Markets you might assign the transactions like this +example, if you buy some groceries at Trader Joe's, then more groceries +at Whole Food Market, you might assign the transactions like this -@smallexample +@smallexample @c input:validate 2011/03/15 Trader Joe's Expenses:Groceries $100.00 Assets:Checking @@ -245,7 +319,7 @@ And just for the sake of example---as a starting point for those who want to dive in head-first---here are the journal transactions from above, formatted as the Ledger program wishes to see them: -@smallexample +@smallexample @c input:48DDF26 2004/09/29 Pacific Bell Expenses:Pacific Bell $23.00 Assets:Checking @@ -254,12 +328,37 @@ above, formatted as the Ledger program wishes to see them: The account balances and registers in this file, if saved as @file{ledger.dat}, could be reported using: -@smallexample +@smallexample @c command:48DDF26 $ ledger -f ledger.dat balance +@end smallexample + +@smallexample @c output:48DDF26 + $-23.00 Assets:Checking + $23.00 Expenses:Pacific Bell +-------------------- + 0 +@end smallexample + +Or + +@smallexample @c command:8C7295F,with_input:48DDF26 $ ledger -f ledger.dat register checking +@end smallexample + +@smallexample @c output:8C7295F +04-Sep-29 Pacific Bell Assets:Checking $-23.00 $-23.00 +@end smallexample + +And even: + +@smallexample @c command:BB32EF2,with_input:48DDF26 $ ledger -f ledger.dat register Bell @end smallexample +@smallexample @c output:BB32EF2 +04-Sep-29 Pacific Bell Expenses:Pacific Bell $23.00 $23.00 +@end smallexample + An important difference between Ledger and other finance packages is that Ledger will never alter your input file. You can create and edit that file in any way you prefer, but Ledger is only for analyzing the @@ -286,14 +385,14 @@ $ ./configure && make install Ledger has a complete online help system based on GNU Info. This manual can be searched directly from the command line using the -following options: @code{ledger --help} bring up this entire manual in -your tty. +following options: @code{ledger --help} brings up this entire manual in +your TTY. If you need help on how to use Ledger, or run into problems, you can join the Ledger mailing list at @url{http://groups.google.com/group/ledger-cli}. -You can also find help at the @code{#ledger} channel on the IRC server +You can also find help in the @code{#ledger} channel on the IRC server @code{irc.freenode.net}. @node Ledger Tutorial, Principles of Accounting with Ledger, Introduction to Ledger, Top @@ -331,11 +430,11 @@ If you would rather start with your own journal right away please Please note that as a command line program, Ledger is controlled from your shell. There are several different command shells that all behave slightly differently with respect to some special characters. -In particular, the BASH shell will interpret @samp{$} signs +In particular, the ``bash'' shell will interpret @samp{$} signs differently than ledger and they must be escaped to reach the actual -program. Another example is zsh, which will interpret @samp{^} +program. Another example is ``zsh'', which will interpret @samp{^} differently than ledger expects. In all cases that follow you should -take that into account when entering the command line arguments given. +take that into account when entering the command line arguments as given. There are too many variations between shells to give concrete examples for each. @@ -346,13 +445,13 @@ for each. To find the balances of all of your accounts, run this command: -@smallexample +@smallexample @c command:1071890 $ ledger -f drewr3.dat balance @end smallexample Ledger will generate: -@smallexample +@smallexample @c output:1071890 $ -3,804.00 Assets $ 1,396.00 Checking $ 30.00 Business @@ -381,8 +480,11 @@ pare this down to show only the accounts you want. A more useful report is to show only your Assets and Liabilities: -@smallexample +@smallexample @c command:5BF4D8E $ ledger -f drewr3.dat balance Assets Liabilities +@end smallexample + +@smallexample @c output:5BF4D8E $ -3,804.00 Assets $ 1,396.00 Checking $ 30.00 Business @@ -402,16 +504,16 @@ $ ledger -f drewr3.dat balance Assets Liabilities To show all transactions and a running total: -@smallexample +@smallexample @c command:66E3A2C $ ledger -f drewr3.dat register @end smallexample @noindent Ledger will generate: -@smallexample +@smallexample @c output:66E3A2C 10-Dec-01 Checking balance Assets:Checking $ 1,000.00 $ 1,000.00 - Equity:Opening Balances $ -1,000.00 0 + Equit:Opening Balances $ -1,000.00 0 10-Dec-20 Organic Co-op Expense:Food:Groceries $ 37.50 $ 37.50 Expense:Food:Groceries $ 37.50 $ 75.00 Expense:Food:Groceries $ 37.50 $ 112.50 @@ -450,8 +552,11 @@ interested in seeing transactions for: @cindex accounts, limiting by @cindex limiting by accounts -@smallexample +@smallexample @c command:96B0EB3 $ ledger -f drewr3.dat register Groceries +@end smallexample + +@smallexample @c output:96B0EB3 10-Dec-20 Organic Co-op Expense:Food:Groceries $ 37.50 $ 37.50 Expense:Food:Groceries $ 37.50 $ 75.00 Expense:Food:Groceries $ 37.50 $ 112.50 @@ -465,8 +570,11 @@ $ ledger -f drewr3.dat register Groceries @noindent Which matches the balance reported for the @samp{Groceries} account: -@smallexample +@smallexample @c command:AECD64E $ ledger -f drewr3.dat balance Groceries +@end smallexample + +@smallexample @c output:AECD64E $ 334.00 Expenses:Food:Groceries @end smallexample @@ -474,8 +582,11 @@ $ ledger -f drewr3.dat balance Groceries If you would like to find transaction to only a certain payee use @samp{payee} or @samp{@@}: -@smallexample +@smallexample @c command:C6BC57E $ ledger -f drewr3.dat register payee "Organic" +@end smallexample + +@smallexample @c output:C6BC57E 10-Dec-20 Organic Co-op Expense:Food:Groceries $ 37.50 $ 37.50 Expense:Food:Groceries $ 37.50 $ 75.00 Expense:Food:Groceries $ 37.50 $ 112.50 @@ -497,8 +608,11 @@ a check to clear, but you should treat it as money spent. The @command{cleared} report will not format correctly for accounts that contain multiple commodities): -@smallexample +@smallexample @c command:B86F6A6 $ ledger -f drewr3.dat cleared +@end smallexample + +@smallexample @c output:B86F6A6 $ -3,804.00 $ 775.00 Assets $ 1,396.00 $ 775.00 10-Dec-20 Checking $ 30.00 0 Business @@ -517,8 +631,8 @@ $ ledger -f drewr3.dat cleared $ -20.00 0 MasterCard $ 200.00 0 Mortgage:Principal $ -243.60 0 Tithe ----------------- ---------------- --------- - $ -243.60 0 +---------------- ---------------- --------- + $ -243.60 0 @end smallexample @noindent @@ -531,7 +645,7 @@ shows the ``cleared'' balance. @cindex currency symbol display on windows Using ledger under the windows command shell has one significant -limitation. CMD.exe is limited to standard ASCII characters and as +limitation. CMD.EXE is limited to standard ASCII characters and as such cannot display any currency symbols other than dollar signs @samp{$}. @@ -555,9 +669,9 @@ such cannot display any currency symbols other than dollar signs Accounting is simply tracking your money. It can range from nothing, and just waiting for automatic overdraft protection to kick in, or -not, to a full blown double entry accounting system. Ledger +not, to a full-blown double-entry accounting system. Ledger accomplishes the latter. With ledger you can handle your personal -finances or your businesses. Double-entry accounting scales. +finances or your business's. Double-entry accounting scales. @node Stating where money goes, Assets and Liabilities, Accounting with Ledger, Principles of Accounting with Ledger @section Stating where money goes @@ -578,7 +692,7 @@ where the money comes from and where it goes to. For example, when you are paid a salary, you must add money to your bank account and also subtract it from an income account: -@smallexample +@smallexample @c input:validate 9/29 My Employer Assets:Checking $500.00 Income:Salary $-500.00 @@ -624,7 +738,7 @@ owe. ``Liabilities'' is just a more inclusive name for Debts. An Asset is typically increased by transferring money from an Income account, such as when you get paid. Here is a typical transaction: -@smallexample +@smallexample @c input:6B43DD4 2004/09/29 My Employer Assets:Checking $500.00 Income:Salary @@ -639,7 +753,7 @@ borrow money to buy something, or if you owe someone money. Here is an example of increasing a MasterCard liability by spending money with it: -@smallexample +@smallexample @c input:6B43DD4 2004/09/30 Restaurant Expenses:Dining $25.00 Liabilities:MasterCard @@ -653,10 +767,17 @@ offsets the value of your assets. The combined total of your Assets and Liabilities is your net worth. So to see your current net worth, use this command: -@smallexample +@smallexample @c command:6B43DD4 $ ledger balance ^assets ^liabilities @end smallexample +@smallexample @c output:6B43DD4 + $500.00 Assets:Checking + $-25.00 Liabilities:MasterCard +-------------------- + $475.00 +@end smallexample + In a similar vein, your Income accounts show up negative, because they transfer money @emph{from} an account in order to increase your assets. Your Expenses show up positive because that is where the @@ -665,17 +786,28 @@ flow. A positive cash flow means you are spending more than you make, since income is always a negative figure. To see your current cash flow, use this command: -@smallexample +@smallexample @c command:DB128F3,with_input:6B43DD4 $ ledger balance ^income ^expenses @end smallexample +@smallexample @c output:DB128F3 + $25.00 Expenses:Dining + $-500.00 Income:Salary +-------------------- + $-475.00 +@end smallexample + Another common question to ask of your expenses is: How much do I spend each month on X? Ledger provides a simple way of displaying monthly totals for any account. Here is an example that summarizes your monthly automobile expenses: -@smallexample -$ ledger -M register expenses:auto +@smallexample @c command:DB524E4 +$ ledger -M register -f drewr3.dat expenses:auto +@end smallexample + +@smallexample @c output:DB524E4 +11-Jan-01 - 11-Jan-31 Expenses:Auto $ 5,500.00 $ 5,500.00 @end smallexample This assumes, of course, that you use account names like @@ -699,7 +831,7 @@ This is fairly easy to do in ledger. When spending the money, spend it @emph{to} your Assets:Reimbursements, using a different account for each person or business that you spend money for. For example: -@smallexample +@smallexample @c input:validate 2004/09/29 Circuit City Assets:Reimbursements:Company XYZ $100.00 Liabilities:MasterCard @@ -710,7 +842,7 @@ expense was made on behalf of Company XYZ. Later, when Company XYZ pays the amount back, the money will transfer from that reimbursement account back to a regular asset account: -@smallexample +@smallexample @c input:validate 2004/09/29 Company XYZ Assets:Checking $100.00 Assets:Reimbursements:Company XYZ @@ -732,7 +864,7 @@ company accounts. But keeping them in one file involves the same kinds of postings, so those are what is shown here. First, the personal transaction, which shows the need for reimbursement: -@smallexample +@smallexample @c input:validate 2004/09/29 Circuit City Assets:Reimbursements:Company XYZ $100.00 Liabilities:MasterCard @@ -744,7 +876,7 @@ transaction should be immediately followed by an equivalent transaction, which shows the kind of expense, and also notes the fact that $100.00 is now payable to you: -@smallexample +@smallexample @c input:validate 2004/09/29 Circuit City Company XYZ:Expenses:Computer:Software $100.00 Company XYZ:Accounts Payable:Your Name @@ -757,7 +889,7 @@ paid back. These two transactions can also be merged, to make things a little clearer. Note that all amounts must be specified now: -@smallexample +@smallexample @c input:validate 2004/09/29 Circuit City Assets:Reimbursements:Company XYZ $100.00 Liabilities:MasterCard $-100.00 @@ -771,7 +903,7 @@ paying it to accounts payable, and then drawing it again from the reimbursement account, and paying it to your personal asset account. It's easier shown than said: -@smallexample +@smallexample @c input:validate 2004/10/15 Company XYZ Assets:Checking $100.00 Assets:Reimbursements:Company XYZ $-100.00 @@ -801,7 +933,7 @@ above. For example, for both the expense and the pay-back shown above, the following four transactions would be created. Two in your personal ledger file: -@smallexample +@smallexample @c input:990E0D1 2004/09/29 Circuit City Assets:Reimbursements:Company XYZ $100.00 Liabilities:MasterCard $-100.00 @@ -813,7 +945,7 @@ personal ledger file: And two in your company ledger file: -@smallexample +@smallexample @c input:990E0D1 apply account Company XYZ 2004/09/29 Circuit City @@ -836,6 +968,18 @@ was spent using your MasterCard on behalf of Company XYZ, and that Company XYZ spent the money on computer software and paid it back about two weeks later. +@smallexample @c command:990E0D1 +$ ledger balance --no-total +@end smallexample + +@smallexample @c output:990E0D1 + $100.00 Assets:Checking + 0 Company XYZ + $-100.00 Assets:Checking + $100.00 Expenses:Computer:Software + $-100.00 Liabilities:MasterCard +@end smallexample + @node Commodities and Currencies, Accounts and Inventories, Assets and Liabilities, Principles of Accounting with Ledger @section Commodities and Currencies @@ -886,7 +1030,7 @@ be any commodity, in which case the balance will be computed in terms of that commodity. The usual way to specify prices is with a price history file, which might look like this: -@smallexample +@smallexample @c input:validate P 2004/06/21 02:18:01 FEQTX $22.49 P 2004/06/21 02:18:01 BORL $6.20 P 2004/06/21 02:18:02 AAPL $32.91 @@ -944,7 +1088,7 @@ that commodity on that day. It is also possible, by recording price details in a ledger file, to specify other prices for commodities at any given time. Such price transactions might look like those below: -@smallexample +@smallexample @c input:validate P 2004/06/21 02:17:58 TWCUX $27.76 P 2004/06/21 02:17:59 AGTHX $25.41 P 2004/06/21 02:18:00 OPTFX $39.31 @@ -970,7 +1114,7 @@ transfers an hour of time into a @samp{Billable} account, and another which decreases the same account by ten minutes. The resulting report will indicate that fifty minutes remain: -@smallexample +@smallexample @c input:DF3FEBE 2005/10/01 Work done for company Billable:Client 1h Project:XYZ @@ -982,9 +1126,13 @@ will indicate that fifty minutes remain: Reporting the balance for this ledger file produces: -@smallexample - 50.0m Billable:Client - -50.0m Project:XYZ +@smallexample @c command:DF3FEBE +$ ledger --no-total balance Billable Project +@end smallexample + +@smallexample @c output:DF3FEBE + 50.0m Billable:Client + -50.0m Project:XYZ @end smallexample This example works because ledger already knows how to handle seconds, @@ -993,7 +1141,7 @@ other equivalencies is simple. The following is an example that creates data equivalencies, helpful for tracking bytes, kilobytes, megabytes, and more: -@smallexample +@smallexample @c input:validate C 1.00 Kb = 1024 b C 1.00 Mb = 1024 Kb C 1.00 Gb = 1024 Mb @@ -1021,7 +1169,7 @@ various items in EverQuest, and want to keep track of them using a ledger. Just add items of whatever quantity you wish into your EverQuest account: -@smallexample +@smallexample @c input:48F4E47 9/29 Get some stuff at the Inn Places:Black's Tavern -3 Apples Places:Black's Tavern -5 Steaks @@ -1034,13 +1182,13 @@ Tavern in order to add to your Inventory account. Note that you don't have to use @samp{Places:Black's Tavern} as the source account. You could use @samp{EverQuest:System} to represent the fact that you acquired them online. The only purpose for choosing one kind of -source account over another is for generate more informative reports -later on. The more you know, the better analysis you can perform. +source account over another is to generate more informative reports +later on. The more you know, the better the analysis you can perform. If you later sell some of these items to another player, the transaction would look like: -@smallexample +@smallexample @c input:48F4E47 10/2 Sturm Brightblade EverQuest:Inventory -2 Steaks EverQuest:Inventory 15 Gold @@ -1049,6 +1197,16 @@ transaction would look like: Now you've turned 2 steaks into 15 gold, courtesy of your customer, Sturm Brightblade. +@smallexample @c command:48F4E47 +$ ledger balance EverQuest +@end smallexample + +@smallexample @c output:48F4E47 + 3 Apples + 15 Gold + 3 Steaks EverQuest:Inventory +@end smallexample + @node Understanding Equity, Dealing with Petty Cash, Accounts and Inventories, Principles of Accounting with Ledger @section Understanding Equity @@ -1058,9 +1216,9 @@ account---because starting balances can't come out of nowhere. When you first start your ledger, you will likely already have money in some of your accounts. Let's say there's $100 in your checking account; then add a transaction to your ledger to reflect this amount. -Where will money come from? The answer: your equity. +Where will the money come from? The answer: your equity. -@smallexample +@smallexample @c input:validate 10/2 Opening Balance Assets:Checking $100.00 Equity:Opening Balances @@ -1085,7 +1243,7 @@ assets is greater than the absolute value of your starting equity, it means you are making money. Clear as mud? Keep thinking about it. Until you figure it out, put -@code{-Equity} at the end of your balance command, to remove the +@code{not Equity} at the end of your balance command, to remove the confusing figure from the total. @node Dealing with Petty Cash, Working with multiple funds and accounts, Understanding Equity, Principles of Accounting with Ledger @@ -1100,7 +1258,7 @@ One solution is: don't bother. Move your spending to a debit card, but in general ignore cash. Once you withdraw it from the ATM, mark it as already spent to an @samp{Expenses:Cash} category: -@smallexample +@smallexample @c input:validate 2004/03/15 ATM Expenses:Cash $100.00 Assets:Checking @@ -1110,7 +1268,7 @@ If at some point you make a large cash expense that you want to track, just @emph{move} the amount of the expense from @samp{Expenses:Cash} into the target account: -@smallexample +@smallexample @c input:validate 2004/03/20 Somebody Expenses:Food $65.00 Expenses:Cash @@ -1144,7 +1302,7 @@ reserves resources for later: @item Community fund @end itemize -The problem with this kind of setup is that when you spend money, it +The problem with this kind of setup is that, when you spend money, it comes from two or more places at once: the account and the fund. And yet, the correlation of amounts between funds and accounts is rarely one-to-one. What if the school fund has @samp{$500.00}, but @@ -1161,7 +1319,7 @@ This situation can be handled one of two ways. The first is using virtual postings to represent the fact that money is moving to and from two kind of accounts at the same time: -@smallexample +@smallexample @c input:396F24E 2004/03/20 Contributions Assets:Checking $500.00 Income:Donations @@ -1177,7 +1335,7 @@ virtual postings balance to zero. Now money can be spent directly from a fund at the same time as money is drawn from a physical account: -@smallexample +@smallexample @c input:396F24E 2004/03/25 Payment for books (paid from Checking) Expenses:Books $100.00 Assets:Checking $-100.00 @@ -1189,16 +1347,30 @@ funds. In this case, you will likely want to mask out your @samp{Assets} account, because otherwise the balance won't make much sense: -@smallexample -$ ledger bal -^Assets +@smallexample @c command:396F24E +$ ledger --no-total bal not ^Assets +@end smallexample + +@smallexample @c output:396F24E + $100.00 Expenses:Books + $400.00 Funds + $200.00 Building + $200.00 School + $-500.00 Income:Donations @end smallexample @findex --real If the @option{--real} option is used, the report will be in terms of the real accounts: -@smallexample -$ ledger --real bal +@smallexample @c command:2F1CB75,with_input:396F24E +$ ledger --real --no-total bal +@end smallexample + +@smallexample @c output:2F1CB75 + $400.00 Assets:Checking + $100.00 Expenses:Books + $-500.00 Income:Donations @end smallexample If more asset accounts are needed as the source of a posting, just @@ -1218,39 +1390,52 @@ set of postings. Basically, we are associating a transaction with a fund by setting its code. Here are two transactions that deposit money into, and spend money from, the @samp{Funds:School} fund: -@smallexample +@smallexample @c input:AD068BA 2004/03/25 (Funds:School) Donations Assets:Checking $100.00 Income:Donations +2004/03/25 (Funds:Building) Donations + Assets:Checking $20.00 + Income:Donations + 2004/04/25 (Funds:School) Payment for books Expenses:Books $50.00 Assets:Checking @end smallexample Note how the accounts now relate only to the real accounts, and any -balance or registers reports will reflect this. That the transactions +balance or register reports will reflect this. That the transactions relate to a particular fund is kept only in the code. -@findex --code-as-payee +@findex --payee=code @findex --by-payee How does this become a fund report? By using the -@option{--code-as-payee} option, you can generate a register report +@option{--payee=code} option, you can generate a register report where the payee for each posting shows the code. Alone, this is not terribly interesting; but when combined with the @option{--by-payee (-P)} option, you will now see account subtotals for any postings related to a specific fund. So, to see the current monetary balances of all funds, the command would be: -@smallexample -$ ledger --code-as-payee -P reg ^Assets +@smallexample @c command:AD068BA +$ ledger --payee=code -P reg ^Assets @end smallexample -Or to see a particular funds expenses, the @samp{School} fund in this +@smallexample @c output:AD068BA +04-Mar-25 Funds:Building Assets:Checking $20.00 $20.00 +04-Mar-25 Funds:School Assets:Checking $50.00 $70.00 +@end smallexample + +Or to see a particular fund's expenses, the @samp{School} fund in this case: -@smallexample -$ ledger --code-as-payee -P reg ^Expenses @@School +@smallexample @c command:E30B2FC,with_input:AD068BA +$ ledger --payee=code -P reg ^Expenses and code School +@end smallexample + +@smallexample @c output:E30B2FC +04-Apr-25 Funds:School Expenses:Books $50.00 $50.00 @end smallexample Both approaches yield different kinds of flexibility, depending on how @@ -1307,9 +1492,9 @@ posting. @section The Most Basic Entry Here is the Pacific Bell example from above, given as a Ledger -posting, with the additional of a check number: +posting, with the addition of a check number: -@smallexample +@smallexample @c input:validate 9/29 (1023) Pacific Bell Expenses:Utilities:Phone $23.00 Assets:Checking $-23.00 @@ -1321,7 +1506,7 @@ work better with Ledger's scheme of things. In fact, since Ledger is smart about many things, you don't need to specify the balanced amount, if it is the same as the first line: -@smallexample +@smallexample @c input:validate 9/29 (1023) Pacific Bell Expenses:Utilities:Phone $23.00 Assets:Checking @@ -1363,7 +1548,7 @@ basis of the opening entry for ledger. For example if you chose the beginning of 2011 as the date to start tracking finances with ledger, your opening balance entry could look like this: -@smallexample +@smallexample @c input:validate 2011/01/01 * Opening Balance Assets:Joint Checking $800.14 Assets:Other Checking $63.44 @@ -1419,28 +1604,28 @@ Expenses:Food:Hamburgers and Fries Comments are generally started using a @samp{;}. However, in order to increase compatibility with other text manipulation programs and -methods four additional comment characters are valid if used at the +methods, four additional comment characters are valid if used at the beginning of a line: @samp{#}, @samp{|}, and @samp{*} and @samp{%}. -Block comments can be made by use @code{@!comment} ... @code{@!end +Block comments can be made by use @code{comment} ... @code{end comment}. -@smallexample +@smallexample @c input:validate ; This is a single line comment, # and this, % and this, | and this, * and this. -!comment +comment This is a block comment with multiple lines -!end comment +end comment @end smallexample There are several forms of comments within a transaction, for example: -@smallexample +@smallexample @c input:validate ; this is a global comment that is not applied to a specific transaction ; it can start with any of the five characters but is not included in the ; output from 'print' or 'output' @@ -1464,7 +1649,7 @@ start with @samp{;} and are preserved as part of the transaction. The @cindex commodity Ledger is agnostic when it comes to how you value your accounts. -Dollars, Euros, Pounds, Francs, Shares etc. are just ``commodities''. +Dollars, Euros, Pounds, Francs, Shares etc. are all just ``commodities''. Holdings in stocks, bonds, mutual funds and other financial instruments can be labeled using whatever is convenient for you (stock ticker symbols are suggested for publicly traded assets).@footnote{You @@ -1485,41 +1670,44 @@ reporting capabilities to convert all commodities to a single commodity for reporting purposes without ever changing the underlying entry. -For example, the following entries reflect transaction made for a +For example, the following entries reflect transactions made for a business trip to Europe from the US: -@smallexample +@smallexample @c input:82150D9 2011/09/23 Cash in Munich - Assets:Cash E50.00 + Assets:Cash €50.00 Assets:Checking $-66.00 2011/09/24 Dinner in Munich - Expenses:Business:Travel E35.00 + Expenses:Business:Travel €35.00 Assets:Cash @end smallexample This says that $66.00 came out of checking and turned into 50 -Euros. The implied exchange rate was $1.32. Then 35.00 Euros was +Euros. The implied exchange rate was $1.32. Then 35.00 Euros were spent on Dinner in Munich. Running a ledger balance report shows: -@smallexample +@smallexample @c command:82150D9 $ ledger -f example.dat bal +@end smallexample + +@smallexample @c output:82150D9 $-66.00 - E15.00 Assets - E15.00 Cash + €15.00 Assets + €15.00 Cash $-66.00 Checking - E35.00 Expenses:Business:Travel + €35.00 Expenses:Business:Travel -------------------- $-66.00 - E50.00 + €50.00 @end smallexample The top two lines show my current assets as $-66.00 in checking (in this very short example I didn't establish opening an opening balance -for the checking account) and E15.00. After spending on dinner I have -E15.00 in my wallet. The bottom line balances to zero, but is shown +for the checking account) and €15.00. After spending on dinner I have +€15.00 in my wallet. The bottom line balances to zero, but is shown in two lines since we haven't told ledger to convert commodities. @menu @@ -1533,10 +1721,10 @@ in two lines since we haven't told ledger to convert commodities. @subsection Naming Commodities Commodity names can have any character, including white-space. -However, if you include white-space or numeric characters the +However, if you include white-space or numeric characters, the commodity name must be enclosed in double quotes @samp{"}: -@smallexample +@smallexample @c input:validate 1999/06/09 ! Achat Actif:SG PEE STK 49.957 "Arcancia Équilibre 454" Actif:SG PEE STK $-234.90 @@ -1556,22 +1744,22 @@ multiple commodities in the same transaction. The type of the share unit you made the purchase in ($ for AAPL). Yes, the typical convention is as follows: -@smallexample +@smallexample @c input:validate 2004/05/01 Stock purchase Assets:Broker 50 AAPL @@ $30.00 Expenses:Broker:Commissions $19.95 - Assets:Broker $-1,500.00 + Assets:Broker $-1,519.95 @end smallexample -This assumes you have a brokerage account that is capable of managed +This assumes you have a brokerage account that is capable of managing both liquid and commodity assets. Now, on the day of the sale: -@smallexample +@smallexample @c input:validate 2005/08/01 Stock sale Assets:Broker -50 APPL @{$30.00@} @@ $50.00 Expenses:Broker:Commissions $19.95 Income:Capital Gains $-1,000.00 - Assets:Broker $2,500.00 + Assets:Broker $2,480.05 @end smallexample @noindent @@ -1588,7 +1776,7 @@ longest-held-first. @cindex fixing lot prices @cindex consumable commodity pricing -Commodities that you keep in order to sell them at a later time have +Commodities that you keep in order to sell at a later time have a variable value that fluctuates with the market prices. Commodities that you consume should not fluctuate in value, but stay at the lot price they were purchased at. As an extension of ``lot pricing'', you @@ -1602,7 +1790,7 @@ reported in terms of today's price. This is supported as follows: -@smallexample +@smallexample @c input:validate 2009/01/01 Shell Expenses:Gasoline 11 GAL @{=$2.299@} Assets:Checking @@ -1614,9 +1802,9 @@ price of gasoline. If you do not want price fixing, you can specify this same transaction in one of two ways, both equivalent (note the lack of the equal sign -from the transaction above): +compared to the transaction above): -@smallexample +@smallexample @c input:validate 2009/01/01 Shell Expenses:Gasoline 11 GAL @{$2.299@} Assets:Checking @@ -1629,7 +1817,7 @@ from the transaction above): There is no difference in meaning between these two forms. Why do both exist, you ask? To support things like this: -@smallexample +@smallexample @c input:validate 2009/01/01 Shell Expenses:Gasoline 11 GAL @{=$2.299@} @@ $2.30 Assets:Checking @@ -1649,12 +1837,12 @@ Assets:Checking because its amount is null. Ledger allows you to have very detailed control over how your commodities are valued. You can fine tune the results given using the @option{--market} or @option{--exchange @var{COMMODITY}} options. There -are now several points of interception, you can specify the valuation +are now several points of interception; you can specify the valuation method: @enumerate @item on a commodity itself, -@item on a posting, via metadata (affect is largely the same as #1), +@item on a posting, via metadata (effect is largely the same as #1), @item on an xact, which then applies to all postings in that xact, @item on any posting via an automated transaction, @item on a per-account basis, @@ -1741,7 +1929,7 @@ function on a transaction-wide or per-posting basis. Lastly, you can specify the valuation function/value for any specific amount using the @samp{(( ))} commodity annotation. -@smallexample +@smallexample @c input:814A366 2012-03-02 KFC Expenses:Food2 $1 ((2 EUR)) Assets:Cash2 @@ -1777,20 +1965,24 @@ amount using the @samp{(( ))} commodity annotation. Assets:Cash9 @end smallexample -@smallexample -ledger reg -V food +@smallexample @c command:814A366 +$ ledger reg -V food +@end smallexample + +@smallexample @c output:814A366 12-Mar-02 KFC Expenses:Food2 2 EUR 2 EUR -12-Mar-03 KFC <Adjustment> -1 EUR 1 EUR - Expenses:Food3 3 EUR 4 EUR -12-Mar-04 KFC <Adjustment> -2 EUR 2 EUR - Expenses:Food4 4 EUR 6 EUR -12-Mar-05 KFC <Adjustment> -3 EUR 3 EUR - Expenses:Food5 5 EUR 8 EUR -12-Mar-06 KFC <Adjustment> -4 EUR 4 EUR - Expenses:Food6 6 EUR 10 EUR -12-Mar-07 KFC Expenses:Food7 7 EUR 17 EUR -12-Mar-08 XACT Expenses:Food8 8 EUR 25 EUR -12-Mar-09 POST (Expenses:Food9) 9 EUR 34 EUR +12-Mar-03 KFC Expenses:Food3 3 EUR 5 EUR +12-Mar-04 KFC Expenses:Food4 4 EUR 9 EUR +12-Mar-05 KFC Expenses:Food5 $1 $1 + 9 EUR +12-Mar-06 KFC Expenses:Food6 $1 $2 + 9 EUR +12-Mar-07 KFC Expenses:Food7 1 CAD $2 + 1 CAD + 9 EUR +12-Mar-08 XACT Expenses:Food8 $1 $3 + 1 CAD + 9 EUR @end smallexample @node Keeping it Consistent, Journal Format, Currency and Commodities, Keeping a Journal @@ -1803,9 +1995,9 @@ freeform text editor to enter transactions makes it easy to keep the data, but also easy to enter accounts or payees inconsistently or with spelling errors. -In order to combat inconsistency you can define allowable accounts and -or payees. For simplicity, create a separate text file and enter -define accounts a payees like +In order to combat inconsistency you can define allowable accounts and +payees. For simplicity, create a separate text file and define accounts +and payees like @smallexample account Expenses @@ -1831,7 +2023,7 @@ $ ledger accounts >> Accounts.dat @end smallexample @noindent -You will have to edit this file to add the @code{account} directive. +You will have to edit this file to add the @code{account} directive in front of every line. @node Journal Format, Converting from other formats, Keeping it Consistent, Keeping a Journal @section Journal Format @@ -1875,7 +2067,7 @@ payee, or a description of the posting. The format of each following posting is: @smallexample -ACCOUNT AMOUNT [; NOTE] + ACCOUNT AMOUNT [; NOTE] @end smallexample The @code{ACCOUNT} may be surrounded by parentheses if it is a virtual @@ -1902,24 +2094,24 @@ An automated transaction. A value expression must appear after the equal sign. After this initial line there should be a set of one or more postings, -just as if it were normal transaction. If the amounts of the postings -have no commodity, they will be applied as modifiers to whichever real +just as if it were a normal transaction. If the amounts of the postings +have no commodity, they will be applied as multipliers to whichever real posting is matched by the value expression (@pxref{Automated Transactions}). @item ~ -A period transaction. A period expression must appear after the tilde. +A periodic transaction. A period expression must appear after the tilde. After this initial line there should be a set of one or more -postings, just as if it were normal transaction. +postings, just as if it were a normal transaction. @item ; # % | * -A line beginning with a colon, pound, percent, bar or asterisk +A line beginning with a semicolon, pound, percent, bar or asterisk indicates a comment, and is ignored. Comments will not be returned in a ``print'' response. @item indented ; -If the semi colon is indented and occurs inside a transaction, it is +If the semicolon is indented and occurs inside a transaction, it is parsed as a persistent note for its preceding category. These notes or tags can be used to augment the reporting and filtering capabilities of Ledger. @@ -1938,13 +2130,13 @@ Command directives must occur at the beginning of a line. Use of @samp{!} and @samp{@@} is deprecated. @item account -Pre-declare valid account names. This only has effect if +Pre-declare valid account names. This only has an effect if @option{--strict} or @option{--pedantic} is used (see below). The @code{account} directive supports several optional sub-directives, if they immediately follow the account directive and if they begin with whitespace: -@smallexample +@smallexample @c input:validate account Expenses:Food note This account is all about the chicken! alias food @@ -1956,7 +2148,7 @@ account Expenses:Food @end smallexample The @code{note} sub-directive associates a textual note with the -account. This can be accessed later using the @code{note} valexpr +account. This can be accessed later using the @code{note} value expression function in any account context. The @code{alias} sub-directive, which can occur multiple times, allows @@ -1968,13 +2160,13 @@ provides regexes that identify the account if that payee is encountered and an account within its transaction ends in the name "Unknown". Example: -@smallexample +@smallexample @c input:validate 2012-02-27 KFC Expenses:Unknown $10.00 ; Read now as "Expenses:Food" Assets:Cash @end smallexample -The @code{check} and @code{assert} directives warn or error +The @code{check} and @code{assert} directives warn or raise an error (respectively) if the given value expression evaluates to false within the context of any posting. @@ -1988,32 +2180,32 @@ contain only a single posting. @item apply account @c instance_t::master_account_directive -Sets the root for all accounts following the directive. Ledger +Sets the root for all accounts following this directive. Ledger supports a hierarchical tree of accounts. It may be convenient to keep two ``root accounts''. For example you may be tracking your personal finances and your business finances. In order to keep them separate you could preface all personal accounts with @samp{personal:} -and all business account with @samp{business:}. You can easily split -out large groups of transaction without manually editing them using +and all business accounts with @samp{business:}. You can easily split +out large groups of transactions without manually editing them using the account directive. For example: -@smallexample +@smallexample @c input:validate apply account Personal 2011/11/15 Supermarket - Expenses:Groceries + Expenses:Groceries $ 50.00 Assets:Checking @end smallexample Would result in all postings going into @samp{Personal:Expenses:Groceries} and @samp{Personal:Assets:Checking} -until and @samp{end apply account} directive was found. +until an @samp{end apply account} directive was found. @item alias @c instance_t::alias_directive Define an alias for an account name. If you have a deeply nested tree of accounts, it may be convenient to define an alias, for example: -@smallexample +@smallexample @c input:validate alias Dining=Expenses:Entertainment:Dining alias Checking=Assets:Credit Union:Joint Checking Account @@ -2023,9 +2215,42 @@ alias Checking=Assets:Credit Union:Joint Checking Account @end smallexample The aliases are only in effect for transactions read in after the alias -is defined and are effected by @code{account} directives that precede +is defined and are affected by @code{account} directives that precede them. +@smallexample @c command:validate +$ ledger bal --no-total ^Exp +@end smallexample + +@smallexample + $10.00 Expenses:Entertainment:Dining +@end smallexample + +With the option @option{--recursive-aliases}, aliases can refer to other aliases, +the following example produces exactly the same transactions and account names +as the preceding one: + +@smallexample @c input:validate +alias Entertainment=Expenses:Entertainment +alias Dining=Entertainment:Dining +alias Checking=Assets:Credit Union:Joint Checking Account + +2011/11/30 ChopChop + Dining $10.00 + Checking +@end smallexample + +@smallexample @c command:validate +$ ledger balance --no-total --recursive-aliases ^Exp +@end smallexample + +@smallexample + $10.00 Expenses:Entertainment:Dining +@end smallexample + +The option @option{--no-aliases} completely disables alias expansion. +All accounts are read verbatim as they are in the ledger file. + @item assert @c instance_t::assert_directive An assertion can throw an error if a condition is not met during @@ -2040,13 +2265,14 @@ assert <VALUE EXPRESSION BOOLEAN RESULT> Defines the default account to use for balancing transactions. Normally, each transaction has at least two postings, which must balance to zero. Ledger allows you to leave one posting with no -amount and automatically calculate balance the transaction in the +amount and automatically balance the transaction in the posting. The @code{bucket} allows you to fill in all postings and automatically generate an additional posting to the bucket account -balancing the transaction. The following example set the -@samp{Assets:Checking} as the bucket: +balancing the transaction. If any transaction is unbalanced, it +will automatically be balanced against the @code{bucket} account. +The following example sets @samp{Assets:Checking} as the bucket: -@smallexample +@smallexample @c input:validate bucket Assets:Checking 2011/01/25 Tom's Used Cars Expenses:Auto $ 5,500.00 @@ -2066,7 +2292,7 @@ bucket Assets:Checking Directs Ledger to replace any account matching a regex with the given account. For example: -@smallexample +@smallexample @c input:validate capture Expenses:Deductible:Medical Medical @end smallexample @@ -2078,7 +2304,7 @@ Ledger will display the mapped payees in @command{print} and @item check @c instance_t::check_directive in textual.cc -A check can issue a warning if a condition is not met during Ledger's +A check issues a warning if a condition is not met during Ledger's run. @smallexample @@ -2090,19 +2316,19 @@ check <VALUE EXPRESSION BOOLEAN RESULT> Start a block comment, closed by @code{end comment}. @item commodity -Pre-declare commodity names. This only has effect if @option{--strict} +Pre-declare commodity names. This only has an effect if @option{--strict} or @option{--pedantic} is used (see below). -@smallexample +@smallexample @c input:validate commodity $ commodity CAD @end smallexample The @code{commodity} directive supports several optional -sub-directives, if they immediately follow the commodity directive and -if they begin with whitespace: +sub-directives, if they immediately follow the commodity directive +and---if they are on successive lines---begin with whitespace: -@smallexample +@smallexample @c input:validate commodity $ note American Dollars format $1,000.00 @@ -2113,21 +2339,21 @@ commodity $ The @code{note} sub-directive associates a textual note with the commodity. At present this has no value other than documentation. -The @code{format} directive gives you a way to tell Ledger how to -format this commodity. In future using this directive will disable +The @code{format} sub-directive gives you a way to tell Ledger how to +format this commodity. In the future, using this directive will disable Ledger's observation of other ways that commodity is used, and will provide the ``canonical'' representation. -The @code{nomarket} directive states that the commodity's price should +The @code{nomarket} sub-directive states that the commodity's price should never be auto-downloaded. -The @code{default} directive marks this as the ``default'' commodity. +The @code{default} sub-directive marks this as the ``default'' commodity. @item define @c instance_t::define_directive in textual.cc -Allows you to define value expression for future use. For example: +Allows you to define value expressions for future use. For example: -@smallexample +@smallexample @c input:validate define var_name=$100 2011/12/01 Test @@ -2153,21 +2379,21 @@ use when entering many transactions with fixated prices. Thus, the following: -@smallexample +@smallexample @c input:validate fixed CAD $0.90 - 2012-04-10 Lunch in Canada - Assets:Wallet -15.50 CAD - Expenses:Food 15.50 CAD +2012-04-10 Lunch in Canada + Assets:Wallet -15.50 CAD + Expenses:Food 15.50 CAD - 2012-04-11 Second day Dinner in Canada - Assets:Wallet -25.75 CAD - Expenses:Food 25.75 CAD +2012-04-11 Second day Dinner in Canada + Assets:Wallet -25.75 CAD + Expenses:Food 25.75 CAD endfixed @end smallexample is equivalent to this: -@smallexample +@smallexample @c input:validate 2012-04-10 Lunch in Canada Assets:Wallet -15.50 CAD @{=$0.90@} Expenses:Food 15.50 CAD @{=$0.90@} @@ -2195,15 +2421,15 @@ Include the stated file as if it were part of the current file. @findex register The @code{payee} directive supports one optional sub-directive, if it -immediately follows the payee directive and if it begins with -whitespace: +immediately follows the payee directive and---if it is on a successive +line---begins with whitespace: -@smallexample +@smallexample @c input:validate payee KFC alias KENTUCKY FRIED CHICKEN @end smallexample -The @code{alias} directive provides a regex which, if it matches +The @code{alias} sub-directive provides a regex which, if it matches a parsed payee, the declared payee name is substituted: @smallexample @@ -2219,7 +2445,7 @@ Ledger will display the mapped payees in @command{print} and Allows you to designate a block of transactions and assign the same tag to all. Tags can have values and may be nested. -@smallexample +@smallexample @c input:validate apply tag hastag apply tag nestedtag: true @@ -2232,67 +2458,70 @@ apply tag nestedtag: true Expenses:Books $20.00 Liabilities:MasterCard -end apply tag nestedtag +end apply tag 2011/12/01 Sale Assets:Checking:Business $ 30.00 Income:Sales -end apply tag hastag +end apply tag @end smallexample @noindent is the equivalent of: -@smallexample +@smallexample @c input:validate 2011/01/25 Tom's Used Cars - :hastag: - nestedtag: true + ; :hastag: + ; nestedtag: true Expenses:Auto $ 5,500.00 ; :nobudget: Assets:Checking 2011/01/27 Book Store - :hastag: - nestedtag: true + ; :hastag: + ; nestedtag: true Expenses:Books $20.00 Liabilities:MasterCard 2011/12/01 Sale - :hastag: + ; :hastag: Assets:Checking:Business $ 30.00 Income:Sales @end smallexample -Note that anything following @code{end apply tag} is ignored. placing -the name of the tag that is being closed is a simple way to keep -track. +@c TODO: the following paragraph seems to be false, the automated tests +@c fail, if anything appears after end apply tag. + +@c Note that anything following @code{end apply tag} is ignored. placing +@c the name of the tag that is being closed is a simple way to keep +@c track. @item tag -Pre-declares tag names. This only has effect if @option{--strict} or +Pre-declares tag names. This only has an effect if @option{--strict} or @option{--pedantic} is used (see below). -@smallexample +@smallexample @c input:validate tag Receipt tag CSV @end smallexample The @code{tag} directive supports two optional sub-directives, if they -immediately follow the tag directive and if they begin with -whitespace: +immediately follow the tag directive and---if on a successive line---begin +with whitespace: -@smallexample +@smallexample @c input:validate tag Receipt check value =~ /pattern/ assert value != "foobar" @end smallexample -The @code{check} and @code{assert} directives warn or error +The @code{check} and @code{assert} sub-directives warn or error (respectively) if the given value expression evaluates to false within the context of any use of the related tag. In such a context, -``value'' is bound to the value of the tag (which may not be a string -if typed-metadata is used!). Such checks or assertions are not called -if no value is given. +``value'' is bound to the value of the tag (which may be something else +but a string if typed metadata is used!). Such checks or assertions are +not called if no value is given. @item test @c instance_t::comment_directive in textual.cc @@ -2342,7 +2571,7 @@ whichever is seen last is used as the default commodity. For example, to set US dollars as the default commodity, while also setting the thousands flag and decimal flag for that commodity, use: -@smallexample +@smallexample @c input:validate D $1,000.00 @end smallexample @@ -2351,13 +2580,13 @@ Specifies a commodity conversion, where the first amount is given to be equivalent to the second amount. The first amount should use the decimal precision desired during reporting: -@smallexample +@smallexample @c input:validate C 1.00 Kb = 1024 bytes @end smallexample @item I, i, O, o, b, h These four relate to timeclock support, which permits Ledger to read -timelog files. See the timeclock's documentation for more info on the +timelog files. See timeclock's documentation for more info on the syntax of its timelog files. @end table @@ -2477,7 +2706,7 @@ doing it. The most basic form of transaction is: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Assets:Cash $-20.00 @@ -2489,7 +2718,7 @@ posting specifies what action is taken related to that account. A transaction can have any number of postings: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Assets:Cash $-10.00 @@ -2503,7 +2732,7 @@ The first thing you can do to make things easier is elide amounts. That is, if exactly one posting has no amount specified, Ledger will infer the inverse of the other postings' amounts: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Assets:Cash $-10.00 @@ -2515,7 +2744,7 @@ If the other postings use multiple commodities, Ledger will copy the empty posting N times and fill in the negated values of the various commodities: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Expenses:Tips $2.00 @@ -2527,7 +2756,7 @@ commodities: @noindent This transaction is identical to writing: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Expenses:Tips $2.00 @@ -2545,7 +2774,7 @@ This transaction is identical to writing: You can associate a second date with a transaction by following the primary date with an equals sign: -@smallexample +@smallexample @c input:validate 2012-03-10=2012-03-08 KFC Expenses:Food $20.00 Assets:Cash $-20.00 @@ -2553,8 +2782,8 @@ primary date with an equals sign: What this auxiliary date means is entirely up to you. The only use Ledger has for it is that if you specify @option{--aux-date}, then all -reports and calculations (including pricing) will use the aux date as if -it were the primary date. +reports and calculations (including pricing) will use the auxiliary +date as if it were the primary date. @node Codes, Transaction state, Auxiliary dates, Transactions @section Codes @@ -2564,7 +2793,7 @@ only displayed by the print command. Checking accounts often use codes like DEP, XFER, etc., as well as check numbers. This is to give you a place to put those codes: -@smallexample +@smallexample @c input:validate 2012-03-10 (#100) KFC Expenses:Food $20.00 Assets:Checking @@ -2577,10 +2806,10 @@ you a place to put those codes: @findex --pending A transaction can have a ``state'': cleared, pending, or uncleared. -The default is uncleared. To mark a transaction cleared, put a * -before the payee, and after date or code: +The default is uncleared. To mark a transaction cleared, put an asterisk (*) +before the payee, after the date or code: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2589,14 +2818,14 @@ before the payee, and after date or code: @noindent To mark it pending, use a !: -@smallexample +@smallexample @c input:validate 2012-03-10 ! KFC Expenses:Food $20.00 Assets:Cash @end smallexample What these mean is entirely up to you. The @option{--cleared} option -will limits to reports to only cleared items, while @option{--uncleared} +limits reports to only cleared items, while @option{--uncleared} shows both uncleared and pending items, and @option{--pending} shows only pending items. @@ -2607,7 +2836,7 @@ a reconciliation. When you clear a transaction, that's really just shorthand for clearing all of its postings. That is: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2616,7 +2845,7 @@ clearing all of its postings. That is: @noindent Is the same as writing: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC * Expenses:Food $20.00 * Assets:Cash @@ -2626,7 +2855,7 @@ Is the same as writing: You can mark individual postings as cleared or pending, in case one ``side'' of the transaction has cleared, but the other hasn't yet: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Liabilities:Credit $100.00 * Assets:Checking @@ -2636,10 +2865,10 @@ You can mark individual postings as cleared or pending, in case one @section Transaction notes After the payee, and after at least one tab or two spaces (or a space -and a tab, which Ledger calls this a ``hard separator''), you may +and a tab, which Ledger calls a ``hard separator''), you may introduce a note about the transaction using the @samp{;} character: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC ; yum, chicken... Expenses:Food $20.00 Assets:Cash @@ -2649,7 +2878,7 @@ introduce a note about the transaction using the @samp{;} character: Notes can also appear on the next line, so long as that line begins with whitespace: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC ; yum, chicken... ; and more notes... Expenses:Food $20.00 @@ -2661,12 +2890,12 @@ with whitespace: Assets:Cash @end smallexample -A transaction note is shared by all its postings. This becomes +A transaction's note is shared by all its postings. This becomes significant when querying for metadata (see below). To specify that a note belongs only to one posting, place it after a hard separator after the amount, or on its own line preceded by whitespace: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 ; posting #1 note Assets:Cash @@ -2690,7 +2919,7 @@ typed metadata with postings and transactions (by which I mean all of a transaction's postings). This metadata can be queried, displayed, and used in calculations. -The are two forms of metadata: tags and tag/value pairs. +The are two forms of metadata: plain tags, and tag/value pairs. @menu * Metadata tags:: @@ -2702,9 +2931,9 @@ The are two forms of metadata: tags and tag/value pairs. @subsection Metadata tags To tag an item, put any word not containing whitespace between two -colons: +colons inside a comment: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2713,7 +2942,7 @@ colons: You can gang up multiple tags by sharing colons: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2740,7 +2969,7 @@ This is useful when for example you deposit 4 checks at a time to the bank. On the bank statement, there is just one amount @samp{$400}, but you can specify from whom each check came from, as shown by example below: -@smallexample +@smallexample @c input:validate 2010-06-17 Sample Assets:Bank $400.00 Income:Check1 $-100.00 ; Payee: Person One @@ -2769,7 +2998,7 @@ To associate a value with a tag, use the syntax ``Key: Value'', where the value can be any string of characters. Whitespace is needed after the colon, and cannot appear in the Key: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2783,7 +3012,7 @@ If a metadata tag ends in ::, its value will be parsed as a value expression and stored internally as a value rather than as a string. For example, although I can specify a date textually like so: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2824,7 +3053,7 @@ reports using @option{--real}. To specify a virtual account, surround the account name with parentheses: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2835,7 +3064,7 @@ If you want, you can state that virtual postings @emph{should} balance against one or more other virtual postings by using brackets (which look ``harder'') rather than parentheses: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food $20.00 Assets:Cash @@ -2850,7 +3079,7 @@ An amount is usually a numerical figure with an (optional) commodity, but it can also be any value expression. To indicate this, surround the amount expression with parentheses: -@smallexample +@smallexample @c input:validate 2012-03-10 * KFC Expenses:Food ($10.00 + $20.00) ; Ledger adds it up for you Assets:Cash @@ -2900,7 +3129,7 @@ A balance assignment has this form: @end smallexample This sets the amount of the second posting to whatever it would need -to be for the total in Assets:Cash to be $500.00 after the posting. +to be for the total in @samp{Assets:Cash} to be $500.00 after the posting. If the resulting amount is not $-20.00 in this case, it is an error. @node Resetting a balance, Balancing transactions, Balance assignments, Balance verification @@ -2910,7 +3139,7 @@ Say your book-keeping has gotten a bit out of date, and your Ledger balance no longer matches your bank balance. You can create an adjustment transaction using balance assignments: -@smallexample +@smallexample @c input:validate 2012-03-10 Adjustment Assets:Cash = $500.00 Equity:Adjustments @@ -2920,7 +3149,7 @@ Since the second posting is also null, it's value will become the inverse of whatever amount is generated for the first posting. This is the only time in ledger when more than one posting's amount -may be empty---and then only because it's not true empty, it is +may be empty---and then only because it's not truly empty, it is indirectly provided by the balance assignment's value. @node Balancing transactions, , Resetting a balance, Balance verification @@ -2935,7 +3164,7 @@ As a consequence of all the above, consider the following transaction: @end smallexample What this says is: set the amount of the posting to whatever value is -needed so that Assets:Brokerage contains 10 AAPL. Then, because this +needed so that @samp{Assets:Brokerage} contains 10 AAPL. Then, because this posting must balance, ensure that its value is zero. This can only be true if Assets:Brokerage does indeed contain 10 AAPL at that point in the input file. @@ -2948,7 +3177,7 @@ anyway (unless you use a register report with @option{--empty}). @section Posting cost When you transfer a commodity from one account to another, sometimes -it get transformed during the transaction. This happens when you +it gets transformed during the transaction. This happens when you spend money on gas, for example, which transforms dollars into gallons of gasoline, or dollars into stocks in a company. @@ -2956,7 +3185,7 @@ In those cases, Ledger will remember the ``cost'' of that transaction for you, and can use it during reporting in various ways. Here's an example of a stock purchase: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL Assets:Brokerage:Cash $-500.00 @@ -2964,7 +3193,7 @@ example of a stock purchase: This is different from transferring 10 AAPL shares from one account to another, in this case you are @emph{exchanging} one commodity for -another. The resulting posting cost is $50.00 per share. +another. The resulting posting's cost is $50.00 per share. @node Explicit posting costs, Posting cost expressions, Posting cost, Transactions @section Explicit posting costs @@ -2972,16 +3201,16 @@ another. The resulting posting cost is $50.00 per share. You can make any posting's cost explicit using the @samp{@@} symbol after the amount or amount expression: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@ $50.00 Assets:Brokerage:Cash $-500.00 @end smallexample When you do this, since Ledger can now figure out the balancing amount -from the first posting's cost, you can elide the otheramount: +from the first posting's cost, you can elide the other amount: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@ $50.00 Assets:Brokerage:Cash @@ -3007,7 +3236,7 @@ Said another way, whenever Ledger sees a posting cost of the form "AMOUNT @@ AMOUNT", the commodity used in the second amount is marked ``primary''. -The only meaning a primary commodity has is that @option{--market (-V)} +The only meaning a primary commodity has is that the @option{--market (-V)} flag will never convert a primary commodity into any other commodity. @option{--exchange @var{COMMODITY} (-X)} still will, however. @@ -3017,7 +3246,7 @@ flag will never convert a primary commodity into any other commodity. Just as you can have amount expressions, you can have posting expressions: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@ ($500.00 / 10) Assets:Brokerage:Cash @@ -3025,7 +3254,7 @@ expressions: You can even have both: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage (5 AAPL * 2) @@ ($500.00 / 10) Assets:Brokerage:Cash @@ -3038,7 +3267,7 @@ The cost figure following the @samp{@@} character specifies the @emph{per-unit} price for the commodity being transferred. If you'd like to specify the total cost instead, use @samp{@@@@}: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@@@ $500.00 Assets:Brokerage:Cash @@ -3046,7 +3275,7 @@ like to specify the total cost instead, use @samp{@@@@}: Ledger reads this as if you had written: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@ ($500.00 / 10) Assets:Brokerage:Cash @@ -3061,7 +3290,7 @@ Ledger's internal price history database. To prevent this from happening in the case of an exceptional transaction, surround the @samp{@@} or @samp{@@@@} with parentheses: -@smallexample +@smallexample @c input:validate 2012-03-10 My Brother Assets:Brokerage 1000 AAPL (@@) $1 Income:Gifts Received @@ -3071,7 +3300,7 @@ happening in the case of an exceptional transaction, surround the @section Commodity prices @findex --lot-prices -When a transaction occurs that exchange one commodity for another, +When a transaction occurs that exchanges one commodity for another, Ledger records that commodity price not only within its internal price database, but also attached to the commodity itself. Usually this fact remains invisible to the user, unless you turn on @option{--lot-prices} @@ -3079,13 +3308,13 @@ to show these hidden price figures. For example, consider the stock sale given above: -@smallexample +@smallexample @c input:validate 2012-03-10 My Broker Assets:Brokerage 10 AAPL @@ $50.00 Assets:Brokerage:Cash @end smallexample -The commodity transferred into Assets:Brokerage is not actually 10 +The commodity transferred into @samp{Assets:Brokerage} is not actually 10 AAPL, but rather 10 AAPL @{$5.00@}. The figure in braces after the amount is called the ``lot price''. It's Ledger's way of remembering that this commodity was transferred through an exchange, and that @@ -3094,7 +3323,7 @@ $5.00 was the price of that exchange. This becomes significant if you later sell that commodity again. For example, you might write this: -@smallexample +@smallexample @c input:validate 2012-04-10 My Broker Assets:Brokerage:Cash Assets:Brokerage -10 AAPL @@ $75.00 @@ -3103,7 +3332,7 @@ example, you might write this: And that would be perfectly fine, but how do you track the capital gains on the sale? It could be done with a virtual posting: -@smallexample +@smallexample @c input:validate 2012-04-10 My Broker Assets:Brokerage:Cash Assets:Brokerage -10 AAPL @@ $75.00 @@ -3139,7 +3368,7 @@ As a shorthand, you can specify the total price instead of the per-share price in doubled braces. This goes well with total costs, but is not required to be used with them: -@smallexample +@smallexample @c input:validate 2012-04-10 My Broker Assets:Brokerage:Cash $750.00 Assets:Brokerage -10 AAPL @{@{$500.00@}@} @@@@ $750.00 @@ -3148,11 +3377,11 @@ but is not required to be used with them: It should be noted that this is a convenience only for cases where you buy and sell whole lots. The @{@{$500.00@}@} is @emph{not} an -attribute of commodity, whereas @{$5.00@} is. In fact, when you write +attribute of the commodity, whereas @{$5.00@} is. In fact, when you write @{@{$500.00@}@}, Ledger just divides that value by 10 and sees @{$50.00@}. So if you use the print command to look at this -transaction, you'll see the single form in the output. The double -price form is a shorthand only. +transaction, you'll see the single braces form in the output. +The double braces price form is a shorthand only. Plus, it comes with dangers. This works fine: @@ -3191,7 +3420,7 @@ But this does not do what you might expect: Income:Capital Gains $-125.00 @end smallexample -And in cases where the amounts do not divide into whole figure and +And in cases where the amounts do not divide into whole figures and must be rounded, the capital gains figure could be off by a cent. Use with caution. @@ -3283,7 +3512,7 @@ indicate a virtual cost: Income:Capital Gains $-125.00 @end smallexample -You can any combination of lot prices, dates or notes, in any order. +You can specify any combination of lot prices, dates or notes, in any order. They are all optional. To show all lot information in a report, use @option{--lots}. @@ -3301,7 +3530,7 @@ However, you can override this valuation logic by providing a commodity valuation expression in doubled parentheses. This expression must result in one of two values: either an amount to always be used as the per-share price for that commodity; or -a function taking three argument which is called to determine that +a function taking three arguments, which is called to determine that price. If you use the functional form, you can either specify a function @@ -3356,8 +3585,8 @@ indicate what is being desired. @end itemize In most cases, it is simplest to either use explicit amounts in your -valuation expressions, or just pass the arguments down to market after -modifying them to suit your needs. +valuation expressions, or just pass the arguments down to @samp{market} +after modifying them to suit your needs. @node Automated Transactions, , Lot value expressions, Transactions @section Automated Transactions @@ -3369,7 +3598,7 @@ same query syntax as the Ledger command line. Consider this posting: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Assets:Cash @@ -3377,7 +3606,7 @@ Consider this posting: If I write this automated transaction before it in the file: -@smallexample +@smallexample @c input:validate = expr true Foo $50.00 Bar $-50.00 @@ -3386,7 +3615,7 @@ If I write this automated transaction before it in the file: Then the first transaction will be modified during parsing as if I'd written this: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Foo $50.00 @@ -3423,7 +3652,7 @@ As a special case, if an automated transaction's posting's amount (phew) has no commodity, it is taken as a multiplier upon the matching posting's cost. For example: -@smallexample +@smallexample @c input:validate = expr true Foo 50.00 Bar -50.00 @@ -3435,7 +3664,7 @@ posting's cost. For example: Then the latter transaction turns into this during parsing: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 Foo $1000.00 @@ -3453,7 +3682,7 @@ posting, that expression has access to all the details of the matched posting. For example, you can refer to that posting's amount using the ``amount'' value expression variable: -@smallexample +@smallexample @c input:validate = expr true (Foo) (amount * 2) ; same as just "2" in this case @@ -3464,7 +3693,7 @@ the ``amount'' value expression variable: This becomes: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 (Foo) $40.00 @@ -3475,11 +3704,12 @@ This becomes: @node Referring to the matching posting's account, Applying metadata to every matched posting, Accessing the matching posting's amount, Automated Transactions @subsection Referring to the matching posting's account -Sometimes want to refer to the account that matched in some way within -the automated transaction itself. This is done by using the string -$account, anywhere within the account part of the automated posting: +Sometimes you want to refer to the account that was matched +in some way within the automated transaction itself. This is +done by using the string @samp{$account}, anywhere within the +account part of the automated posting: -@smallexample +@smallexample @c input:validate = food (Budget:$account) 10 @@ -3490,7 +3720,7 @@ $account, anywhere within the account part of the automated posting: Becomes: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 (Budget:Expenses:Food) $200.00 @@ -3504,7 +3734,7 @@ If the automated transaction has a transaction note, that note is copied (along with any metadata) to every posting that matches the predicate: -@smallexample +@smallexample @c input:validate = food ; Foo: Bar (Budget:$account) 10 @@ -3516,7 +3746,7 @@ predicate: Becomes: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 ; Foo: Bar @@ -3530,7 +3760,7 @@ Becomes: If the automated transaction's posting has a note, that note is carried to the generated posting within the matched transaction: -@smallexample +@smallexample @c input:validate = food (Budget:$account) 10 ; Foo: Bar @@ -3542,7 +3772,7 @@ carried to the generated posting within the matched transaction: Becomes: -@smallexample +@smallexample @c input:validate 2012-03-10 KFC Expenses:Food $20.00 (Budget:Expenses:Food) $200.00 @@ -3568,7 +3798,7 @@ the generated posting. @cindex effective dates @findex --effective -In the real world transactions do not take place instantaneously. +In the real world, transactions do not take place instantaneously. Purchases can take several days to post to a bank account. And you may pay ahead for something for which you want to distribute costs. With Ledger you can control every aspect of the timing of a transaction. @@ -3578,7 +3808,7 @@ something like @cindex effective date of invoice -@smallexample +@smallexample @c input:validate 2008/01/01=2008/01/14 Client invoice ; estimated date you'll be paid Assets:Accounts Receivable $100.00 Income: Client name @@ -3586,7 +3816,7 @@ something like Then, when you receive the payment, you change it to -@smallexample +@smallexample @c input:validate 2008/01/01=2008/01/15 Client invoice ; actual date money received Assets:Accounts Receivable $100.00 Income: Client name @@ -3595,7 +3825,7 @@ Then, when you receive the payment, you change it to @noindent and add something like -@smallexample +@smallexample @c input:validate 2008/01/15 Client payment Assets:Checking $100.00 Assets:Accounts Receivable @@ -3603,14 +3833,14 @@ and add something like Now -@smallexample +@smallexample @c command:validate $ ledger --begin 2008/01/01 --end 2008/01/14 bal Income @end smallexample @noindent gives you your accrued income in the first two weeks of the year, and -@smallexample +@smallexample @c command:validate $ ledger --effective --begin 2008/01/01 --end 2008/01/14 bal Income @end smallexample @@ -3626,7 +3856,7 @@ the money to be evenly distributed over the next six months so that your monthly budgets gradually take a hit for the vegetables you'll pick up from the co-op, even though you've already paid for them. -@smallexample +@smallexample @c input:6453542 2008/10/16 * (2090) Bountiful Blessings Farm Expenses:Food:Groceries $ 37.50 ; [=2008/10/01] Expenses:Food:Groceries $ 37.50 ; [=2008/11/01] @@ -3637,22 +3867,24 @@ pick up from the co-op, even though you've already paid for them. Assets:Checking @end smallexample -This entry accomplishes this. Every month until you'll start with an +This entry accomplishes this. Every month you'll see an automatic $37.50 deficit like you should, while your checking account really knows that it debited $225 this month. -And using @option{--effective} option, initial date will be overridden -by effective dates. +And using the @option{--effective} option, the initial date will be overridden +by the effective dates. -@smallexample +@smallexample @c command:6453542 $ ledger --effective register Groceries +@end smallexample -08-Oct-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 37.50 -08-Nov-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 75.00 -08-Dec-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 112.50 -09-Jan-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 150.00 -09-Feb-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 187.50 -09-Mar-01 Bountiful Blessi.. Expe:Food:Groceries $ 37.50 $ 225.00 +@smallexample @c output:6453542 +08-Oct-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 37.50 +08-Nov-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 75.00 +08-Dec-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 112.50 +09-Jan-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 150.00 +09-Feb-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 187.50 +09-Mar-01 Bountiful Blessings.. Expense:Food:Groceries $ 37.50 $ 225.00 @end smallexample @node Periodic Transactions, Concrete Example of Automated Transactions, Effective Dates, Automated Transactions @@ -3676,9 +3908,9 @@ complex, but if you have further interest, please consult the Web. Ledger makes this otherwise difficult law very easy. Just set up an automated posting at the top of your ledger file: -@smallexample +@smallexample @c input:C371854 ; This automated transaction will compute Huqúqu'lláh based on this -; journal's postings. Any that match will affect the +; journal's postings. Any accounts that match will affect the ; Liabilities:Huququ'llah account by 19% of the value of that posting. = /^(?:Income:|Expenses:(?:Business|Rent$|Furnishings|Taxes|Insurance))/ @@ -3690,12 +3922,24 @@ ledger file. If any match the given value expression, 19% of the posting's value is applied to the @samp{Liabilities:Huququ'llah} account. So, if $1000 is earned from @samp{Income:Salary}, $190 is added to @samp{Liabilities:Huqúqu'lláh}; if $1000 is spent on Rent, -$190 is subtracted. The ultimate balance of Huqúqu'lláh reflects how +$190 is subtracted. + +@smallexample @c input:C371854 +2003/01/01 (99) Salary + Income:Salary -$1000 + Assets:Checking + +2003/01/01 (100) Rent + Expenses:Rent $500 + Assets:Checking +@end smallexample + +The ultimate balance of Huqúqu'lláh reflects how much is owed in order to fulfill one's obligation to Huqúqu'lláh. When ready to pay, just write a check to cover the amount shown in @samp{Liabilities:Huququ'llah}. That transaction would look like: -@smallexample +@smallexample @c input:validate 2003/01/01 (101) Baha'i Huqúqu'lláh Trust Liabilities:Huququ'llah $1,000.00 Assets:Checking @@ -3704,17 +3948,22 @@ When ready to pay, just write a check to cover the amount shown in That's it. To see how much Huqúq is currently owed based on your ledger transactions, use: -@smallexample +@smallexample @c command:C371854 $ ledger balance Liabilities:Huquq @end smallexample -This works fine, but omits one aspect of the law: that Huquq is only +@smallexample @c output:C371854 + $-95 Liabilities:Huququ'llah +@end smallexample + +This works fine, but omits one aspect of the law: that Huqúq is only due once the liability exceeds the value of 19 mithqáls of gold (which is roughly 2.22 ounces). So what we want is for the liability to appear in the balance report only when it exceeds the present day value of 2.22 ounces of gold. This can be accomplished using the command: +@c TODO: fix this, it doesn't work any longer @smallexample $ ledger -Q -t "/Liab.*Huquq/?(a/P@{2.22 AU@}<=@{-1.0@}&a):a" bal liab @end smallexample @@ -3724,6 +3973,7 @@ Huqúqu'lláh is reported only if its value exceeds that of 2.22 ounces of gold. If you wish the liability to be reflected in the parent subtotal either way, use this instead: +@c TODO: fix this, it doesn't work any longer @smallexample $ ledger -Q -T "/Liab.*Huquq/?(O/P@{2.22 AU@}<=@{-1.0@}&O):O" bal liab @end smallexample @@ -3732,7 +3982,7 @@ In some cases, you may wish to refer to the account of whichever posting matched your automated transaction's value expression. To do this, use the special account name @samp{$account}: -@smallexample +@smallexample @c input:validate = /^Some:Long:Account:Name/ [$account] -0.10 [Savings] 0.10 @@ -3777,14 +4027,14 @@ options. The balance report is the most commonly used report. The simplest invocation is: -@smallexample +@smallexample @c command:1D00D56 $ ledger balance -f drewr3.dat @end smallexample @noindent which will print the balances of every account in your journal. -@smallexample +@smallexample @c output:1D00D56 $ -3,804.00 Assets $ 1,396.00 Checking $ 30.00 Business @@ -3807,12 +4057,15 @@ which will print the balances of every account in your journal. $ -243.60 @end smallexample -Most times this is more than you want. Limiting the results to +Most times, this is more than you want. Limiting the results to specific accounts is as easy as entering the names of the accounts -after the command. +after the command: -@smallexample +@smallexample @c command:06B2AD4 $ ledger balance -f drewr3.dat Auto MasterCard +@end smallexample + +@smallexample @c output:06B2AD4 $ 5,500.00 Expenses:Auto $ -20.00 Liabilities:MasterCard -------------------- @@ -3820,14 +4073,17 @@ $ ledger balance -f drewr3.dat Auto MasterCard @end smallexample @noindent -note the implicit logical and between @samp{Auto} and +Note the implicit logical or between @samp{Auto} and @samp{Mastercard}. If you want the entire contents of a branch of your account tree, use the highest common name in the branch: -@smallexample +@smallexample @c command:B0468E1 $ ledger balance -f drewr3.dat Income +@end smallexample + +@smallexample @c output:B0468E1 $ -2,030.00 Income $ -2,000.00 Salary $ -30.00 Sales @@ -3835,18 +4091,28 @@ $ ledger balance -f drewr3.dat Income $ -2,030.00 @end smallexample -You can use general regular expressions in nearly anyplace Ledger +You can use general regular expressions in nearly any place Ledger needs a string: -@smallexample +@smallexample @c command:EAE389F $ ledger balance -f drewr3.dat ^Bo +@end smallexample +@smallexample @c output:EAE389F +@end smallexample + +This first example looks for any account starting with @samp{Bo}, of +which there are none. + +@smallexample @c command:E2AF6AD $ ledger balance -f drewr3.dat Bo +@end smallexample + +@smallexample @c output:E2AF6AD $ 20.00 Expenses:Books @end smallexample -The first example looks for any account starting with @samp{Bo}, of -which there are none. The second looks for any account with @samp{Bo}, -which is @samp{Expenses:Books}. +This second example looks for any account containing @samp{Bo}, which is +@samp{Expenses:Books}. @cindex limit by payees @findex --limit @var{EXPR} @@ -3854,9 +4120,12 @@ which is @samp{Expenses:Books}. If you want to know exactly how much you have spent in a particular account on a particular payee, the following are equivalent: -@smallexample +@smallexample @c command:validate $ ledger balance Auto:Fuel and Chevron -$ ledger balance --limit "(account=~/Fuel/) & (payee=~/Chev/)" +@end smallexample + +@smallexample @c command:validate +$ ledger balance --limit 'account=~/Fuel/' and 'payee=~/Chev/' @end smallexample @noindent @@ -3869,8 +4138,8 @@ possibilities. If you want to exclude specific accounts from the report, you can exclude multiple accounts with parentheses: -@smallexample -$ ledger bal Expenses and not \(Expenses:Drinks or Expenses:Candy or Expenses:Gifts\) +@smallexample @c command:validate +$ ledger bal Expenses and not (Expenses:Drinks or Expenses:Candy or Expenses:Gifts) @end smallexample @node Controlling Formatting, , Controlling the Accounts and Payees, Balance Reports @@ -3886,6 +4155,7 @@ you want, or interface Ledger with other programs. A query such as the following shows all expenses since last October, sorted by total: +@c TODO: does not validate with @c command:validate, because "last oct" is split at the space @smallexample $ ledger -b "last oct" -S T bal ^expenses @end smallexample @@ -3909,7 +4179,7 @@ for all accounts that begin with @samp{expenses}. The following query makes it easy to see monthly expenses, with each month's expenses sorted by the amount: -@smallexample +@smallexample @c command:validate $ ledger -M --period-sort "(amount)" reg ^expenses @end smallexample @@ -3917,7 +4187,7 @@ Now, you might wonder where the money came from to pay for these things. To see that report, add @option{--related (-r)}, which shows the ``related account'' postings: -@smallexample +@smallexample @c command:validate $ ledger -M --period-sort "(amount)" -r reg ^expenses @end smallexample @@ -3927,8 +4197,8 @@ requires the use of a display predicate, since the postings calculated must match @samp{^expenses}, while the postings displayed must match @samp{mastercard}. The command would be: -@smallexample -$ ledger -M -r --display "account =~ /mastercard/" reg ^expenses +@smallexample @c command:validate +$ ledger -M -r --display 'account=~/mastercard/' reg ^expenses @end smallexample This query says: Report monthly subtotals; report the ``related @@ -3936,10 +4206,10 @@ account'' postings; display only related postings whose account matches @samp{mastercard}, and base the calculation on postings matching @samp{^expenses}. -This works just as well for report the overall total, too: +This works just as well for reporting the overall total, too: -@smallexample -$ ledger -s -r --display "account =~ /mastercard/" reg ^expenses +@smallexample @c command:validate +$ ledger -s -r --display "account=~/mastercard/" reg ^expenses @end smallexample The @option{--subtotal (-s)} option subtotals all postings, just as @@ -3965,11 +4235,11 @@ allocation in ledger is not difficult but does require some additional effort to describe how the various assets you own contribute to the asset classes you want to track. -In our simple example we assume you want to apportion you assets into +In our simple example we assume you want to apportion your assets into the general categories of domestic and international equities (stocks) -and a combined category of bonds and cash. For illustrative purposes +and a combined category of bonds and cash. For illustrative purposes, we will use several publicly available mutual funds from Vanguard. -the three funds we will track are the Vanguard 500 IDX FD Signal +The three funds we will track are the Vanguard 500 IDX FD Signal (VIFSX), the Vanguard Target Retirement 2030 (VTHRX), and the Vanguard Short Term Federal Fund (VSGBX). Each of these funds allocates assets to different categories of the investment universe and in different @@ -4002,7 +4272,7 @@ actual balances. For the three instruments listed above, those automatic transactions would look like: -@smallexample +@smallexample @c input:validate ; ; automatic calculations for asset allocation tracking ; @@ -4034,6 +4304,7 @@ the various asset classes how do we get a report that tells us our current allocation? Using the balance command and some tricky formatting! +@c TODO: does not @c command:validate due to multiple lines @smallexample ledger bal Allocation --current --format "\ %-17((depth_spacer)+(partial_account))\ @@ -4063,7 +4334,7 @@ tree, using a special formatter. The magic is in the formatter. The second line simply tells Ledger to print the partial account name indented by its depth in the tree. The third line is where we calculate and display the percentages. The -@code{display_total} command give the values of the total calculated +@code{display_total} command gives the values of the total calculated for the account in this line. The @code{parent.total} command gives the total for the next level up in the tree. @code{percent} formats their ratio as a percentage. The fourth line tells ledger to display @@ -4080,7 +4351,7 @@ nothing. @findex --limit @var{EXPR} @findex --display @var{EXPR} -If you have ``Gnuplot'' program installed, you can graph any of the +If you have the ``Gnuplot'' program installed, you can graph any of the above register reports. The script to do this is included in the ledger distribution, and is named @file{contrib/report}. Install @file{report} anywhere along your @env{PATH}, and then use @file{report} instead of @@ -4119,11 +4390,11 @@ report -J -l "Ua>=@{\$0.01@}" -d "d>=[last feb]" reg ^assets ^liab The last report uses both a calculation predicate @option{--limit @var{EXPR} (-l)} and a display predicate @option{--display @var{EXPR} -(-d)}. The calculation predicates limits the report to postings whose -amount is greater than $1 (which can only happen if the posting amount +(-d)}. The calculation predicate limits the report to postings whose +amount is greater than or equal to $1 (which can only happen if the posting amount is in dollars). The display predicate limits the transactions -@emph{displayed} to just those since last February, even those -transactions from before then will be computed as part of the balance. +@emph{displayed} to just those since last February, even though those +transactions from before will be computed as part of the balance. @node Reporting Commands, Command-line Syntax, Building Reports, Top @chapter Reporting Commands @@ -4158,7 +4429,7 @@ separately. @subsection The @command{equity} command @findex equity -The @command{equity} command prints out accounts balances as if they +The @command{equity} command prints out account balances as if they were transactions. This makes it easy to establish the starting balances for an account, such as when @ref{Archiving Previous Years}. @@ -4172,7 +4443,7 @@ The @command{register} command displays all the postings occurring in a single account, line by line. The account regex must be specified as the only argument to this command. If any regexes occur after the required account name, the register will contain only those -postings that match. Very useful for hunting down a particular +postings that match, which makes it very useful for hunting down a particular posting. The output from @command{register} is very close to what a typical @@ -4184,7 +4455,7 @@ If you have ``Gnuplot'' installed, you may plot the amount or running total of any register by using the script @file{report}, which is included in the Ledger distribution. The only requirement is that you add either @option{--amount-data (-j)} or @option{--total-data (-J)} to -your register command, in order to plot either the amount or total +your @command{register} command, in order to plot either the amount or total column, respectively. @node The @command{print} command, , The @command{register} command, Primary Financial Reports @@ -4225,8 +4496,8 @@ file whose formatting has gotten out of hand. @subsubsection The @command{csv} command @findex csv -The @command{csv} command will output print out the desired ledger -transactions in a csv format suitable for import into other programs. +The @command{csv} command prints the desired ledger +transactions in a csv format suitable for importing into other programs. You can specify the transactions to print using all the normal limiting and searching functions. @@ -4238,12 +4509,12 @@ limiting and searching functions. @findex --input-date-format @var{DATE_FORMAT} The @command{convert} command parses a comma separated value (csv) file -and outputs Ledger transactions. Many banks offer csv file downloads. -Unfortunately, the file formats, aside the from commas, are all +and prints Ledger transactions. Many banks offer csv file downloads. +Unfortunately, the file formats, aside from the commas, are all different. The ledger @command{convert} command tries to help as much as it can. -Your banks csv files will have fields in different orders from other +Your bank's csv files will have fields in different orders from other banks, so there must be a way to tell Ledger what to expect. Insert a line at the beginning of the csv file that describes the fields to Ledger. @@ -4286,7 +4557,7 @@ $ ledger convert download.csv --input-date-format "%m/%d/%Y" Where the @option{--input-date-format @var{DATE_FORMAT}} option tells ledger how to interpret the dates. -Importing csv files is a lot of work, and but is very amenable to +Importing csv files is a lot of work, but is very amenable to scripting. If there are columns in the bank data you would like to keep in your @@ -4307,14 +4578,14 @@ is from the file above. @findex --account @var{STR} @findex --rich-data -The @command{convert} command accepts three options, the most important +The @command{convert} command accepts three options. The most important ones are @option{--invert} which inverts the amount field, and @option{--account @var{STR}} which you can use to specify the account to balance against and @option{--rich-data}. When using the rich-data -switch additional metadata is stored as tags. There is, for example, +switch, additional metadata is stored as tags. There is, for example, a UUID field. If an entry with the same UUID tag is already included in the normal ledger file (specified via @option{--file @var{FILE} (-f)} or -via environment variable @env{LEDGER_FILE}) this entry will not be +via the environment variable @env{LEDGER_FILE}) this entry will not be printed again. You can also use @command{convert} with @code{payee} and @code{account} @@ -4323,7 +4594,7 @@ directive to rewrite the @code{payee} field based on some rules. Then you can use the account and its @code{payee} directive to specify the account. I use it like this, for example: -@smallexample +@smallexample @c input:validate payee Aldi alias ^ALDI SUED SAGT DANKE account Aufwand:Einkauf:Lebensmittel @@ -4341,7 +4612,7 @@ used. @findex lisp @findex emacs -The @command{lisp} command outputs results in a form that can be read +The @command{lisp} command prints results in a form that can be read directly by Emacs Lisp. The format of the @code{sexp} is: @smallexample @@ -4372,7 +4643,7 @@ 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 of the Babel system: +a very naive but still useful application of the Babel system: @smallexample * A simple test of ledger in an org file @@ -4418,7 +4689,7 @@ 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 +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: @@ -4429,7 +4700,7 @@ I currently do this directly as follows: )) @end smallexample -Once Ledger support in Babel has been enabled, we can use proceed to +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: @@ -4467,7 +4738,7 @@ The first two are described in more detail in this short tutorial. @node Embedded Ledger example with single source block, Multiple Ledger source blocks with @code{noweb}, Org mode with Babel, Org mode with Babel @subsubsection Embedded Ledger example with single source block -The easiest, albeit possibly less useful, way in which to use Ledger +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: @@ -4706,10 +4977,10 @@ the running total of the assets in our ledger. @node Summary, , Generating a monthly register, Org mode with Babel @subsubsection Summary -This short tutorial shows how Ledger entries can be embedded in a org +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 with a ledger. +examples of more complex operations on a ledger. @node The @command{pricemap} command, The @command{xml} command, Org mode with Babel, Reports in other Formats @subsection The @command{pricemap} command @@ -4721,7 +4992,7 @@ 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 multiples investments valued in those currencies. +currencies and multiple investments valued in those currencies. @node The @command{xml} command, @command{prices} and @command{pricedb} commands, The @command{pricemap} command, Reports in other Formats @subsection The @command{xml} command @@ -4744,7 +5015,7 @@ The general format used for Ledger data is: @end smallexample The data stream is enclosed in a @code{ledger} tag, which contains a -series of one or more transactions. Each @code{xact} describes the +series of one or more transactions. Each @code{xact} describes one transaction and contains a series of one or more postings: @smallexample @@ -4789,7 +5060,7 @@ Within the @code{en:postings} tag is a series of one or more </posting> @end smallexample -This is a basic posting. It may also be begin with +This is a basic posting. It may also begin with @code{tr:virtual} and/or @code{tr:generated} tags, to indicate virtual and auto-generated postings. Then follows the @code{tr:account} tag, which contains the full name of the account the posting is @@ -4891,7 +5162,7 @@ report, to display the running average price, or @option{--deviation (-D)} to show each price's deviation from that average. There is also a @command{pricedb} command which outputs the same -information as @command{prices}, but does in a format that can be +information as @command{prices}, but does so in a format that can be parsed by Ledger. This is useful for generating and tidying up pricedb database files. @@ -4913,7 +5184,7 @@ pricedb database files. @subsection @command{accounts} @findex accounts -The @command{accounts} reports all of the accounts in the journal. +The @command{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 @option{--count} option will tell you how many entries use each account. @@ -4922,9 +5193,9 @@ accounts matching the regex. The output is sorted by name. Using the @subsection @command{payees} @findex payees -The @command{payees} reports all of the unique payees in the journal. +The @command{payees} command reports all of the unique payees in the journal. Using the @option{--count} option will tell you how many entries use -each payee. To filter the payees displayed you must use the prefix: +each payee. To filter the payees displayed you must use the prefix @@: @smallexample $ ledger payees @@Nic @@ -4947,7 +5218,7 @@ you how many entries use each commodity. @findex tags @findex --values -The @command{tags} reports all of the tags in the journal. The output +The @command{tags} command reports all of the tags in the journal. The output is sorted by name. Using the @option{--count} option will tell you how many entries use each tag. Using the @option{--values} option will report the values used by each tag. @@ -4964,7 +5235,7 @@ earlier postings. Here's how it works: Say you currently have this posting in your ledger file: -@smallexample +@smallexample @c input:03ACB97 2004/03/15 * Viva Italiano Expenses:Food $12.45 Expenses:Tips $2.55 @@ -4975,17 +5246,17 @@ Now it's @samp{2004/4/9}, and you've just eating at @samp{Viva Italiano} again. The exact amounts are different, but the overall form is the same. With the @command{xact} command you can type: -@smallexample +@smallexample @c command:03ACB97 $ ledger xact 2004/4/9 viva food 11 tips 2.50 @end smallexample This produces the following output: -@smallexample +@smallexample @c output:03ACB97 2004/04/09 Viva Italiano - Expenses:Food $11.00 - Expenses:Tips $2.50 - Liabilities:MasterCard $-13.50 + Expenses:Food $11.00 + Expenses:Tips $2.50 + Liabilities:MasterCard @end smallexample It works by finding a past posting matching the regular expression @@ -5037,7 +5308,7 @@ FIX THIS ENTRY @c FIXME thdox @section Basic Usage This chapter describes Ledger's features and options. You may wish to -survey this to get an overview before diving in to the @ref{Ledger +survey this to get an overview before diving into the @ref{Ledger Tutorial} and more detailed examples that follow. Ledger has a very simple command-line interface, named---enticingly @@ -5062,14 +5333,14 @@ instead, precede the regular expression with @samp{payee} or totals for rent, food and movies, but only those whose payee matches Freddie: -@smallexample +@smallexample @c command:validate $ ledger bal rent food movies payee freddie @end smallexample @noindent or -@smallexample +@smallexample @c command:validate $ ledger bal rent food movies @@freddie @end smallexample @@ -5108,14 +5379,14 @@ Show all transactions with running total. Show transactions in csv format, for exporting to other programs. @item print -Print transaction in a ledger readable format. +Print transactions in a format readable by ledger. @item xml Produce XML output of the register command. @item lisp @itemx emacs -Produce Emacs lisp output. +Produce s-expression output, suitable for Emacs. @item equity Print account balances as transactions. @@ -5124,7 +5395,7 @@ Print account balances as transactions. Print price history for matching commodities. @item pricedb -Print price history for matching commodities in ledger readable format. +Print price history for matching commodities in a format readable by ledger. @item xact Generate transactions based on previous postings. @@ -5142,7 +5413,7 @@ Print summary of all options. @item --version @itemx -v -Print version of ledger executable. +Print version information and exit. @item --file @var{FILE} @itemx -f @var{FILE} @@ -5154,7 +5425,7 @@ Redirect output to @file{FILE}. @item --init-file @var{FILE} @itemx -i @var{FILE} -Specify options file. +Specify an options file. @item --account @var{STR} @itemx -a @var{STR} @@ -5169,22 +5440,22 @@ Specify default account @var{STR} for QIF file postings. @item --current @itemx -c -Display transaction on or before the current date. +Display only transactions on or before the current date. @item --begin @var{DATE} @itemx -b @var{DATE} -Begin reports on or after @var{DATE}. +Limit the processing to transactions on or after @var{DATE}. @item --end @var{DATE} @itemx -e @var{DATE} -Limit end date of transactions for report. +Limit the processing to transactions before @var{DATE}. @item --period @var{PERIOD_EXPRESSION} @itemx -p @var{PERIOD_EXPRESSION} -Set report period to @var{PERIOD_EXPRESSION}. +Limit the processing to transactions in @var{PERIOD_EXPRESSION}. @item --period-sort @var{VEXPR} -Sort postings within each period. +Sort postings within each period according to @var{VEXPR}. @item --cleared @itemx -C @@ -5203,7 +5474,7 @@ Display only real postings. @item --actual @itemx -L -Display only actual postings, not automated. +Display only actual postings, not automated ones. @item --related @itemx -r @@ -5213,17 +5484,17 @@ Display related postings. Display how close your postings meet your budget. @item --add-budget -Show un-budgeted postings. +Show unbudgeted postings. @item --unbudgeted -Show only un-budgeted postings. +Show only unbudgeted postings. @item --forecast @var{VEXPR} Project balances into the future. @item --limit @var{EXPR} @itemx -l @var{EXPR} -Limit postings in calculations. +Limit which postings are used in calculations by @var{EXPR}. @item --amount @var{EXPR} @itemx -t @var{EXPR} @@ -5250,7 +5521,8 @@ Accounts, tags or commodities not previously declared will cause errors. @item --check-payees Enable strict and pedantic checking for payees as well as accounts, -commodities and tags. +commodities and tags. This only works in conjunction with +@option{--strict} or @option{--pedantic}. @item --immediate Instruct ledger to evaluate calculations immediately rather than lazily. @@ -5276,18 +5548,21 @@ Report subtotals by payee. @item --empty @itemx -E -Include empty accounts in report. +Include empty accounts in the report. @item --weekly @itemx -W Report posting totals by week. +@item --quarterly +Report posting totals by quarter. + @item --yearly @itemx -Y Report posting totals by year. @item --dow -Report Posting totals by day of week. +Report posting totals by day of week. @item --sort @var{VEXPR} @itemx -S @var{VEXPR} @@ -5308,11 +5583,11 @@ Direct output to @var{FILE} pager program. @item --average @itemx -A -Report average posting value. +Report the average posting value. @item --deviation @itemx -D -Report each posting deviation from the average. +Report each posting's deviation from the average. @item --percent @itemx -% @@ -5325,21 +5600,21 @@ Produce a pivot table of the @var{TAG} type specified. @item --amount-data @itemx -j -Show only date and value column to format the output for plots. +Show only the date and value columns to format the output for plots. @item --plot-amount-format @var{FORMAT_STRING} Specify the format for the plot output. @item --total-data @itemx -J -Show only dates and totals to format the output for plots. +Show only the date and total columns to format the output for plots. @item --plot-total-format @var{FORMAT_STRING} Specify the format for the plot output. @item --display @var{EXPR} @itemx -d @var{EXPR} -Display only posting that meet the criterias in the @var{EXPR}. +Display only postings that meet the criteria in the @var{EXPR}. @item --date-format @var{DATE_FORMAT} @itemx -y @var{DATE_FORMAT} @@ -5350,11 +5625,7 @@ Change the basic date format used in reports. @itemx --register-format @var{FORMAT_STRING} @itemx --prices-format @var{FORMAT_STRING} @itemx -F @var{FORMAT_STRING} -Set reporting format. - -@item --wide -@itemx -w -Wide. +Set the reporting format for various reports. @item --anon Print the ledger register with anonymized accounts and payees, useful @@ -5395,7 +5666,7 @@ Group by day of weeks. @item --subtotal @itemx -s -Group posting together, similar to balance report. +Group postings together, similar to the balance report. @end ftable @@ -5413,10 +5684,10 @@ Set expected freshness of prices in @var{INT} minutes. @item --download @itemx -Q -Download quotes using named @file{getquote}. +Download quotes using the script named @file{getquote}. @item --getquote @var{FILE} -Sets path to a user defined script to download commodity prices. +Sets the path to a user-defined script to download commodity prices. @item --quantity @itemx -O @@ -5432,7 +5703,7 @@ Report last known market value. @item --gain @itemx -G -Report net gain loss for commodities that have a price history. +Report net gain or loss for commodities that have a price history. @end ftable @@ -5453,7 +5724,7 @@ Report net gain loss for commodities that have a price history. @node Global Options, Session Options, Detailed Option Description, Detailed Option Description @subsection Global Options -Options for Ledger report affect three separate scopes of operation: +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 @@ -5464,8 +5735,8 @@ sessions with multiple reports per session. @item --args-only Ignore all environment and init-file settings and -use only command-line arguments to control Ledger. Useful for debugs -or testing small Journal files not associated with you main financial +use only command-line arguments to control Ledger. Useful for debugging +or testing small journal files not associated with your main financial database. @item --debug @var{CODE} @@ -5473,7 +5744,7 @@ FIX THIS ENTRY @c FIXME thdox @item --help @itemx -h -Display the info page for ledger. +Display the man page for ledger. @item --init-file @var{FILE} Specify the location of the init file. The default is @file{~/.ledgerrc}. @@ -5513,7 +5784,7 @@ $ ledger --options bal --cleared -f ~/ledger/test/input/drewr3.dat @noindent For the source column, a value starting with a @samp{-} or @samp{--} -indicated the source was a command line argument. It the entry starts +indicated the source was a command line argument. If the entry starts with a @samp{$}, the source was an environment variable. If the source is @code{?normalize} the value was set internally by ledger, in a function called @code{normalize_options}. @@ -5542,7 +5813,7 @@ FIX THIS ENTRY @c FIXME thdox @node Session Options, Report Options, Global Options, Detailed Option Description @subsection Session Options -Options for Ledger report affect three separate scopes of operation: +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 @@ -5562,11 +5833,11 @@ FIX THIS ENTRY @c FIXME thdox @item --decimal-comma Direct Ledger to parse journals using the European standard comma as -decimal separator, vice a period. +a decimal separator, not the usual period. @item --download @itemx -Q -Direct Ledger to download prices using the script defined in +Direct Ledger to download prices using the script defined via the option @option{--getquote @var{FILE}}. @item --explicit @@ -5596,22 +5867,23 @@ Format Codes}). @item --master-account @var{STR} Prepend all account names with the argument. -@smallexample -$ ledger -f test/input/drewr3.dat bal --master-account HUMBUG +@smallexample @c command:A76BB56 +$ ledger -f drewr3.dat bal --no-total --master-account HUMBUG +@end smallexample + +@smallexample @c output:A76BB56 0 HUMBUG $ -3,804.00 Assets $ 1,396.00 Checking $ 30.00 Business $ -5,200.00 Savings - $ 20.00 Books $ -1,000.00 Equity:Opening Balances - $ 6,634.00 Expenses - $ 11,000.00 Auto + $ 6,654.00 Expenses + $ 5,500.00 Auto $ 20.00 Books $ 300.00 Escrow $ 334.00 Food:Groceries $ 500.00 Interest:Mortgage - $ -5,520.00 Assets:Checking $ -2,030.00 Income $ -2,000.00 Salary $ -30.00 Sales @@ -5620,8 +5892,11 @@ $ ledger -f test/input/drewr3.dat bal --master-account HUMBUG $ 200.00 Mortgage:Principal @end smallexample +@item --no-aliases +Ledger does not expand any aliases if this option is specified. + @item --pedantic -FIX THIS ENTRY @c FIXME thdox +Accounts, tags or commodities not previously declared will cause errors. @item --permissive FIX THIS ENTRY @c FIXME thdox @@ -5640,13 +5915,18 @@ considered to be fresh enough. @item --strict Ledger normally silently accepts any account or commodity in a posting, -even if you have misspelled a common used one. The option -@option{--strict} changes that behavior. While running +even if you have misspelled a commonly used one. The option +@option{--strict} changes that behavior. While running with @option{--strict}, Ledger interprets all cleared transactions as -correct, and if it finds a new account or commodity (same 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. +@item --recursive-aliases +Normally, ledger only expands aliases once. With this option, ledger tries +to expand the result of alias expansion recursively, until no more expansions +apply. + @item --time-colon The @option{--time-colon} option will display the value for a seconds based commodity as real hours and minutes. @@ -5662,7 +5942,7 @@ FIX THIS ENTRY @c FIXME thdox @node Report Options, Basic options, Session Options, Detailed Option Description @subsection Report Options -Options for Ledger report affect three separate scopes of operation: +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 @@ -5681,7 +5961,7 @@ desired width. @item --account @var{STR} Prepend @var{STR} to all accounts reported. That is, the option -@samp{--account Personal} would track @samp{Personal:} to the beginning +@samp{--account Personal} would tack @samp{Personal:} to the beginning of every account reported in a balance report or register report. @item --account-width @var{INT} @@ -5690,11 +5970,11 @@ to @var{INT} characters. @item --actual @itemx -L -Report only real transactions, with no automated or virtual -transactions used. +Report only real transactions, ignoring all automated or virtual +transactions. @item --add-budget -Show only un-budgeted postings. +Show only unbudgeted postings. @item --amount @var{EXPR} @itemx -t @var{EXPR} @@ -5704,7 +5984,7 @@ arbitrary transformation to the postings. @item --amount-data @itemx -j -On a register report print only the dates and amount of postings. +On a register report print only the date and amount of postings. Useful for graphing and spreadsheet applications. @item --amount-width @var{INT} @@ -5754,17 +6034,17 @@ that date will be ignored. Print the entire line in bold if the given value expression is true (@pxref{Value Expressions}). -@smallexample -$ ledger reg Expenses --begin Dec --bold-if "amount > 100" +@smallexample @c command:validate +$ ledger reg Expenses --begin Dec --bold-if "amount>100" @end smallexample @noindent -list all transactions since the beginning of December and bold any -posting greater than $100. +list all transactions since the beginning of December and print in +bold any posting greater than $100. @item --budget Only display budgeted items. In a register report this -displays transaction in the budget, in a balance report this displays +displays transactions in the budget, in a balance report this displays accounts in the budget (@pxref{Budgeting and Forecasting}). @item --budget-format @var{FORMAT_STRING} @@ -5785,7 +6065,7 @@ Group the register report by payee. @item --cleared @itemx -C -Consider only transaction that have been cleared for display and +Consider only transactions that have been cleared for display and calculation. @item --cleared-format @var{FORMAT_STRING} @@ -5807,22 +6087,22 @@ Strings}). The default is: @item --collapse @itemx -n -By default ledger prints all account in an account tree. With -@option{--collapse} it print only the top level account specified. +By default ledger prints all accounts in an account tree. With +@option{--collapse} it prints only the top level account specified. @item --collapse-if-zero Collapse the account display only if it has a zero balance. @item --color @itemx --ansi -Use color is the tty supports it. +Use color if the terminal supports it. @item --columns @var{INT} Specify the width of the @command{register} report in characters. @item --count Direct ledger to report the number of items when appended to the -commodities, accounts or payees command. +@command{commodities}, @command{accounts} or @command{payees} command. @item --csv-format @var{FORMAT_STRING} Specify the format to use for the @command{csv} report (@pxref{Format @@ -5833,7 +6113,7 @@ Strings}). The default is: "%(quoted(code))," "%(quoted(payee))," "%(quoted(display_account))," -"%(quoted(commodity))," +"%(quoted(commodity(scrub(display_amount))))," "%(quoted(quantity(scrub(display_amount))))," "%(quoted(cleared ? \"*\" : (pending ? \"!\" : \"\")))," "%(quoted(join(note | xact.note)))\n" @@ -5851,8 +6131,8 @@ Transform the date of the transaction using @var{EXPR}. @item --date-format @var{DATE_FORMAT} @itemx -y @var{DATE_FORMAT} -Specify format ledger should use to print dates (@pxref{Date and Time -Format Codes}). +Specify the format ledger should use to read and print dates +(@pxref{Date and Time Format Codes}). @item --date-width @var{INT} Specify the width, in characters, of the date column in the @@ -5863,8 +6143,9 @@ FIX THIS ENTRY @c ASK JOHN @item --dc Display register or balance in debit/credit format If you use -@option{--dc} with either the register (reg) or balance (bal) commands, -you will now get extra columns. The register goes from this: +@option{--dc} with either the @command{register} (reg) or +@command{balance} (bal) commands, you will now get extra columns. +The register goes from this: @smallexample 12-Mar-10 Employer Assets:Cash $100 $100 @@ -5921,9 +6202,9 @@ And with @option{--dc} it becomes this: @item --depth @var{INT} Limit the depth of the account tree. In a balance report, for example, -a @samp{--depth 2} statement will print balances only for account with +a @samp{--depth 2} statement will print balances only for accounts with two levels, i.e. @samp{Expenses:Entertainment} but not -@samp{Expenses:entertainemnt:Dining}. This is a display predicate, which +@samp{Expenses:Entertainment:Dining}. This is a display predicate, which means it only affects display, not the total calculations. @item --deviation @@ -5931,21 +6212,21 @@ Report each posting’s deviation from the average. It is only meaningful in the register and prices reports. @item --display @var{EXPR} -Display lines that satisfy the expression given. +Display only lines that satisfy the expression @var{EXPR}. @item --display-amount @var{EXPR} -Apply a transform to the @emph{displayed} amount. This occurs after +Apply a transformation to the @emph{displayed} amount. This happens after calculations occur. @item --display-total @var{EXPR} -Apply a transform to the @emph{displayed} total. This occurs after +Apply a transformation to the @emph{displayed} total. This happens after calculations occur. @item --dow @itemx --days-of-week -Group transactions by the days of the week. +Group transactions by the day of the week. -@smallexample +@smallexample @c command:validate $ ledger reg Expenses --dow --collapse @end smallexample @@ -5954,11 +6235,11 @@ Will print all Expenses totaled for each day of the week. @item --empty @itemx -E -Include empty accounts in the report. +Include empty accounts in the report and in average calculations. @item --end @var{DATE} -Specify the end @var{DATE} for transaction to be considered in the -report. +Specify the end @var{DATE} for a transaction to be considered in the +report. All transactions on or after this date are ignored. @item --equity Related to the @command{equity} command (@pxref{The @command{equity} @@ -5978,8 +6259,8 @@ Force the full names of accounts to be used in the balance report. The balance report will not use an indented tree. @item --force-color -Output tty color codes even if the tty doesn't support them. Useful -for TTY that don't advertise their capabilities correctly. +Output TTY color codes even if the TTY doesn't support them. Useful +for TTYs that don't advertise their capabilities correctly. @item --force-pager Force Ledger to paginate its output. @@ -5989,7 +6270,7 @@ Force Ledger to paginate its output. Continue forecasting while @var{VEXPR} is true. @item --forecast-years @var{INT} -Forecast at most @var{INT} years in the future. +Forecast at most @var{INT} years into the future. @item --format @var{FORMAT_STRING} @itemx -F @var{FORMAT_STRING} @@ -6006,13 +6287,13 @@ transactions) in the report, in cases where you normally wouldn't want them. @item --group-by @var{EXPR} -Group transaction together in the @command{register} report. +Group transactions together in the @command{register} report. @var{EXPR} can be anything, although most common would be @code{payee} or @code{commodity}. The @code{tags()} function is also useful here. @item --group-title-format @var{FORMAT_STRING} -Set the format for the headers that separate reports section of -a grouped report. Only has effect with a @option{--group-by @var{EXPR}} +Set the format for the headers that separates the report sections of +a grouped report. Only has an effect with a @option{--group-by @var{EXPR}} register report. @smallexample @@ -6041,11 +6322,11 @@ FIX THIS ENTRY @c FIXME thdox FIX THIS ENTRY @c FIXME thdox @item --inject -Use @code{Expected} amounts in calculations. In the case that you know -that amount a transaction should be, but the actual transaction has the -wrong value you can use metadata to put in the expected amount: +Use @code{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: -@smallexample +@smallexample @c input:validate 2012-03-12 Paycheck Income $-990; Expected:: $-1000.00 Checking @@ -6059,8 +6340,8 @@ Change the sign of all reported values. @item --limit @var{EXPR} @itemx -l @var{EXPR} -Only transactions that satisfy the expression will be considered in the -calculation. +Only transactions that satisfy @var{EXPR} are considered in +calculations and for display. @item --lot-dates Report the date on which each commodity in a balance report was @@ -6097,12 +6378,15 @@ Specify the width of the Meta column used for the @option{--meta @itemx -M Synonym for @samp{--period "monthly"}. +@item --no-aliases +Aliases are completely ignored. + @item --no-color Suppress any color TTY output. @item --no-rounding Don't output @samp{<Rounding>} postings. Note that this will cause the -running total to often not add up! It's main use is for +running total to often not add up! Its main use is for @option{--amount-data (-j)} and @option{--total-data (-J)} reports. @item --no-titles @@ -6112,7 +6396,7 @@ Suppress the output of group titles. Suppress printing the final total line in a balance report. @item --now @var{DATE} -Define the current date in case to you to do calculate in the past or +Define the current date in case you want to calculate in the past or future using @option{--current}. @item --only @var{FIXME} @@ -6132,22 +6416,22 @@ a date and payee for each transaction. @item --payee-width @var{INT} Set the number of columns dedicated to the payee in the register -report. +report to @var{INT}. @item --pending Use only postings that are marked pending. @item --percent @itemx -% -Calculate the percentage value of each account in a balance reports. -Only works for account that have a single commodity. +Calculate the percentage value of each account in balance reports. +Only works for accounts that have a single commodity. @item --period @var{PERIOD_EXPRESSION} Define a period expression that sets the time period during which transactions are to be accounted. For a @command{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. +For a @command{balance} report only those transactions will be accounted +in the final balances. @item --pivot @var{TAG} Produce a balance pivot report @emph{around} the given @var{TAG}. For @@ -6200,15 +6484,15 @@ Show primary dates for all calculations (@pxref{Effective Dates}). @item --quantity @itemx -O -FIX THIS ENTRY +Report commodity totals (this is the default). @item --quarterly Synonym for @samp{--period "quarterly"}. @item --raw -In the print report, show transactions using the exact same syntax as +In the @command{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. Can be useful for minor cleanups, like just aligning +interpreting. This can be useful for minor cleanups, like just aligning amounts. @item --real @@ -6217,10 +6501,10 @@ Account using only real transactions ignoring virtual and automatic transactions. @item --register-format @var{FORMAT_STRING} -FIX THIS ENTRY @c FIXME thdox +Define the output format for the @command{register} report. @item --related -In a register report show the related account. This is the other +In a @command{register} report show the related account. This is the other @emph{side} of the transaction. @item --related-all @@ -6241,19 +6525,19 @@ FIX THIS ENTRY FIX THIS ENTRY @c FIXME thdox @item --seed @var{FIXME} -Set the random seed for the @code{generate} command. Used as part of +Set the random seed to @var{FIXME} for the @code{generate} command. Used as part of development testing. @item --sort @var{VEXPR} @itemx -S @var{VEXPR} -Sort the register report based on the value expression given to sort. +Sort the @command{register} report based on the value expression given to sort. @item --sort-all @var{FIXME} FIX THIS ENTRY @item --sort-xacts @var{VEXPR} @itemx --period-sort @var{VEXPR} -Sort the posting within transactions using the given value expression. +Sort the postings within transactions using the given value expression. @item --start-of-week @var{INT} Tell ledger to use a particular day of the week to start its ``weekly'' @@ -6266,7 +6550,7 @@ FIX THIS ENTRY @item --tail @var{INT} @itemx --last @var{INT} -Report only the last @var{INT} entries. Only useful on a register +Report only the last @var{INT} entries. Only useful in a @command{register} report. @item --time-report @@ -6278,7 +6562,7 @@ Define a value expression used to calculate the total in reports. @item --total-data @itemx -J -FIX THIS ENTRY +Show only dates and totals to format the output for plots. @item --total-width @var{INT} Set the width of the total field in the register report. @@ -6291,7 +6575,7 @@ as it considers sub-names within the account name (that style is called ``abbreviate''). @item --unbudgeted -FIX THIS ENTRY +Show only unbudgeted postings. @item --uncleared @itemx -U @@ -6303,12 +6587,12 @@ FIX THIS ENTRY @item --unrealized-gains @var{STR} Allow the user to specify what account name should be used for unrealized gains. Defaults to @samp{"Equity:Unrealized Gains"}. -Often set in one's @file{~/.ledgerrc} file to change default. +Often set in one's @file{~/.ledgerrc} file to change the default. @item --unrealized-losses @var{STR} Allow the user to specify what account name should be used for unrealized gains. Defaults to @samp{"Equity:Unrealized Losses"}. -Often set in one's @file{~/.ledgerrc} file to change default. +Often set in one's @file{~/.ledgerrc} file to change the default. @item --unround Perform all calculations without rounding and display results to full @@ -6322,8 +6606,8 @@ FIX THIS ENTRY @c FIXME thdox Synonym for @samp{--period "weekly"}. @item --wide -Let the register report use 132 columns. Identical to @samp{--columns -"132"}. +Let the register report use 132 columns instead of 80 (the default). +Identical to @samp{--columns "132"}. @item --yearly @itemx -Y @@ -6343,19 +6627,17 @@ variables}), instead of using actual command-line options: @item --help @itemx -h Print a summary of all the options, and what they are used for. This -can be a handy way to remember which options do what. This help screen -is also printed if ledger is run without a command. +can be a handy way to remember which options do what. @item --version -@itemx -v 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. @item --file @var{FILE} @itemx -f @var{FILE} -Read @file{FILE} as a ledger file. @var{FILE} can be @samp{-} that is -a synonym of @samp{/dev/stdin}. This command may be used multiple +Read @file{FILE} as a ledger file. @var{FILE} can be @samp{-} which is +a synonym for @samp{/dev/stdin}. This command may be used multiple times. Typically, the environment variable @env{LEDGER_FILE} is set, rather than using this command-line option. @@ -6369,12 +6651,12 @@ goes to standard output. Causes @file{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 -the command-line, but put each option on its own line. Here is an +on the command-line, but put each option on its own line. Here is an example init file: @smallexample --price-db ~/finance/.pricedb - +--wide ; ~/.ledgerrc ends here @end smallexample @@ -6411,7 +6693,7 @@ first matching transaction. (Note: This is different from using @item --end @var{DATE} @itemx -e @var{DATE} Constrain the report so that transactions on or after @var{DATE} are -not considered. The ending date is inclusive. +not considered. @item --period @var{PERIOD_EXPRESSION} @itemx -p @var{PERIOD_EXPRESSION} @@ -6419,7 +6701,7 @@ Set the reporting period to @var{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 @samp{last June} or @samp{next month}. For more using period +terms like @samp{last June} or @samp{next month}. For more details on period expressions, see @ref{Period Expressions}. @item --period-sort @var{VEXPR} @@ -6428,8 +6710,9 @@ expression @var{EXPR}. This is most often useful when reporting monthly expenses, in order to view the highest expense categories at the top of each month: -@smallexample -$ ledger -M --period-sort -At reg ^Expenses +@c TODO: the parameter to --period-sort was -At, which doesn't seem to work any longer +@smallexample @c command:validate +$ ledger -M --period-sort total reg ^Expenses @end smallexample @item --cleared @@ -6450,8 +6733,8 @@ see @ref{Virtual postings} for more information). @item --actual @itemx -L -Display only actual postings, and not those created due to automated -postings. +Display only actual postings, and not those created by automated +transactions. @item --related @itemx -r @@ -6462,7 +6745,7 @@ In the balance report, it shows all the accounts affected by transactions having a related posting. For example, if a file had this transaction: -@smallexample +@smallexample @c input:94C5675 2004/03/20 Safeway Expenses:Food $65.00 Expenses:Cash $20.00 @@ -6471,21 +6754,21 @@ this transaction: And the register command was: -@smallexample -$ ledger -r register food +@smallexample @c command:94C5675 +$ ledger -f example.dat -r register food @end smallexample -The following would be output, showing the postings related to the +The following would be printed, showing the postings related to the posting that matched: -@smallexample -2004/03/20 Safeway Expenses:Cash $-20.00 $-20.00 - Assets:Checking $85.00 $65.00 +@smallexample @c output:94C5675 +04-Mar-20 Safeway Expenses:Cash $20.00 $20.00 + Assets:Checking $-85.00 $-65.00 @end smallexample @item --budget Useful for displaying how close your postings meet your budget. -@option{--add-budget} also shows un-budgeted postings, while +@option{--add-budget} also shows unbudgeted postings, while @option{--unbudgeted} shows only those. @option{--forecast @var{VEXPR}} is a related option that projects your budget into the future, showing how it will affect future balances. @xref{Budgeting and Forecasting}. @@ -6590,22 +6873,22 @@ Report posting totals by month. @item --yearly @itemx -Y -Report posting totals by year. For more complex period, using the +Report posting totals by year. For more complex periods, use @option{--period}. @c TODO end this sentence @item --period @var{PERIOD_EXPRESSION} Option described above. @item --dow -Report postings totals for each day of the week. This is an easy way +Report posting totals for each day of the week. This is an easy way to see if weekend spending is more than on weekdays. @item --sort @var{VEXPR} @itemx -S @var{VEXPR} Sort a report by comparing the values determined using the value -expression @var{VEXPR}. For example, using @samp{-S -UT} 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, +expression @var{VEXPR}. For example, using @samp{-S "-abs(total)"} in the +@command{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 @ref{Value Expressions}. @item --pivot @var{TAG} @@ -6650,7 +6933,7 @@ the parent account. @item --amount-data @itemx -j -Change the @command{register} report so that it outputs nothing but the +Change the @command{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, @@ -6658,17 +6941,18 @@ etc. @item --total-data @itemx -J -Change the @command{register} report so that it outputs nothing but the -date and totals column, without commodities. +Change the @command{register} report so that it prints nothing but the +date and total columns, without commodities. @item --display @var{EXPR} @itemx -d @var{EXPR} -Limit which postings or accounts or actually displayed in a report. +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: +@c TODO: does not @c command:validate due to space in "last month" @smallexample $ ledger -d "d>=[last month]" reg checking @end smallexample @@ -6677,6 +6961,7 @@ The output from this command is very different from the following, whose running total includes only postings from the last month onward: +@c TODO: does not @c command:validate due to space in "last month" @smallexample $ ledger -p "last month" reg checking @end smallexample @@ -6780,7 +7065,7 @@ Set the format for @command{csv} reports. The default is: %(quoted(code)), %(quoted(payee)), %(quoted(display_account)), - %(quoted(commodity)), + %(quoted(commodity(scrub(display_amount)))), %(quoted(quantity(scrub(display_amount)))), %(quoted(cleared ? \"*\" : (pending ? \"!\" : \"\"))), %(quoted(join(note | xact.note)))\n" @@ -6871,7 +7156,7 @@ 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 @option{--amount @var{EXPR} (-t)} and @option{--total @var{VEXPR} (-T)} options. However, there are also -several ``default'' reports, which will satisfy most users basic +several ``default'' reports, which will satisfy most users' basic reporting needs: @ftable @code @@ -6918,7 +7203,7 @@ If no @var{VALUE} property is specified, each posting is assumed to have a default, as if you'd specified a global, automated transaction as follows: -@smallexample +@smallexample @c input:validate = expr true ; VALUE:: market(amount, date, exchange) @end smallexample @@ -6932,7 +7217,7 @@ This definition emulates the present day behavior of @option{--market 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: -@smallexample +@smallexample @c input:validate = expr commodity == "DM" ; VALUE:: date < [Jun 2008] ? market(amount, date, exchange) : 1.44 EUR @end smallexample @@ -6944,7 +7229,7 @@ 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: -@smallexample +@smallexample @c input:validate = /^Expenses:/ ; VALUE:: market(amount, post.date, exchange) @end smallexample @@ -6956,7 +7241,7 @@ the value of @option{--now @var{DATE}} (defaults to today). Or how about valuating miles based on a reimbursement rate during a specific time period: -@smallexample +@smallexample @c input:validate = expr commodity == "miles" and date >= [2007] and date < [2008] ; VALUE:: market($1.05, date, exchange) @end smallexample @@ -6970,7 +7255,7 @@ Note that you can have a valuation expression specific to a particular posting or transaction, by overriding these general defaults using specific meta-data: -@smallexample +@smallexample @c input:validate 2010-12-26 Example Expenses:Food $20 ; Just to be silly, always valuate *these* $20 as 30 DM, no matter what @@ -6979,7 +7264,7 @@ specific meta-data: Assets:Cash @end smallexample -This example demonstrates that your VALUE expression should be as +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 @@ -6990,7 +7275,9 @@ which allows you to report most everything in EUR if you use @samp{-X EUR}, except for certain accounts or postings which should always be valuated in another currency. For example: -@smallexample +@c TODO is this example missing the actual line to get the effect? +@c it looks like it only contains a match, but no effect +@smallexample @c input:validate = /^Assets:Brokerage:CAD$/ ; Always report the value of commodities in this account in ; terms of present day dollars, despite what was asked for @@ -7026,13 +7313,13 @@ these values: @itemize @item Register Report -For the register report, use the value of that commodity on the date of +For the @command{register} report, use the value of that commodity on the date of the posting being reported, with a @samp{<Revalued>} posting added at -the end of today's value is different from the value of the last +the end if today's value is different from the value of the last posting. @item Balance Report -For the balance report, use the value of that commodity as of today. +For the @command{balance} report, use the value of that commodity as of today. @end itemize @@ -7171,11 +7458,11 @@ your expectations. To start keeping a budget, put some periodic transactions (@pxref{Periodic Transactions}) at the top of your ledger file. A -period transaction is almost identical to a regular transaction, except +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: -@smallexample +@smallexample @c input:validate ~ Monthly Expenses:Rent $500.00 Expenses:Food $450.00 @@ -7192,9 +7479,9 @@ payee. For example: Assets @end smallexample -These two period transactions give the usual monthly expenses, as well +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 expense is for any category, use a command like: +average monthly expenses are for any category, use a command like: @smallexample $ ledger -p "this year" --monthly --average balance ^expenses @@ -7202,26 +7489,26 @@ $ ledger -p "this year" --monthly --average balance ^expenses The reported totals are the current year's average for each account. -Once these period transactions are defined, creating a budget report is +Once these periodic transactions are defined, creating a budget report is as easy as adding @option{--budget} to the command-line. For example, a typical monthly expense report would be: -@smallexample +@smallexample @c command:validate $ ledger --monthly register ^expenses @end smallexample To see the same report balanced against your budget, use: -@smallexample +@smallexample @c command:validate $ ledger --budget --monthly register ^expenses @end smallexample A budget report includes only those accounts that appear in the budget. To see all expenses balanced against the budget, use -@option{--add-budget}. You can even see only the un-budgeted expenses +@option{--add-budget}. You can even see only the unbudgeted expenses using @option{--unbudgeted}: -@smallexample +@smallexample @c command:validate $ ledger --unbudgeted --monthly register ^expenses @end smallexample @@ -7233,21 +7520,21 @@ You can also use these flags with the @command{balance} command. 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 period transactions as are used +makes this easy to do, using the same periodic transactions as are used for budgeting. An example forecast report can be generated with: -@smallexample +@smallexample @c command:validate $ ledger --forecast "T>@{\$-500.00@}" register ^assets ^liabilities @end smallexample This report continues outputting postings until the running total -is greater than $-500.00. A final posting is always output, to -show you what the total afterwards would be. +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: +Forecasting can also be used with the @command{balance} report, +but by date only, and not against the running total: -@smallexample +@smallexample @c command:validate $ ledger --forecast "d<[2010]" bal ^assets ^liabilities @end smallexample @@ -7257,7 +7544,7 @@ $ ledger --forecast "d<[2010]" bal ^assets ^liabilities Ledger directly supports ``timelog'' entries, which have this form: -@smallexample +@smallexample @c input:validate i 2013/03/28 22:13:00 ACCOUNT[ PAYEE] o 2013/03/29 03:39:00 @end smallexample @@ -7265,21 +7552,21 @@ 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 @option{--day-break} to break them up in the -report). The number of seconds between is accumulated as time to that -ACCOUNT. If the checkout uses a capital @samp{O}, the transaction is -marked ``cleared''. You can use an optional PAYEE for whatever meaning -you like. +report). The number of seconds between check-in and check-out is accumulated +as time to that ACCOUNT. If the checkout uses a capital @samp{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 @file{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. +the @samp{org2tc} script developed by John Wiegley. These timelog entries can appear in a separate file, or directly in -your main ledger file. The initial @samp{i} and @samp{o} count as -Ledger ``directives'', and are accepted anywhere that ordinary -transactions are. +your main ledger file. The initial @samp{i} and @samp{o} characters +count as Ledger ``directives'', and are accepted anywhere that +ordinary transactions are valid. @node Value Expressions, Format Strings, Time Keeping, Top @chapter Value Expressions @@ -7314,7 +7601,7 @@ addition to a set of functions and variables. @c a display predicate that I use with the @command{balance} command: @c @smallexample -@c ledger -d /^Liabilities/?T<0:UT>100 balance +@c ledger -d '/^Liabilities/?T<0:UT>100' balance @c @end smallexample @c The effect is that account totals are displayed only if: 1) A @@ -7332,7 +7619,7 @@ while still calculating the running balance based on all transactions: $ ledger -d "d>[this month]" register checking @end smallexample -This advantage to this command's complexity is that it prints the +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: @@ -7354,9 +7641,9 @@ $ ledger -b "this month" register checking @findex --total @var{VEXPR} 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 +For the @command{register} and @command{print} commands, these variables +relate to individual postings, and sometimes the account affected by a +posting. For the @command{balance} command, these variables relate to accounts, often with a subtle difference in meaning. The use of each variable for both is specified. @@ -7364,8 +7651,8 @@ variable for both is specified. @item t This maps to whatever the user specified with @option{--amount -@var{EXPR} (-t)}. In a register report, @option{--amount @var{EXPR} -(-t)} changes the value column; in a balance report, it has no meaning +@var{EXPR} (-t)}. In a @command{register} report, @option{--amount @var{EXPR} +(-t)} changes the value column; in a @command{balance} report, it has no meaning by default. If @option{--amount @var{EXPR} (-t)} was not specified, the current report style's value expression is used. @@ -7404,15 +7691,15 @@ The cost of a posting; the cost of an account, without its children. @item v -The market value of a posting, or an account without its children. +The market value of a posting or an account, without its children. @item g The net gain (market value minus cost basis), for a posting or an -account without its children. It is the same as @samp{v-b}. +account, without its children. It is the same as @samp{v-b}. @item l The depth (``level'') of an account. If an account has one parent, -it's depth is one. +its depth is one. @item n The index of a posting, or the count of postings affecting an @@ -7563,10 +7850,10 @@ posting. @item c/REGEX/ A regular expression that matches against the transaction code (the -text that occurs between parentheses before the payee name). +text that occurs between parentheses before the payee). @item e/REGEX/ -A regular expression that matches against a posting's note, or +A regular expression that matches against a posting's note or comment field. @item (EXPR) @@ -7575,7 +7862,7 @@ more complicated arguments to functions, or for overriding the natural precedence order of operators. @item [DATE] -Useful specifying a date in plain terms. For example, you could say +Useful for specifying a date in plain terms. For example, you could say @samp{[2004/06/01]}. @end table @@ -7758,8 +8045,8 @@ format string, exactly like those supported by @code{strftime}. For example: @samp{%[%Y/%m/%d %H:%M:%S]}. @item S -Insert the pathname of the file from which the transaction's data was -read. Only sensible in a register report. +Insert the path name of the file from which the transaction's data was +read. Only sensible in a @command{register} report. @item B Inserts the beginning character position of that transaction within the @@ -7792,8 +8079,8 @@ This is the same as @samp{%X}, except that it only displays a state character if all of the member postings have the same state. @item C -Inserts the transaction type. This is the value specified between -parenthesis on the first line of the transaction. +Inserts the transaction code. This is the value specified between +parentheses on the first line of the transaction. @item P Inserts the payee related to a posting. @@ -7879,7 +8166,7 @@ options: @node Colors, Quantities and Calculations, Field Widths, Formatting Functions and Codes @subsection Colors -The character based formatting ledger can do is limited to the ANSI +The character-based formatting ledger can do is limited to the ANSI terminal character colors and font highlights in a normal TTY session. @multitable @columnfractions .3 .3 .3 @@ -8020,10 +8307,10 @@ weekday, abbreviated Wed. weekday, full Wednesday. @item %d -day of the month (dd), zero padded 10. +day of the month (dd), zero padded up to 10. @item %e -day of the month (dd) 10. +day of the month (dd) , no leading zero up to 10. @item %j day of year, zero padded 000–366. @@ -8065,7 +8352,7 @@ Locale’s abbreviated month, for example @samp{02} might be abbreviated as @samp{Feb}. @item %B -Locale’s full month, variable length February. +Locale’s full month, variable length, e.g. February. @end table @@ -8118,7 +8405,7 @@ subsequent lines the width is given by @code{latterwidth}. If If @code{right_justify=true} then the field is right justify within the width of the field. If it is @code{false}, then the field is left justified and padded to the full width of the field. If -@code{colorize} is true then ledger will honor color settings. +@code{colorize} is true, then ledger will honor color settings. @item join(STR) Replaces line feeds in @code{STR} with @samp{\n}. @@ -8142,7 +8429,7 @@ generated the posting. @table @code @item filename -name of ledger data file from whence posting came, abbreviated @samp{S}. +the name of ledger the data file from whence the posting came, abbreviated @samp{S}. @item beg_pos character position in @code{filename} where entry for posting begins, @@ -8183,16 +8470,16 @@ make sense later. 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 Commodity's that Amount's refer to. +like the Commodities that Amounts refer to. The make a Session useful, you must read a Journal into it, using the function `@code{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 Transaction's, Posting's, and other -objects related to your data. There are also AutomatedTransaction's -and PeriodicTransaction's, etc. +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: @@ -8211,7 +8498,7 @@ 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: -@smallexample +@smallexample @c input:validate = true (Assets:Cash) $100 @@ -8222,7 +8509,7 @@ was seen in the data file. Consider this journal: In this case, the @emph{raw} regular transaction in this file is: -@smallexample +@smallexample @c input:validate 2012-03-01 KFC Expenses:Food $100 Assets:Credit @@ -8230,7 +8517,7 @@ In this case, the @emph{raw} regular transaction in this file is: While the @emph{cooked} form is: -@smallexample +@smallexample @c input:validate 2012-03-01 KFC Expenses:Food $100 Assets:Credit $-100 @@ -8240,7 +8527,7 @@ While the @emph{cooked} form is: 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 its transactions, you are +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: @@ -8350,7 +8637,7 @@ reused in other projects as needed. @item Commoditized Amounts (amount_t, commodity_t and friends) -An numerical abstraction combining multi-precision rational numbers (via +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). @@ -8406,7 +8693,7 @@ string (cash) down to the corresponding value expression @samp{(account @item Format strings -Format strings let you interpolate value expressions into string, with +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 @@ -8448,7 +8735,7 @@ querying ad reporting on your data. @item Textual journal parser -There is a textual parser, wholly contained in textual.cc, which knows +There is a textual parser, wholly contained in @file{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. @@ -8456,7 +8743,7 @@ double-entry guarantee. @item Iterators Every journal object is ``iterable'', and these iterators are defined in -iterators.h and iterators.cc. This iteration logic is kept out of the +@file{iterators.h} and @file{iterators.cc}. This iteration logic is kept out of the basic journal objects themselves for the sake of modularity. @item Comparators @@ -8469,7 +8756,7 @@ the user passed to @option{--sort @var{VEXPR}}. Many reports bring pseudo-journal objects into existence, like postings which report totals in a @samp{Total} account. These objects are -created and managed by a temporaries_t object, which gets used in many +created and managed by a @code{temporaries_t} object, which gets used in many places by the reporting filters. @item Option handling @@ -8487,7 +8774,7 @@ a separate session. They are all owned by the global scope. @item Report objects -Every time you create report output, a report object is created to +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 @@ -8510,7 +8797,7 @@ 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 -@file{filters.h}, I see over 25 of them defined currently. +@file{filters.h}, there are over 25 of them defined currently. @item The filter chain @@ -8523,9 +8810,9 @@ exposed this layer to the Python bridge yet. @item Output modules Although filters are great and all, in the end you want to see stuff. -This is the job of special ``leaf'' filters call output modules. They +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 time on down to. Instead, they are the +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. @@ -8571,7 +8858,7 @@ one or more @dfn{postings}, which describe how @dfn{amounts} flow from one @dfn{account} to another. Here is an example of the simplest of journal files: -@smallexample +@smallexample @c input:validate 2010/05/31 Just an example Expenses:Some:Account $100.00 Income:Another:Account @@ -8580,9 +8867,9 @@ journal files: 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 in +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 practice (@pxref{Principles of Accounting +to follow standard accounting practices (@pxref{Principles of Accounting with Ledger}). Since an amount is missing from the second posting, it is assumed to be @@ -8595,7 +8882,7 @@ 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: -@smallexample +@smallexample @c input:validate 2010/05/31 An income transaction Assets:Checking $1,000.00 Income:Salary @@ -8630,7 +8917,7 @@ are covered here, though it must be said that sometimes, there are multiple ways to achieve a desired result. @emph{Note:} It is important to note that there must be at least two -spaces between the end of the post and the beginning of the amount +spaces between the end of the account and the beginning of the amount (including a commodity designator). @menu @@ -8643,7 +8930,7 @@ spaces between the end of the post and the beginning of the amount In the simplest form, bare decimal numbers are accepted: -@smallexample +@smallexample @c input:validate 2010/05/31 An income transaction Assets:Checking 1000.00 Income:Salary @@ -8750,10 +9037,10 @@ 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: -@smallexample +@smallexample @c input:validate 2010/05/31 Farmer's Market Assets:My Larder 100 apples - Assets:Checking $20.00 + Assets:Checking -$20.00 @end smallexample In this example, you have paid twenty dollars for one hundred apples. @@ -8761,18 +9048,18 @@ 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 @dfn{cost amount}: -@smallexample +@smallexample @c input:validate 2010/05/31 Farmer's Market Assets:My Larder 100 apples @@ $0.200000 Assets:Checking @end smallexample Here the @dfn{per-unit cost} is given explicitly in the form of a cost -amount; and since cost amount are @emph{unobserved}, the use of six +amount; and since cost amounts are @emph{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 @dfn{total cost}: -@smallexample +@smallexample @c input:validate 2010/05/31 Farmer's Market Assets:My Larder 100 apples @@@@ $20 Assets:Checking @@ -8782,7 +9069,7 @@ 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: -@smallexample +@smallexample @c input:validate 2010/05/31 Farmer's Market Assets:My Larder 100 apples @@ $0.200000 Assets:My Larder 100 pineapples @@ $0.33 @@ -8801,14 +9088,14 @@ posting automatically so that the transaction balances. In every transaction involving more than one commodity, there is always one which is the @dfn{primary commodity}. This commodity should be thought of as the exchange commodity, or the commodity used -to buy and sells units of the other commodity. In the fruit examples +to buy and sell units of the other commodity. In the fruit examples above, dollars are the primary commodity. This is decided by Ledger -on the placement of the commodity in the transaction: +based on the placement of the commodity in the transaction: -@smallexample +@smallexample @c input:validate 2010/05/31 Sample Transaction Expenses 100 secondary - Assets 50 primary + Assets -50 primary 2010/05/31 Sample Transaction Expenses 100 secondary @@ 0.5 primary @@ -8825,7 +9112,7 @@ play is in reports that use the @option{--market (-V)} or shown. If a transaction uses only one commodity, this commodity is also -considered a primary. In fact, when Ledger goes about ensures that +considered a primary. In fact, when Ledger goes about ensuring that all transactions balance to zero, it only ever asks this of primary commodities. @@ -8858,8 +9145,8 @@ nothing for a command line user. @subsection @command{source} @findex source -The @command{source} command take a journal file as an argument and -parses it checking for errors, no other reports are generated, and no +The @command{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. @@ -8960,7 +9247,7 @@ apply it against a model transaction. @item generate Randomly generates syntactically valid Ledger data from a seed. Used -by the GenerateTests harness for development testing. +by the @samp{GenerateTests} harness for development testing. @item parse @var{VEXPR} @itemx expr @var{VEXPR} @@ -9034,7 +9321,7 @@ true FIX THIS ENTRY @c FIXME thdox @item template -Shows the insertion template that @command{xact} sub-command generates. +Shows the insertion template that the @command{xact} sub-command generates. This is a debugging command. @end ftable @@ -9054,13 +9341,13 @@ This is a debugging command. @subsection Testing Framework Ledger source ships with a fairly complete set of tests to verify that -all is well, and no old errors have been resurfaced. Tests are run +all is well, and no old errors have resurfaced. Tests are run individually with @file{ctest}. All tests can be run using @code{make check} or @code{ninja check} depending on which build tool you prefer. Once built, the ledger executable resides under the @file{build} subdirectory in the source tree. Tests are built and stored in the -test subdirectory for the build. For example, +@file{test} subdirectory for the build. For example, @file{~/ledger/build/ledger/opt/test}. @menu @@ -9071,7 +9358,7 @@ test subdirectory for the build. For example, @node Running Tests, Writing Tests, Testing Framework, Testing Framework @subsubsection Running Tests -The complete test sweet can be run from the build directory using the +The complete test suite can be run from the build directory using the check option for the build tool you use. For example, @code{make check}. The entire test suit lasts around a minute for the optimized built and many times longer for the debug version. While developing @@ -9082,7 +9369,7 @@ build location. To execute a single test use @code{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 @file{test} subdirectory -in main source distribution. They are broken into two broad +in the main source distribution. They are broken into two broad categories, baseline and regression. To run the @file{5FBF2ED8} test, for example, issue @samp{ctest -V -R "5FB"}. @@ -9145,7 +9432,7 @@ The following journal file is included with the source distribution of ledger. It is called @file{drewr.dat} and exhibits many ledger features, include automatic and virtual transactions, -@smallexample +@smallexample @c input:validate ; -*- ledger -*- = /^Income/ @@ -9243,7 +9530,7 @@ $ ledger register Checking --sort d -d 'd>[2011/04/01]' until 2011/05/25 @node Ledger Files, , Invoking Ledger, Cookbook @subsection Ledger Files -@smallexample +@smallexample @c input:validate = /^Income:Taxable/ (Liabilities:Tithe Owed) -0.1 = /Noah/ diff --git a/lisp/CMakeLists.txt b/lisp/CMakeLists.txt index 2258fd5d..525e91aa 100644 --- a/lisp/CMakeLists.txt +++ b/lisp/CMakeLists.txt @@ -1,23 +1,24 @@ set(EMACS_LISP_SOURCES - ldg-commodities.el - ldg-complete.el - ldg-exec.el - ldg-fonts.el - ldg-init.el - ldg-mode.el - ldg-new.el - ldg-occur.el - ldg-post.el - ldg-reconcile.el - ldg-regex.el - ldg-report.el - ldg-sort.el - ldg-state.el - ldg-test.el - ldg-texi.el - ldg-xact.el - ldg-context.el - ldg-schedule.el) + ledger-commodities.el + ledger-complete.el + ledger-exec.el + ledger-fonts.el + ledger-init.el + ledger-mode.el + ledger-occur.el + ledger-post.el + ledger-reconcile.el + ledger-regex.el + ledger-report.el + ledger-schedule.el + ledger-sort.el + ledger-state.el + ledger-test.el + ledger-texi.el + ledger-xact.el) + +set(EMACS_LISP_SOURCES_UNCOMPILABLE + ledger-context.el) # find emacs and complain if not found find_program(EMACS_EXECUTABLE emacs) @@ -30,7 +31,7 @@ macro(add_emacs_lisp_target el) OUTPUT ${el}c COMMAND ${EMACS_EXECUTABLE} -L ${CMAKE_CURRENT_BINARY_DIR} - -l ${CMAKE_CURRENT_BINARY_DIR}/ldg-regex.el + -l ${CMAKE_CURRENT_BINARY_DIR}/ledger-regex.el -batch -f batch-byte-compile ${CMAKE_CURRENT_BINARY_DIR}/${el} DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${el} @@ -39,6 +40,13 @@ macro(add_emacs_lisp_target el) endmacro(add_emacs_lisp_target el) if(EMACS_EXECUTABLE) + # uncompilable .el files + foreach(el ${EMACS_LISP_SOURCES_UNCOMPILABLE}) + configure_file(${el} ${CMAKE_CURRENT_BINARY_DIR}/${el}) + list(APPEND EMACS_LISP_UNCOMPILABLE ${CMAKE_CURRENT_BINARY_DIR}/${el}) + endforeach() + + # compilable .el files foreach(el ${EMACS_LISP_SOURCES}) add_emacs_lisp_target(${el}) list(APPEND EMACS_LISP_BINARIES ${CMAKE_CURRENT_BINARY_DIR}/${el}c) @@ -47,8 +55,8 @@ if(EMACS_EXECUTABLE) add_custom_target(emacs_lisp_byte_compile ALL DEPENDS ${EMACS_LISP_BINARIES}) # install the byte-compiled emacs-lisp sources - install(FILES ${EMACS_LISP_SOURCES} ${EMACS_LISP_BINARIES} - DESTINATION share/emacs/site-lisp) + install(FILES ${EMACS_LISP_SOURCES} ${EMACS_LISP_BINARIES} ${EMACS_LISP_UNCOMPILABLE} + DESTINATION share/emacs/site-lisp/ledger-mode) endif() ### CMakeLists.txt ends here diff --git a/lisp/ledger-commodities.el b/lisp/ledger-commodities.el index 48d41979..a2cdf6ac 100644 --- a/lisp/ledger-commodities.el +++ b/lisp/ledger-commodities.el @@ -1,6 +1,6 @@ ;;; ledger-commodities.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: ;; Helper functions to deal with commoditized numbers. A commoditized @@ -34,50 +34,51 @@ :group 'ledger-reconcile) (defcustom ledger-scale 10000 - "The 10 ^ maximum number of digits you would expect to appear in your reports. -This is a cheap way of getting around floating point silliness in subtraction") + "The 10 ^ maximum number of digits you would expect to appear in your reports. +This is a cheap way of getting around floating point silliness in subtraction" + :group 'ledger) (defun ledger-split-commodity-string (str) "Split a commoditized string, STR, into two parts. Returns a list with (value commodity)." (let ((number-regex (if (assoc "decimal-comma" ledger-environment-alist) - ledger-amount-decimal-comma-regex - ledger-amount-decimal-period-regex))) - (if (> (length str) 0) - (with-temp-buffer - (insert str) - (goto-char (point-min)) - (cond - ((re-search-forward "\"\\(.*\\)\"" nil t) ; look for quoted commodities - (let ((com (delete-and-extract-region - (match-beginning 1) - (match-end 1)))) - (if (re-search-forward - number-regex nil t) - (list - (ledger-string-to-number - (delete-and-extract-region (match-beginning 0) (match-end 0))) - com)))) - ((re-search-forward number-regex nil t) - ;; found a number in the current locale, return it in the - ;; car. Anything left over is annotation, the first - ;; thing should be the commodity, separated by - ;; whitespace, return it in the cdr. I can't think of - ;; any counterexamples - (list - (ledger-string-to-number - (delete-and-extract-region (match-beginning 0) (match-end 0))) - (nth 0 (split-string (buffer-substring-no-properties (point-min) (point-max)))))) - ((re-search-forward "0" nil t) - ;; couldn't find a decimal number, look for a single 0, - ;; indicating account with zero balance - (list 0 ledger-reconcile-default-commodity)))) - ;; nothing found, return 0 - (list 0 ledger-reconcile-default-commodity)))) + ledger-amount-decimal-comma-regex + ledger-amount-decimal-period-regex))) + (if (> (length str) 0) + (with-temp-buffer + (insert str) + (goto-char (point-min)) + (cond + ((re-search-forward "\"\\(.*\\)\"" nil t) ; look for quoted commodities + (let ((com (delete-and-extract-region + (match-beginning 1) + (match-end 1)))) + (if (re-search-forward + number-regex nil t) + (list + (ledger-string-to-number + (delete-and-extract-region (match-beginning 0) (match-end 0))) + com)))) + ((re-search-forward number-regex nil t) + ;; found a number in the current locale, return it in the + ;; car. Anything left over is annotation, the first + ;; thing should be the commodity, separated by + ;; whitespace, return it in the cdr. I can't think of + ;; any counterexamples + (list + (ledger-string-to-number + (delete-and-extract-region (match-beginning 0) (match-end 0))) + (nth 0 (split-string (buffer-substring-no-properties (point-min) (point-max)))))) + ((re-search-forward "0" nil t) + ;; couldn't find a decimal number, look for a single 0, + ;; indicating account with zero balance + (list 0 ledger-reconcile-default-commodity)))) + ;; nothing found, return 0 + (list 0 ledger-reconcile-default-commodity)))) (defun ledger-string-balance-to-commoditized-amount (str) "Return a commoditized amount (val, 'comm') from STR." - ; break any balances with multi commodities into a list + ; break any balances with multi commodities into a list (mapcar #'(lambda (st) (ledger-split-commodity-string st)) (split-string str "[\n\r]"))) @@ -85,8 +86,10 @@ Returns a list with (value commodity)." (defun -commodity (c1 c2) "Subtract C2 from C1, ensuring their commodities match." (if (string= (cadr c1) (cadr c2)) - ; the scaling below is to get around inexact subtraction results where, for example - ; 1.23 - 4.56 = -3.3299999999999996 instead of -3.33 + ; the scaling below is to get around inexact + ; subtraction results where, for example 1.23 + ; - 4.56 = -3.3299999999999996 instead of + ; -3.33 (list (/ (- (* ledger-scale (car c1)) (* ledger-scale (car c2))) ledger-scale) (cadr c1)) (error "Can't subtract different commodities %S from %S" c2 c1))) @@ -97,50 +100,50 @@ Returns a list with (value commodity)." (error "Can't add different commodities, %S to %S" c1 c2))) (defun ledger-strip (str char) - (let (new-str) - (concat (dolist (ch (append str nil) new-str) - (unless (= ch char) - (setq new-str (append new-str (list ch)))))))) + (let (new-str) + (concat (dolist (ch (append str nil) new-str) + (unless (= ch char) + (setq new-str (append new-str (list ch)))))))) (defun ledger-string-to-number (str &optional decimal-comma) - "improve builtin string-to-number by handling internationalization, and return nil if number can't be parsed" - (let ((nstr (if (or decimal-comma - (assoc "decimal-comma" ledger-environment-alist)) - (ledger-strip str ?.) - (ledger-strip str ?,)))) - (while (string-match "," nstr) ;if there is a comma now, it is a thousands separator - (setq nstr (replace-match "." nil nil nstr))) - (string-to-number nstr))) + "improve builtin string-to-number by handling internationalization, and return nil if number can't be parsed" + (let ((nstr (if (or decimal-comma + (assoc "decimal-comma" ledger-environment-alist)) + (ledger-strip str ?.) + (ledger-strip str ?,)))) + (while (string-match "," nstr) ;if there is a comma now, it is a thousands separator + (setq nstr (replace-match "." nil nil nstr))) + (string-to-number nstr))) (defun ledger-number-to-string (n &optional decimal-comma) - (let ((str (number-to-string n))) - (if (or decimal-comma - (assoc "decimal-comma" ledger-environment-alist)) - (while (string-match "\\." str) - (setq str (replace-match "," nil nil str))) - str))) + (let ((str (number-to-string n))) + (when (or decimal-comma + (assoc "decimal-comma" ledger-environment-alist)) + (while (string-match "\\." str) + (setq str (replace-match "," nil nil str)))) + str)) (defun ledger-commodity-to-string (c1) "Return string representing C1. Single character commodities are placed ahead of the value, longer ones are after the value." - (let ((str (ledger-number-to-string (car c1))) - (commodity (cadr c1))) - (if (> (length commodity) 1) - (concat str " " commodity) - (concat commodity " " str)))) + (let ((str (ledger-number-to-string (car c1))) + (commodity (cadr c1))) + (if (> (length commodity) 1) + (concat str " " commodity) + (concat commodity " " str)))) (defun ledger-read-commodity-string (prompt) (let ((str (read-from-minibuffer - (concat prompt " (" ledger-reconcile-default-commodity "): "))) - comm) + (concat prompt " (" ledger-reconcile-default-commodity "): "))) + comm) (if (and (> (length str) 0) - (ledger-split-commodity-string str)) - (progn - (setq comm (ledger-split-commodity-string str)) - (if (cadr comm) - comm - (list (car comm) ledger-reconcile-default-commodity)))))) + (ledger-split-commodity-string str)) + (progn + (setq comm (ledger-split-commodity-string str)) + (if (cadr comm) + comm + (list (car comm) ledger-reconcile-default-commodity)))))) (provide 'ledger-commodities) diff --git a/lisp/ledger-complete.el b/lisp/ledger-complete.el index a8ef9a8a..fd4cbcc0 100644 --- a/lisp/ledger-complete.el +++ b/lisp/ledger-complete.el @@ -1,6 +1,6 @@ ;;; ledger-complete.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: ;; Functions providing payee and account auto complete. @@ -34,8 +34,8 @@ ;; with pcomplete. See pcomplete-parse-arguments-function for ;; details (let* ((begin (save-excursion - (ledger-thing-at-point) ;; leave point at beginning of thing under point - (point))) + (ledger-thing-at-point) ;; leave point at beginning of thing under point + (point))) (end (point)) begins args) ;; to support end of line metadata @@ -65,42 +65,42 @@ (unless (and (>= origin (match-beginning 0)) (< origin (match-end 0))) (setq payees-list (cons (match-string-no-properties 3) - payees-list))))) ;; add the payee - ;; to the list + payees-list))))) ;; add the payee + ;; to the list (pcomplete-uniqify-list (nreverse payees-list)))) (defun ledger-find-accounts-in-buffer () - (interactive) - (let ((origin (point)) - accounts - (account-tree (list t)) - (account-elements nil) - (seed-regex (ledger-account-any-status-with-seed-regex - (regexp-quote (car pcomplete-args))))) - (save-excursion - (goto-char (point-min)) + (interactive) + (let ((origin (point)) + accounts + (account-tree (list t)) + (account-elements nil) + (seed-regex (ledger-account-any-status-with-seed-regex + (regexp-quote (car pcomplete-args))))) + (save-excursion + (goto-char (point-min)) - (dolist (account - (delete-dups - (progn - (while (re-search-forward seed-regex nil t) - (unless (between origin (match-beginning 0) (match-end 0)) - (setq accounts (cons (match-string-no-properties 2) accounts)))) - accounts))) - (let ((root account-tree)) + (dolist (account + (delete-dups + (progn + (while (re-search-forward seed-regex nil t) + (unless (between origin (match-beginning 0) (match-end 0)) + (setq accounts (cons (match-string-no-properties 2) accounts)))) + accounts))) + (let ((root account-tree)) (setq account-elements - (split-string - account ":")) - (while account-elements - (let ((xact (assoc (car account-elements) root))) - (if xact - (setq root (cdr xact)) - (setq xact (cons (car account-elements) (list t))) - (nconc root (list xact)) - (setq root (cdr xact)))) - (setq account-elements (cdr account-elements)))))) - account-tree)) + (split-string + account ":")) + (while account-elements + (let ((xact (assoc (car account-elements) root))) + (if xact + (setq root (cdr xact)) + (setq xact (cons (car account-elements) (list t))) + (nconc root (list xact)) + (setq root (cdr xact)))) + (setq account-elements (cdr account-elements)))))) + account-tree)) (defun ledger-find-metadata-in-buffer () "Search through buffer and build list of metadata. @@ -129,19 +129,19 @@ Return list." (setq prefix (concat prefix (and prefix ":") (car elements)) root (cdr xact)) - (setq root nil elements nil))) + (setq root nil elements nil))) (setq elements (cdr elements))) (setq root (delete (list (car elements) t) root)) (and root (sort (mapcar (function (lambda (x) - (let ((term (if prefix - (concat prefix ":" (car x)) - (car x)))) - (if (> (length (cdr x)) 1) - (concat term ":") - term)))) + (let ((term (if prefix + (concat prefix ":" (car x)) + (car x)))) + (if (> (length (cdr x)) 1) + (concat term ":") + term)))) (cdr root)) 'string-lessp)))) @@ -155,27 +155,32 @@ Return list." (delete (caar (ledger-parse-arguments)) (ledger-payees-in-buffer)) ;; this completes against payee names - (progn - (let ((text (buffer-substring-no-properties - (line-beginning-position) - (line-end-position)))) - (delete-region (line-beginning-position) - (line-end-position)) - (condition-case nil - (ledger-add-transaction text t) - (error nil))) - (forward-line) - (goto-char (line-end-position)) - (search-backward ";" (line-beginning-position) t) - (skip-chars-backward " \t0123456789.,") - (throw 'pcompleted t))) - (ledger-accounts))))) + (progn + (let ((text (buffer-substring-no-properties + (line-beginning-position) + (line-end-position)))) + (delete-region (line-beginning-position) + (line-end-position)) + (condition-case nil + (ledger-add-transaction text t) + (error nil))) + (forward-line) + (goto-char (line-end-position)) + (search-backward ";" (line-beginning-position) t) + (skip-chars-backward " \t0123456789.,") + (throw 'pcompleted t))) + (ledger-accounts))))) + +(defun ledger-trim-trailing-whitespace (str) + (let ((s str)) + (when (string-match "[ \t]*$" s) + (replace-match "" nil nil s)))) (defun ledger-fully-complete-xact () "Completes a transaction if there is another matching payee in the buffer. Does not use ledger xact" (interactive) - (let* ((name (caar (ledger-parse-arguments))) + (let* ((name (ledger-trim-trailing-whitespace (caar (ledger-parse-arguments)))) (rest-of-name name) xacts) (save-excursion @@ -208,35 +213,41 @@ Does not use ledger xact" (goto-char (match-end 0)))))) +(defcustom ledger-complete-ignore-case t + "Non-nil means that ledger-complete-at-point will be case-insensitive" + :type 'boolean + :group 'ledger) + (defun ledger-pcomplete (&optional interactively) "Complete rip-off of pcomplete from pcomplete.el, only added ledger-magic-tab in the previous commands list so that ledger-magic-tab would cycle properly" (interactive "p") - (if (and interactively - pcomplete-cycle-completions - pcomplete-current-completions - (memq last-command '(ledger-magic-tab - ledger-pcomplete - pcomplete-expand-and-complete - pcomplete-reverse))) - (progn - (delete-backward-char pcomplete-last-completion-length) - (if (eq this-command 'pcomplete-reverse) - (progn - (push (car (last pcomplete-current-completions)) - pcomplete-current-completions) - (setcdr (last pcomplete-current-completions 2) nil)) + (let ((pcomplete-ignore-case ledger-complete-ignore-case)) + (if (and interactively + pcomplete-cycle-completions + pcomplete-current-completions + (memq last-command '(ledger-magic-tab + ledger-pcomplete + pcomplete-expand-and-complete + pcomplete-reverse))) + (progn + (delete-backward-char pcomplete-last-completion-length) + (if (eq this-command 'pcomplete-reverse) + (progn + (push (car (last pcomplete-current-completions)) + pcomplete-current-completions) + (setcdr (last pcomplete-current-completions 2) nil)) (nconc pcomplete-current-completions (list (car pcomplete-current-completions))) (setq pcomplete-current-completions (cdr pcomplete-current-completions))) - (pcomplete-insert-entry pcomplete-last-completion-stub - (car pcomplete-current-completions) - nil pcomplete-last-completion-raw)) - (setq pcomplete-current-completions nil + (pcomplete-insert-entry pcomplete-last-completion-stub + (car pcomplete-current-completions) + nil pcomplete-last-completion-raw)) + (setq pcomplete-current-completions nil pcomplete-last-completion-raw nil) - (catch 'pcompleted + (catch 'pcompleted (let* ((pcomplete-stub) pcomplete-seen pcomplete-norm-func pcomplete-args pcomplete-last pcomplete-index @@ -250,7 +261,7 @@ ledger-magic-tab would cycle properly" (pcomplete-insert-entry pcomplete-stub (cdr result) (memq (car result) '(sole shortest)) - pcomplete-last-completion-raw)))))) + pcomplete-last-completion-raw))))))) (provide 'ledger-complete) diff --git a/lisp/ledger-context.el b/lisp/ledger-context.el index b1bcd870..064ac380 100644 --- a/lisp/ledger-context.el +++ b/lisp/ledger-context.el @@ -1,6 +1,6 @@ ;;; ledger-context.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: @@ -28,56 +28,57 @@ (eval-when-compile (require 'cl)) -;; *-string constants are assembled in the single-line-config macro to -;; form the regex and list of elements -(defconst indent-string "\\(^[ \t]+\\)") -(defconst status-string "\\([*! ]?\\)") -(defconst account-string "[\\[(]?\\(.*?\\)[])]?") -(defconst amount-string "[ \t]?\\(-?[0-9]+\\.[0-9]*\\)") -(defconst comment-string "[ \t]*;[ \t]*\\(.*?\\)") -(defconst nil-string "\\([ \t]+\\)") -(defconst commodity-string "\\(.+?\\)") -(defconst date-string "^\\([0-9]\\{4\\}[/-][01]?[0-9][/-][0123]?[0-9]\\)") -(defconst code-string "\\((.*)\\)?") -(defconst payee-string "\\(.*\\)") - -(defmacro line-regex (&rest elements) +;; ledger-*-string constants are assembled in the +;; `ledger-single-line-config' macro to form the regex and list of +;; elements +(defconst ledger-indent-string "\\(^[ \t]+\\)") +(defconst ledger-status-string "\\([*! ]?\\)") +(defconst ledger-account-string "[\\[(]?\\(.*?\\)[])]?") +(defconst ledger-amount-string "[ \t]?\\(-?[0-9]+\\.[0-9]*\\)") +(defconst ledger-comment-string "[ \t]*;[ \t]*\\(.*?\\)") +(defconst ledger-nil-string "\\([ \t]+\\)") +(defconst ledger-commodity-string "\\(.+?\\)") +(defconst ledger-date-string "^\\([0-9]\\{4\\}[/-][01]?[0-9][/-][0123]?[0-9]\\)") +(defconst ledger-code-string "\\((.*)\\)?") +(defconst ledger-payee-string "\\(.*\\)") + +(defmacro ledger-line-regex (&rest elements) (let (regex-string) (concat (dolist (e elements regex-string) (setq regex-string (concat regex-string (eval (intern - (concat (symbol-name e) "-string")))))) "[ \t]*$"))) + (concat "ledger-" (symbol-name e) "-string")))))) "[ \t]*$"))) -(defmacro single-line-config2 (&rest elements) -"Take list of ELEMENTS and return regex and element list for use in context-at-point" +(defmacro ledger-single-line-config2 (&rest elements) + "Take list of ELEMENTS and return regex and element list for use in context-at-point" (let (regex-string) `'(,(concat (dolist (e elements regex-string) - (setq regex-string - (concat regex-string - (eval - (intern - (concat (symbol-name e) "-string")))))) "[ \t]*$") + (setq regex-string + (concat regex-string + (eval + (intern + (concat "ledger-" (symbol-name e) "-string")))))) "[ \t]*$") ,elements))) -(defmacro single-line-config (&rest elements) +(defmacro ledger-single-line-config (&rest elements) "Take list of ELEMENTS and return regex and element list for use in context-at-point" - `'(,(eval `(line-regex ,@elements)) + `'(,(eval `(ledger-line-regex ,@elements)) ,elements)) (defconst ledger-line-config - (list (list 'xact (list (single-line-config date nil status nil code nil payee nil comment) - (single-line-config date nil status nil code nil payee) - (single-line-config date nil status nil payee))) - (list 'acct-transaction (list (single-line-config indent comment) - (single-line-config2 indent status account nil commodity amount nil comment) - (single-line-config2 indent status account nil commodity amount) - (single-line-config2 indent status account nil amount nil commodity comment) - (single-line-config2 indent status account nil amount nil commodity) - (single-line-config2 indent status account nil amount) - (single-line-config2 indent status account nil comment) - (single-line-config2 indent status account))))) + (list (list 'xact (list (ledger-single-line-config date nil status nil code nil payee nil comment) + (ledger-single-line-config date nil status nil code nil payee) + (ledger-single-line-config date nil status nil payee))) + (list 'acct-transaction (list (ledger-single-line-config indent comment) + (ledger-single-line-config2 indent status account nil commodity amount nil comment) + (ledger-single-line-config2 indent status account nil commodity amount) + (ledger-single-line-config2 indent status account nil amount nil commodity comment) + (ledger-single-line-config2 indent status account nil amount nil commodity) + (ledger-single-line-config2 indent status account nil amount) + (ledger-single-line-config2 indent status account nil comment) + (ledger-single-line-config2 indent status account))))) (defun ledger-extract-context-info (line-type pos) "Get context info for current line with LINE-TYPE. @@ -113,7 +114,7 @@ Leave point at the beginning of the thing under point" (cond ((looking-at "^[0-9/.=-]+\\(\\s-+\\*\\)?\\(\\s-+(.+?)\\)?\\s-+") (goto-char (match-end 0)) 'transaction) - ((looking-at "^\\s-+\\([*!]\\s-+\\)?[[(]?\\(.\\)") + ((looking-at "^\\s-+\\([*!]\\s-+\\)?[[(]?\\([^\\s-]\\)") (goto-char (match-beginning 2)) 'posting) ((looking-at "^\\(sun\\|mon\\|tue\\|wed\\|thu\\|fri\\|sat\\)\\s-+") diff --git a/lisp/ledger-exec.el b/lisp/ledger-exec.el index 95b28ec2..13a99125 100644 --- a/lisp/ledger-exec.el +++ b/lisp/ledger-exec.el @@ -1,6 +1,6 @@ ;;; ledger-exec.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: @@ -97,11 +97,10 @@ (defun ledger-check-version () "Verify that ledger works and is modern enough." (interactive) - (if ledger-mode-should-check-version - (if (setq ledger-works (ledger-version-greater-p ledger-version-needed)) - (message "Good Ledger Version") - (message "Bad Ledger Version")) - setq ledger-works t)) + (if ledger-mode-should-check-version + (if (setq ledger-works (ledger-version-greater-p ledger-version-needed)) + (message "Good Ledger Version") + (message "Bad Ledger Version")))) (provide 'ledger-exec) diff --git a/lisp/ledger-fonts.el b/lisp/ledger-fonts.el index 28f1f98d..5194e876 100644 --- a/lisp/ledger-fonts.el +++ b/lisp/ledger-fonts.el @@ -1,6 +1,6 @@ ;;; ledger-fonts.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. @@ -40,7 +40,8 @@ :group 'ledger-faces) (defface ledger-font-xact-highlight-face - `((t :background "#eee8d5")) + `((((background dark)) :background "#1a1a1a" ) + (t :background "#eee8d5")) "Default face for transaction under point" :group 'ledger-faces) @@ -80,7 +81,8 @@ :group 'ledger-faces) (defface ledger-occur-xact-face - `((t :background "#eee8d5" )) + `((((background dark)) :background "#1a1a1a" ) + (t :background "#eee8d5" )) "Default face for Ledger occur mode shown transactions" :group 'ledger-faces) diff --git a/lisp/ledger-init.el b/lisp/ledger-init.el index fd06d4c5..531f2c45 100644 --- a/lisp/ledger-init.el +++ b/lisp/ledger-init.el @@ -1,6 +1,6 @@ ;;; ledger-init.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: ;; Determine the ledger environment @@ -30,38 +30,41 @@ (defvar ledger-environment-alist nil) +(defvar ledger-default-date-format "%Y/%m/%d") + (defun ledger-init-parse-initialization (buffer) (with-current-buffer buffer (let (environment-alist) (goto-char (point-min)) (while (re-search-forward ledger-init-string-regex nil t ) - (let ((matchb (match-beginning 0)) ;; save the match data, string-match stamp on it - (matche (match-end 0))) - (end-of-line) - (setq environment-alist - (append environment-alist - (list (cons (let ((flag (buffer-substring-no-properties (+ 2 matchb) matche))) - (if (string-match "[ \t\n\r]+\\'" flag) - (replace-match "" t t flag) - flag)) - (let ((value (buffer-substring-no-properties matche (point) ))) - (if (> (length value) 0) - value - t)))))))) + (let ((matchb (match-beginning 0)) ;; save the match data, string-match stamp on it + (matche (match-end 0))) + (end-of-line) + (setq environment-alist + (append environment-alist + (list (cons (let ((flag (buffer-substring-no-properties (+ 2 matchb) matche))) + (if (string-match "[ \t\n\r]+\\'" flag) + (replace-match "" t t flag) + flag)) + (let ((value (buffer-substring-no-properties matche (point) ))) + (if (> (length value) 0) + value + t)))))))) environment-alist))) (defun ledger-init-load-init-file () (interactive) (let ((init-base-name (file-name-nondirectory ledger-init-file-name))) (if (get-buffer init-base-name) ;; init file already loaded, parse it and leave it - (ledger-init-parse-initialization init-base-name) - (when (and ledger-init-file-name - (file-exists-p ledger-init-file-name) - (file-readable-p ledger-init-file-name)) - (find-file-noselect ledger-init-file-name) - (setq ledger-environment-alist - (ledger-init-parse-initialization init-base-name)) - (kill-buffer init-base-name))))) + (setq ledger-environment-alist + (ledger-init-parse-initialization init-base-name)) + (when (and ledger-init-file-name + (file-exists-p ledger-init-file-name) + (file-readable-p ledger-init-file-name)) + (find-file-noselect ledger-init-file-name) + (setq ledger-environment-alist + (ledger-init-parse-initialization init-base-name)) + (kill-buffer init-base-name))))) (provide 'ledger-init) diff --git a/lisp/ledger-mode.el b/lisp/ledger-mode.el index 387ace97..07e6732a 100644 --- a/lisp/ledger-mode.el +++ b/lisp/ledger-mode.el @@ -1,6 +1,6 @@ ;;; ledger-mode.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. @@ -29,6 +29,7 @@ (require 'ledger-regex) (require 'esh-util) (require 'esh-arg) +(require 'easymenu) (require 'ledger-commodities) (require 'ledger-complete) (require 'ledger-context) @@ -92,31 +93,43 @@ (defun ledger-read-account-with-prompt (prompt) (let* ((context (ledger-context-at-point)) - (default (if (and (eq (ledger-context-line-type context) 'acct-transaction) - (eq (ledger-context-current-field context) 'account)) - (regexp-quote (ledger-context-field-value context 'account)) - nil))) + (default (if (and (eq (ledger-context-line-type context) 'acct-transaction) + (eq (ledger-context-current-field context) 'account)) + (regexp-quote (ledger-context-field-value context 'account)) + nil))) (ledger-read-string-with-default prompt default))) +(defun ledger-read-date (prompt) + "Returns user-supplied date after `PROMPT', defaults to today." + (let* ((default (ledger-year-and-month)) + (date (read-string prompt default + 'ledger-minibuffer-history))) + (if (or (string= date default) + (string= "" date)) + (format-time-string + (or (cdr (assoc "date-format" ledger-environment-alist)) + ledger-default-date-format)) + date))) + (defun ledger-read-string-with-default (prompt default) "Return user supplied string after PROMPT, or DEFAULT." (read-string (concat prompt - (if default - (concat " (" default "): ") - ": ")) - nil 'ledger-minibuffer-history default)) + (if default + (concat " (" default "): ") + ": ")) + nil 'ledger-minibuffer-history default)) (defun ledger-display-balance-at-point () "Display the cleared-or-pending balance. And calculate the target-delta of the account being reconciled." (interactive) (let* ((account (ledger-read-account-with-prompt "Account balance to show")) - (buffer (current-buffer)) - (balance (with-temp-buffer - (ledger-exec-ledger buffer (current-buffer) "cleared" account) - (if (> (buffer-size) 0) - (buffer-substring-no-properties (point-min) (1- (point-max))) - (concat account " is empty."))))) + (buffer (current-buffer)) + (balance (with-temp-buffer + (ledger-exec-ledger buffer (current-buffer) "cleared" account) + (if (> (buffer-size) 0) + (buffer-substring-no-properties (point-min) (1- (point-max))) + (concat account " is empty."))))) (when balance (message balance)))) @@ -125,9 +138,9 @@ And calculate the target-delta of the account being reconciled." And calculate the target-delta of the account being reconciled." (interactive) (let* ((buffer (current-buffer)) - (balance (with-temp-buffer - (ledger-exec-ledger buffer (current-buffer) "stats") - (buffer-substring-no-properties (point-min) (1- (point-max)))))) + (balance (with-temp-buffer + (ledger-exec-ledger buffer (current-buffer) "stats") + (buffer-substring-no-properties (point-min) (1- (point-max)))))) (when balance (message balance)))) @@ -135,71 +148,95 @@ And calculate the target-delta of the account being reconciled." "Decide what to with with <TAB>. Can indent, complete or align depending on context." (interactive "p") - (if (= (point) (line-beginning-position)) - (indent-to ledger-post-account-alignment-column) - (if (and (> (point) 1) - (looking-back "\\([^ \t]\\)" 1)) - (ledger-pcomplete interactively) - (ledger-post-align-postings)))) + (if (= (point) (line-beginning-position)) + (indent-to ledger-post-account-alignment-column) + (if (and (> (point) 1) + (looking-back "\\([^ \t]\\)" 1)) + (ledger-pcomplete interactively) + (ledger-post-align-postings)))) (defvar ledger-mode-abbrev-table) -(defun ledger-insert-effective-date () +(defvar ledger-date-string-today + (format-time-string (or + (cdr (assoc "date-format" ledger-environment-alist)) + ledger-default-date-format))) + +(defun ledger-remove-effective-date () + "Removes the effective date from a transaction or posting." (interactive) - (let ((context (car (ledger-context-at-point))) - (date-string (format-time-string (cdr (assoc "date-format" ledger-environment-alist))))) - (cond ((eq 'xact context) - (beginning-of-line) - (insert date-string "=")) - ((eq 'acct-transaction context) - (end-of-line) - (insert " ; [=" date-string "]"))))) + (let ((context (car (ledger-context-at-point)))) + (save-excursion + (save-restriction + (narrow-to-region (point-at-bol) (point-at-eol)) + (beginning-of-line) + (cond ((eq 'pmnt-transaction context) + (re-search-forward ledger-iso-date-regexp) + (when (= (char-after) ?=) + (let ((eq-pos (point))) + (delete-region + eq-pos + (re-search-forward ledger-iso-date-regexp))))) + ((eq 'acct-transaction context) + ;; Match "; [=date]" & delete string + (when (re-search-forward + (concat ledger-comment-regex + "\\[=" ledger-iso-date-regexp "\\]") + nil 'noerr) + (replace-match "")))))))) + +(defun ledger-insert-effective-date (&optional date) + "Insert effective date `DATE' to the transaction or posting. + +If `DATE' is nil, prompt the user a date. + +Replace the current effective date if there's one in the same +line. + +With a prefix argument, remove the effective date. " + (interactive) + (if (and (listp current-prefix-arg) + (= 4 (prefix-numeric-value current-prefix-arg))) + (ledger-remove-effective-date) + (let* ((context (car (ledger-context-at-point))) + (date-string (or date (ledger-read-date "Effective date: ")))) + (save-restriction + (narrow-to-region (point-at-bol) (point-at-eol)) + (cond + ((eq 'pmnt-transaction context) + (beginning-of-line) + (re-search-forward ledger-iso-date-regexp) + (when (= (char-after) ?=) + (ledger-remove-effective-date)) + (insert "=" date-string)) + ((eq 'acct-transaction context) + (end-of-line) + (ledger-remove-effective-date) + (insert " ; [=" date-string "]"))))))) (defun ledger-mode-remove-extra-lines () - (goto-char (point-min)) - (while (re-search-forward "\n\n\\(\n\\)+" nil t) - (replace-match "\n\n"))) + (goto-char (point-min)) + (while (re-search-forward "\n\n\\(\n\\)+" nil t) + (replace-match "\n\n"))) (defun ledger-mode-clean-buffer () - "indent, remove multiple linfe feeds and sort the buffer" - (interactive) - (ledger-sort-buffer) - (ledger-post-align-postings (point-min) (point-max)) - (ledger-mode-remove-extra-lines)) - - -;;;###autoload -(define-derived-mode ledger-mode text-mode "Ledger" - "A mode for editing ledger data files." - (ledger-check-version) - (ledger-post-setup) - - (set (make-local-variable 'comment-start) "; ") - (set (make-local-variable 'comment-end) "") - (set (make-local-variable 'indent-tabs-mode) nil) - - (if (boundp 'font-lock-defaults) - (set (make-local-variable 'font-lock-defaults) - '(ledger-font-lock-keywords nil t))) - (setq font-lock-extend-region-functions - (list #'font-lock-extend-region-wholelines)) - (setq font-lock-multiline nil) - - (set (make-local-variable 'pcomplete-parse-arguments-function) - 'ledger-parse-arguments) - (set (make-local-variable 'pcomplete-command-completion-function) - 'ledger-complete-at-point) - (set (make-local-variable 'pcomplete-termination-string) "") - - (add-hook 'post-command-hook 'ledger-highlight-xact-under-point nil t) - (add-hook 'before-revert-hook 'ledger-occur-remove-all-overlays nil t) - (make-variable-buffer-local 'highlight-overlay) + "indent, remove multiple linfe feeds and sort the buffer" + (interactive) + (ledger-sort-buffer) + (ledger-post-align-postings (point-min) (point-max)) + (ledger-mode-remove-extra-lines)) - (ledger-init-load-init-file) - (set (make-local-variable 'indent-region-function) 'ledger-post-align-postings) +(defvar ledger-mode-syntax-table + (let ((table (make-syntax-table))) + ;; Support comments via the syntax table + (modify-syntax-entry ?\; "< b" table) + (modify-syntax-entry ?\n "> b" table) + table) + "Syntax table for `ledger-mode' buffers.") - (let ((map (current-local-map))) +(defvar ledger-mode-map + (let ((map (make-sparse-keymap))) (define-key map [(control ?c) (control ?a)] 'ledger-add-transaction) (define-key map [(control ?c) (control ?b)] 'ledger-post-edit-amount) (define-key map [(control ?c) (control ?c)] 'ledger-toggle-current) @@ -232,67 +269,101 @@ Can indent, complete or align depending on context." (define-key map [(meta ?p)] 'ledger-post-prev-xact) (define-key map [(meta ?n)] 'ledger-post-next-xact) + map) + "Keymap for `ledger-mode'.") + +(easy-menu-define ledger-mode-menu ledger-mode-map + "Ledger menu" + '("Ledger" + ["Narrow to REGEX" ledger-occur] + ["Ledger Statistics" ledger-display-ledger-stats ledger-works] + "---" + ["Show upcoming transactions" ledger-schedule-upcoming ledger-schedule-available] + ["Add Transaction (ledger xact)" ledger-add-transaction ledger-works] + ["Complete Transaction" ledger-fully-complete-xact] + ["Delete Transaction" ledger-delete-current-transaction] + "---" + ["Calc on Amount" ledger-post-edit-amount] + "---" + ["Check Balance" ledger-display-balance-at-point ledger-works] + ["Reconcile Account" ledger-reconcile ledger-works] + "---" + ["Toggle Current Transaction" ledger-toggle-current-transaction] + ["Toggle Current Posting" ledger-toggle-current] + ["Copy Trans at Point" ledger-copy-transaction-at-point] + "---" + ["Clean-up Buffer" ledger-mode-clean-buffer] + ["Align Region" ledger-post-align-postings mark-active] + ["Align Xact" ledger-post-align-xact] + ["Sort Region" ledger-sort-region mark-active] + ["Sort Buffer" ledger-sort-buffer] + ["Mark Sort Beginning" ledger-sort-insert-start-mark] + ["Mark Sort End" ledger-sort-insert-end-mark] + ["Set effective date" ledger-insert-effective-date] + "---" + ["Customize Ledger Mode" (lambda () (interactive) (customize-group 'ledger))] + ["Set Year" ledger-set-year ledger-works] + ["Set Month" ledger-set-month ledger-works] + "---" + ["Run Report" ledger-report ledger-works] + ["Goto Report" ledger-report-goto ledger-works] + ["Re-run Report" ledger-report-redo ledger-works] + ["Save Report" ledger-report-save ledger-works] + ["Edit Report" ledger-report-edit ledger-works] + ["Kill Report" ledger-report-kill ledger-works] + )) + +;;;###autoload +(define-derived-mode ledger-mode text-mode "Ledger" + "A mode for editing ledger data files." + (ledger-check-version) + (ledger-schedule-check-available) + (ledger-post-setup) + + (set-syntax-table ledger-mode-syntax-table) + (set (make-local-variable 'comment-start) "; ") + (set (make-local-variable 'comment-end) "") + (set (make-local-variable 'indent-tabs-mode) nil) + + (if (boundp 'font-lock-defaults) + (set (make-local-variable 'font-lock-defaults) + '(ledger-font-lock-keywords nil t))) + (setq font-lock-extend-region-functions + (list #'font-lock-extend-region-wholelines)) + (setq font-lock-multiline nil) + + (set (make-local-variable 'pcomplete-parse-arguments-function) + 'ledger-parse-arguments) + (set (make-local-variable 'pcomplete-command-completion-function) + 'ledger-complete-at-point) + (add-hook 'completion-at-point-functions 'pcomplete-completions-at-point nil t) - (define-key map [menu-bar] (make-sparse-keymap "ledger-menu")) - (define-key map [menu-bar ledger-menu] (cons "Ledger" map)) - - (define-key map [report-kill] '(menu-item "Kill Report" ledger-report-kill :enable ledger-works)) - (define-key map [report-edit] '(menu-item "Edit Report" ledger-report-edit :enable ledger-works)) - (define-key map [report-save] '(menu-item "Save Report" ledger-report-save :enable ledger-works)) - (define-key map [report-rrun] '(menu-item "Re-run Report" ledger-report-redo :enable ledger-works)) - (define-key map [report-goto] '(menu-item "Goto Report" ledger-report-goto :enable ledger-works)) - (define-key map [report-run] '(menu-item "Run Report" ledger-report :enable ledger-works)) - (define-key map [sep5] '(menu-item "--")) - (define-key map [set-month] '(menu-item "Set Month" ledger-set-month :enable ledger-works)) - (define-key map [set-year] '(menu-item "Set Year" ledger-set-year :enable ledger-works)) - (define-key map [cust] '(menu-item "Customize Ledger Mode" (lambda () - (interactive) - (customize-group 'ledger)))) - (define-key map [sep1] '("--")) - (define-key map [effective-date] '(menu-item "Set effective date" ledger-insert-effective-date)) - (define-key map [sort-end] '(menu-item "Mark Sort End" ledger-sort-insert-end-mark)) - (define-key map [sort-start] '(menu-item "Mark Sort Beginning" ledger-sort-insert-start-mark)) - (define-key map [sort-buff] '(menu-item "Sort Buffer" ledger-sort-buffer)) - (define-key map [sort-reg] '(menu-item "Sort Region" ledger-sort-region :enable mark-active)) - (define-key map [align-xact] '(menu-item "Align Xact" ledger-post-align-xact)) - (define-key map [align-reg] '(menu-item "Align Region" ledger-post-align-postings :enable mark-active)) - (define-key map [clean-buf] '(menu-item "Clean-up Buffer" ledger-mode-clean-buffer)) - (define-key map [sep2] '(menu-item "--")) - (define-key map [copy-xact] '(menu-item "Copy Trans at Point" ledger-copy-transaction-at-point)) - (define-key map [toggle-post] '(menu-item "Toggle Current Posting" ledger-toggle-current)) - (define-key map [toggle-xact] '(menu-item "Toggle Current Transaction" ledger-toggle-current-transaction)) - (define-key map [sep4] '(menu-item "--")) - (define-key map [recon-account] '(menu-item "Reconcile Account" ledger-reconcile :enable ledger-works)) - (define-key map [check-balance] '(menu-item "Check Balance" ledger-display-balance-at-point :enable ledger-works)) - (define-key map [sep6] '(menu-item "--")) - (define-key map [edit-amount] '(menu-item "Calc on Amount" ledger-post-edit-amount)) - (define-key map [sep] '(menu-item "--")) - (define-key map [delete-xact] '(menu-item "Delete Transaction" ledger-delete-current-transaction)) - (define-key map [cmp-xact] '(menu-item "Complete Transaction" ledger-fully-complete-xact)) - (define-key map [add-xact] '(menu-item "Add Transaction (ledger xact)" ledger-add-transaction :enable ledger-works)) - (define-key map [sep3] '(menu-item "--")) - (define-key map [stats] '(menu-item "Ledger Statistics" ledger-display-ledger-stats :enable ledger-works)) - (define-key map [fold-buffer] '(menu-item "Narrow to REGEX" ledger-occur)))) + (add-hook 'post-command-hook 'ledger-highlight-xact-under-point nil t) + (add-hook 'before-revert-hook 'ledger-occur-remove-all-overlays nil t) + (ledger-init-load-init-file) + (set (make-local-variable 'indent-region-function) 'ledger-post-align-postings)) (defun ledger-set-year (newyear) "Set ledger's idea of the current year to the prefix argument NEWYEAR." (interactive "p") - (if (= newyear 1) - (setq ledger-year (read-string "Year: " (ledger-current-year))) - (setq ledger-year (number-to-string newyear)))) + (setq ledger-year + (if (= newyear 1) + (read-string "Year: " (ledger-current-year)) + (number-to-string newyear)))) (defun ledger-set-month (newmonth) "Set ledger's idea of the current month to the prefix argument NEWMONTH." (interactive "p") - (if (= newmonth 1) - (setq ledger-month (read-string "Month: " (ledger-current-month))) - (setq ledger-month (format "%02d" newmonth)))) + (setq ledger-month + (if (= newmonth 1) + (read-string "Month: " (ledger-current-month)) + (format "%02d" newmonth)))) -(provide 'ledger) +(provide 'ledger-mode) ;;; ledger-mode.el ends here diff --git a/lisp/ledger-occur.el b/lisp/ledger-occur.el index 33d3a56c..24ded4ca 100644 --- a/lisp/ledger-occur.el +++ b/lisp/ledger-occur.el @@ -1,6 +1,6 @@ ;;; ledger-mode.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: ;; Provide buffer narrowing to ledger mode. Adapted from original loccur @@ -39,7 +39,7 @@ (defvar ledger-occur-mode nil - "name of the minor mode, shown in the mode-line") + "name of the minor mode, shown in the mode-line") (make-variable-buffer-local 'ledger-occur-mode) @@ -65,19 +65,19 @@ When REGEX is nil, unhide everything, and remove higlight" (set-buffer buffer) (setq ledger-occur-mode - (if (or (null regex) - (zerop (length regex))) - nil - (concat " Ledger-Narrowed: " regex))) + (if (or (null regex) + (zerop (length regex))) + nil + (concat " Ledger-Narrowed: " regex))) (force-mode-line-update) (ledger-occur-remove-overlays) (when ledger-occur-mode - (ledger-occur-create-overlays - (ledger-occur-compress-matches - (ledger-occur-find-matches regex))) - (setq ledger-occur-last-match regex) - (if (get-buffer-window buffer) - (select-window (get-buffer-window buffer)))) + (ledger-occur-create-overlays + (ledger-occur-compress-matches + (ledger-occur-find-matches regex))) + (setq ledger-occur-last-match regex) + (if (get-buffer-window buffer) + (select-window (get-buffer-window buffer)))) (recenter)) (defun ledger-occur (regex) @@ -90,7 +90,7 @@ When REGEX is nil, unhide everything, and remove higlight" (if ledger-occur-mode (list nil) (list (read-string (concat "Regexp<" (ledger-occur-prompt) ">: ") - nil 'ledger-occur-history (ledger-occur-prompt))))) + nil 'ledger-occur-history (ledger-occur-prompt))))) (ledger-occur-mode regex (current-buffer))) (defun ledger-occur-prompt () @@ -108,32 +108,32 @@ When REGEX is nil, unhide everything, and remove higlight" (if (= (line-number-at-pos pos1) (line-number-at-pos pos2)) (buffer-substring-no-properties pos1 pos2))) - (current-word)))) + (current-word)))) prompt)) (defun ledger-occur-make-visible-overlay (beg end) - (let ((ovl (make-overlay beg end (current-buffer)))) - (overlay-put ovl ledger-occur-overlay-property-name t) - (overlay-put ovl 'face 'ledger-occur-xact-face))) + (let ((ovl (make-overlay beg end (current-buffer)))) + (overlay-put ovl ledger-occur-overlay-property-name t) + (overlay-put ovl 'face 'ledger-occur-xact-face))) (defun ledger-occur-make-invisible-overlay (beg end) - (let ((ovl (make-overlay beg end (current-buffer)))) - (overlay-put ovl ledger-occur-overlay-property-name t) - (overlay-put ovl 'invisible t))) + (let ((ovl (make-overlay beg end (current-buffer)))) + (overlay-put ovl ledger-occur-overlay-property-name t) + (overlay-put ovl 'invisible t))) (defun ledger-occur-create-overlays (ovl-bounds) "Create the overlays for the visible transactions. Argument OVL-BOUNDS contains bounds for the transactions to be left visible." - (let* ((beg (caar ovl-bounds)) - (end (cadar ovl-bounds))) - (ledger-occur-make-invisible-overlay (point-min) (1- beg)) - (dolist (visible (cdr ovl-bounds)) - (ledger-occur-make-visible-overlay beg end) - (ledger-occur-make-invisible-overlay (1+ end) (1- (car visible))) - (setq beg (car visible)) - (setq end (cadr visible))) - (ledger-occur-make-invisible-overlay (1+ end) (point-max)))) + (let* ((beg (caar ovl-bounds)) + (end (cadar ovl-bounds))) + (ledger-occur-make-invisible-overlay (point-min) (1- beg)) + (dolist (visible (cdr ovl-bounds)) + (ledger-occur-make-visible-overlay beg end) + (ledger-occur-make-invisible-overlay (1+ end) (1- (car visible))) + (setq beg (car visible)) + (setq end (cadr visible))) + (ledger-occur-make-invisible-overlay (1+ end) (point-max)))) (defun ledger-occur-quit-buffer (buffer) "Quits hidings transaction in the given BUFFER. @@ -148,7 +148,7 @@ Used for coordinating `ledger-occur' with other buffers, like reconcile." "Remove the transaction hiding overlays." (interactive) (remove-overlays (point-min) - (point-max) ledger-occur-overlay-property-name t) + (point-max) ledger-occur-overlay-property-name t) (setq ledger-occur-overlay-list nil)) (defun ledger-occur-find-matches (regex) @@ -157,35 +157,35 @@ Used for coordinating `ledger-occur' with other buffers, like reconcile." (goto-char (point-min)) ;; Set initial values for variables (let (curpoint - endpoint - (lines (list))) + endpoint + (lines (list))) ;; Search loop (while (not (eobp)) (setq curpoint (point)) ;; if something found (when (setq endpoint (re-search-forward regex nil 'end)) (save-excursion - (let ((bounds (ledger-find-xact-extents (match-beginning 0)))) - (push bounds lines) - (setq curpoint (cadr bounds)))) ;; move to the end of - ;; the xact, no need to - ;; search inside it more + (let ((bounds (ledger-find-xact-extents (match-beginning 0)))) + (push bounds lines) + (setq curpoint (cadr bounds)))) ;; move to the end of + ;; the xact, no need to + ;; search inside it more (goto-char curpoint)) (forward-line 1)) (setq lines (nreverse lines))))) (defun ledger-occur-compress-matches (buffer-matches) - "identify sequential xacts to reduce number of overlays required" - (let ((points (list)) - (current-beginning (caar buffer-matches)) - (current-end (cadar buffer-matches))) - (dolist (match (cdr buffer-matches)) - (if (< (- (car match) current-end) 2) - (setq current-end (cadr match)) - (push (list current-beginning current-end) points) - (setq current-beginning (car match)) - (setq current-end (cadr match)))) - (nreverse (push (list current-beginning current-end) points)))) + "identify sequential xacts to reduce number of overlays required" + (let ((points (list)) + (current-beginning (caar buffer-matches)) + (current-end (cadar buffer-matches))) + (dolist (match (cdr buffer-matches)) + (if (< (- (car match) current-end) 2) + (setq current-end (cadr match)) + (push (list current-beginning current-end) points) + (setq current-beginning (car match)) + (setq current-end (cadr match)))) + (nreverse (push (list current-beginning current-end) points)))) (provide 'ledger-occur) diff --git a/lisp/ledger-post.el b/lisp/ledger-post.el index 5d30e954..b8fa36ca 100644 --- a/lisp/ledger-post.el +++ b/lisp/ledger-post.el @@ -1,6 +1,6 @@ ;;; ledger-post.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: @@ -44,10 +44,10 @@ (defcustom ledger-post-use-completion-engine :built-in "Which completion engine to use, :iswitchb or :ido chose those engines, :built-in uses built-in Ledger-mode completion" - :type '(radio (const :tag "built in completion" :built-in) + :type '(radio (const :tag "built in completion" :built-in) (const :tag "ido completion" :ido) (const :tag "iswitchb completion" :iswitchb) ) - :group 'ledger-post) + :group 'ledger-post) (defun ledger-post-all-accounts () "Return a list of all accounts in the buffer." @@ -129,8 +129,8 @@ point at beginning of the commodity." "Move point to the beginning of the next account, or status marker (!*), as long as it is not past END. Return the column of the beginning of the account and leave point at beginning of account" - (if (> end (point)) - (when (re-search-forward ledger-account-any-status-regex (1+ end) t) + (if (> end (point)) + (when (re-search-forward ledger-account-any-status-regex (1+ end) t) ;; the 1+ is to make sure we can catch the newline (if (match-beginning 1) (goto-char (match-beginning 1)) @@ -138,9 +138,9 @@ at beginning of account" (current-column)))) (defun ledger-post-align-xact (pos) - (interactive "d") - (let ((bounds (ledger-find-xact-extents pos))) - (ledger-post-align-postings (car bounds) (cadr bounds)))) + (interactive "d") + (let ((bounds (ledger-find-xact-extents pos))) + (ledger-post-align-postings (car bounds) (cadr bounds)))) (defun ledger-post-align-postings (&optional beg end) "Align all accounts and amounts within region, if there is no @@ -209,11 +209,11 @@ region align the posting on the current line." (let ((end-of-amount (re-search-forward "[-.,0-9]+" (line-end-position) t))) ;; determine if there is an amount to edit (if end-of-amount - (let ((val (ledger-string-to-number (match-string 0)))) + (let ((val-string (match-string 0))) (goto-char (match-beginning 0)) (delete-region (match-beginning 0) (match-end 0)) (calc) - (calc-eval val 'push)) ;; edit the amount + (calc-eval val-string 'push)) ;; edit the amount (progn ;;make sure there are two spaces after the account name and go to calc (if (search-backward " " (- (point) 3) t) (goto-char (line-end-position)) diff --git a/lisp/ledger-reconcile.el b/lisp/ledger-reconcile.el index 4725c6e4..bdd530d2 100644 --- a/lisp/ledger-reconcile.el +++ b/lisp/ledger-reconcile.el @@ -1,6 +1,6 @@ ;;; ledger-reconcile.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;; Reconcile mode @@ -27,13 +27,16 @@ ;;; Code: +(require 'easymenu) +(require 'ledger-init) + (defvar ledger-buf nil) (defvar ledger-bufs nil) (defvar ledger-acct nil) (defvar ledger-target nil) (defgroup ledger-reconcile nil - "Options for Ledger-mode reconciliation" + "Options for Ledger-mode reconciliation" :group 'ledger) (defcustom ledger-recon-buffer-name "*Reconcile*" @@ -59,10 +62,10 @@ Then that transaction will be shown in its source buffer." (defcustom ledger-reconcile-toggle-to-pending t "If true then toggle between uncleared and pending. reconcile-finish will mark all pending posting cleared." - :type 'boolean - :group 'ledger-reconcile) + :type 'boolean + :group 'ledger-reconcile) -(defcustom ledger-reconcile-default-date-format "%Y/%m/%d" +(defcustom ledger-reconcile-default-date-format ledger-default-date-format "Default date format for the reconcile buffer" :type 'string :group 'ledger-reconcile) @@ -72,8 +75,15 @@ reconcile-finish will mark all pending posting cleared." :type 'string :group 'ledger-reconcile) -(defvar ledger-reconcile-sort-key "(date)" - "Default key for sorting reconcile buffer") +(defcustom ledger-reconcile-sort-key "(date)" + "Default key for sorting reconcile buffer. For no sorting by default, use '(0)'." + :type 'string + :group 'ledger-reconcile) + +(defcustom ledger-reconcile-insert-effective-date nil + "If t, prompt for effective date when clearing transactions during reconciliation." + :type 'boolean + :group 'ledger-reconcile) (defun ledger-reconcile-get-cleared-or-pending-balance (buffer account) "Calculate the cleared or pending balance of the account." @@ -87,10 +97,10 @@ reconcile-finish will mark all pending posting cleared." ;; split arguments like the shell does, so you need to ;; specify the individual fields in the command line. (if (ledger-exec-ledger buffer (current-buffer) - "balance" "--limit" "cleared or pending" "--empty" "--collapse" - "--format" "%(display_total)" account) - (ledger-split-commodity-string - (buffer-substring-no-properties (point-min) (point-max)))))) + "balance" "--limit" "cleared or pending" "--empty" "--collapse" + "--format" "%(display_total)" account) + (ledger-split-commodity-string + (buffer-substring-no-properties (point-min) (point-max)))))) (defun ledger-display-balance () "Display the cleared-or-pending balance. @@ -98,14 +108,14 @@ And calculate the target-delta of the account being reconciled." (interactive) (let* ((pending (ledger-reconcile-get-cleared-or-pending-balance ledger-buf ledger-acct))) (when pending - (if ledger-target - (message "Pending balance: %s, Difference from target: %s" - (ledger-commodity-to-string pending) - (ledger-commodity-to-string (-commodity ledger-target pending))) - (message "Pending balance: %s" - (ledger-commodity-to-string pending)))))) - -(defun is-stdin (file) + (if ledger-target + (message "Pending balance: %s, Difference from target: %s" + (ledger-commodity-to-string pending) + (ledger-commodity-to-string (-commodity ledger-target pending))) + (message "Pending balance: %s" + (ledger-commodity-to-string pending)))))) + +(defun ledger-is-stdin (file) "True if ledger FILE is standard input." (or (equal file "") @@ -127,27 +137,30 @@ And calculate the target-delta of the account being reconciled." status) (when (ledger-reconcile-get-buffer where) (with-current-buffer (ledger-reconcile-get-buffer where) - (ledger-goto-line (cdr where)) - (forward-char) - (setq status (ledger-toggle-current (if ledger-reconcile-toggle-to-pending - 'pending - 'cleared)))) - ;; remove the existing face and add the new face + (ledger-goto-line (cdr where)) + (forward-char) + (setq status (ledger-toggle-current (if ledger-reconcile-toggle-to-pending + 'pending + 'cleared))) + (when ledger-reconcile-insert-effective-date + ;; Ask for effective date & insert it + (ledger-insert-effective-date))) + ;; remove the existing face and add the new face (remove-text-properties (line-beginning-position) - (line-end-position) - (list 'face)) + (line-end-position) + (list 'face)) (cond ((eq status 'pending) - (add-text-properties (line-beginning-position) - (line-end-position) - (list 'face 'ledger-font-reconciler-pending-face ))) - ((eq status 'cleared) - (add-text-properties (line-beginning-position) - (line-end-position) - (list 'face 'ledger-font-reconciler-cleared-face ))) - (t - (add-text-properties (line-beginning-position) - (line-end-position) - (list 'face 'ledger-font-reconciler-uncleared-face ))))) + (add-text-properties (line-beginning-position) + (line-end-position) + (list 'face 'ledger-font-reconciler-pending-face ))) + ((eq status 'cleared) + (add-text-properties (line-beginning-position) + (line-end-position) + (list 'face 'ledger-font-reconciler-cleared-face ))) + (t + (add-text-properties (line-beginning-position) + (line-end-position) + (list 'face 'ledger-font-reconciler-uncleared-face ))))) (forward-line) (beginning-of-line) (ledger-display-balance))) @@ -159,18 +172,18 @@ Return the number of uncleared xacts found." (let ((inhibit-read-only t)) (erase-buffer) (prog1 - (ledger-do-reconcile ledger-reconcile-sort-key) + (ledger-do-reconcile ledger-reconcile-sort-key) (set-buffer-modified-p t)))) (defun ledger-reconcile-refresh-after-save () "Refresh the recon-window after the ledger buffer is saved." (let ((curbuf (current-buffer)) - (curpoint (point)) - (recon-buf (get-buffer ledger-recon-buffer-name))) + (curpoint (point)) + (recon-buf (get-buffer ledger-recon-buffer-name))) (when (buffer-live-p recon-buf) (with-current-buffer recon-buf - (ledger-reconcile-refresh) - (set-buffer-modified-p nil)) + (ledger-reconcile-refresh) + (set-buffer-modified-p nil)) (select-window (get-buffer-window curbuf)) (goto-char curpoint)))) @@ -188,7 +201,7 @@ Return the number of uncleared xacts found." (when (ledger-reconcile-get-buffer where) (with-current-buffer (ledger-reconcile-get-buffer where) (ledger-goto-line (cdr where)) - (ledger-delete-current-transaction)) + (ledger-delete-current-transaction (point))) (let ((inhibit-read-only t)) (goto-char (line-beginning-position)) (delete-region (point) (1+ (line-end-position))) @@ -200,19 +213,19 @@ Return the number of uncleared xacts found." (progn (beginning-of-line) (let* ((where (get-text-property (1+ (point)) 'where)) - (target-buffer (if where - (ledger-reconcile-get-buffer where) - nil)) - (cur-win (get-buffer-window (get-buffer ledger-recon-buffer-name)))) + (target-buffer (if where + (ledger-reconcile-get-buffer where) + nil)) + (cur-win (get-buffer-window (get-buffer ledger-recon-buffer-name)))) (when target-buffer - (switch-to-buffer-other-window target-buffer) - (ledger-goto-line (cdr where)) - (forward-char) - (recenter) - (ledger-highlight-xact-under-point) - (forward-char -1) - (if (and come-back cur-win) - (select-window cur-win)))))) + (switch-to-buffer-other-window target-buffer) + (ledger-goto-line (cdr where)) + (forward-char) + (recenter) + (ledger-highlight-xact-under-point) + (forward-char -1) + (if (and come-back cur-win) + (select-window cur-win)))))) (defun ledger-reconcile-save () "Save the ledger buffer." @@ -220,7 +233,7 @@ Return the number of uncleared xacts found." (let ((curpoint (point))) (dolist (buf (cons ledger-buf ledger-bufs)) (with-current-buffer buf - (save-buffer))) + (save-buffer))) (with-current-buffer (get-buffer ledger-recon-buffer-name) (set-buffer-modified-p nil) (ledger-display-balance) @@ -243,94 +256,93 @@ and exit reconcile mode" (ledger-toggle-current 'cleared)))) (forward-line 1))) (ledger-reconcile-save) - (ledger-reconcile-quit)) + (ledger-reconcile-quit)) (defun ledger-reconcile-quit () "Quit the reconcile window without saving ledger buffer." (interactive) (let ((recon-buf (get-buffer ledger-recon-buffer-name)) - buf) + buf) (if recon-buf - (with-current-buffer recon-buf - (ledger-reconcile-quit-cleanup) - (setq buf ledger-buf) - ;; Make sure you delete the window before you delete the buffer, - ;; otherwise, madness ensues - (delete-window (get-buffer-window recon-buf)) - (kill-buffer recon-buf) - (set-window-buffer (selected-window) buf))))) + (with-current-buffer recon-buf + (ledger-reconcile-quit-cleanup) + (setq buf ledger-buf) + ;; Make sure you delete the window before you delete the buffer, + ;; otherwise, madness ensues + (delete-window (get-buffer-window recon-buf)) + (kill-buffer recon-buf) + (set-window-buffer (selected-window) buf))))) (defun ledger-reconcile-quit-cleanup () "Cleanup all hooks established by reconcile mode." (interactive) (let ((buf ledger-buf)) (if (buffer-live-p buf) - (with-current-buffer buf - (remove-hook 'after-save-hook 'ledger-reconcile-refresh-after-save t) - (when ledger-narrow-on-reconcile - (ledger-occur-quit-buffer buf) - (ledger-highlight-xact-under-point)))))) + (with-current-buffer buf + (remove-hook 'after-save-hook 'ledger-reconcile-refresh-after-save t) + (when ledger-narrow-on-reconcile + (ledger-occur-quit-buffer buf) + (ledger-highlight-xact-under-point)))))) (defun ledger-marker-where-xact-is (emacs-xact posting) "Find the position of the EMACS-XACT in the `ledger-buf'. POSTING is used in `ledger-clear-whole-transactions' is nil." - (let ((buf (if (is-stdin (nth 0 emacs-xact)) - ledger-buf - (find-file-noselect (nth 0 emacs-xact))))) + (let ((buf (if (ledger-is-stdin (nth 0 emacs-xact)) + ledger-buf + (find-file-noselect (nth 0 emacs-xact))))) (cons buf (if ledger-clear-whole-transactions - (nth 1 emacs-xact) ;; return line-no of xact - (nth 0 posting))))) ;; return line-no of posting + (nth 1 emacs-xact) ;; return line-no of xact + (nth 0 posting))))) ;; return line-no of posting (defun ledger-do-reconcile (&optional sort) "Return the number of uncleared transactions in the account and display them in the *Reconcile* buffer." (let* ((buf ledger-buf) (account ledger-acct) - (ledger-success nil) - (sort-by (if sort - sort - "(date)")) + (ledger-success nil) + (sort-by (if sort + sort + "(date)")) (xacts (with-temp-buffer - (when (ledger-exec-ledger buf (current-buffer) - "--uncleared" "--real" "emacs" "--sort" sort-by account) - (setq ledger-success t) - (goto-char (point-min)) - (unless (eobp) - (if (looking-at "(") - (read (current-buffer)))))))) ;current-buffer is the *temp* created above + (when (ledger-exec-ledger buf (current-buffer) + "--uncleared" "--real" "emacs" "--sort" sort-by account) + (setq ledger-success t) + (goto-char (point-min)) + (unless (eobp) + (if (looking-at "(") + (read (current-buffer)))))))) ;current-buffer is the *temp* created above (if (and ledger-success (> (length xacts) 0)) - (let ((date-format (cdr (assoc "date-format" ledger-environment-alist)))) - (dolist (xact xacts) - (dolist (posting (nthcdr 5 xact)) - (let ((beg (point)) - (where (ledger-marker-where-xact-is xact posting))) - (insert (format "%s %-4s %-30s %-30s %15s\n" - (format-time-string (if date-format - date-format - ledger-reconcile-default-date-format) (nth 2 xact)) - (if (nth 3 xact) - (nth 3 xact) - "") - (nth 4 xact) (nth 1 posting) (nth 2 posting))) - (if (nth 3 posting) - (if (eq (nth 3 posting) 'pending) - (set-text-properties beg (1- (point)) - (list 'face 'ledger-font-reconciler-pending-face - 'where where)) - (set-text-properties beg (1- (point)) - (list 'face 'ledger-font-reconciler-cleared-face - 'where where))) - (set-text-properties beg (1- (point)) - (list 'face 'ledger-font-reconciler-uncleared-face - 'where where)))) )) - (goto-char (point-max)) - (delete-char -1)) ;gets rid of the extra line feed at the bottom of the list - (if ledger-success - (insert (concat "There are no uncleared entries for " account)) - (insert "Ledger has reported a problem. Check *Ledger Error* buffer."))) + (let ((date-format (or (cdr (assoc "date-format" ledger-environment-alist)) + ledger-default-date-format))) + (dolist (xact xacts) + (dolist (posting (nthcdr 5 xact)) + (let ((beg (point)) + (where (ledger-marker-where-xact-is xact posting))) + (insert (format "%s %-4s %-30s %-30s %15s\n" + (format-time-string date-format (nth 2 xact)) + (if (nth 3 xact) + (nth 3 xact) + "") + (nth 4 xact) (nth 1 posting) (nth 2 posting))) + (if (nth 3 posting) + (if (eq (nth 3 posting) 'pending) + (set-text-properties beg (1- (point)) + (list 'face 'ledger-font-reconciler-pending-face + 'where where)) + (set-text-properties beg (1- (point)) + (list 'face 'ledger-font-reconciler-cleared-face + 'where where))) + (set-text-properties beg (1- (point)) + (list 'face 'ledger-font-reconciler-uncleared-face + 'where where)))) )) + (goto-char (point-max)) + (delete-char -1)) ;gets rid of the extra line feed at the bottom of the list + (if ledger-success + (insert (concat "There are no uncleared entries for " account)) + (insert "Ledger has reported a problem. Check *Ledger Error* buffer."))) (goto-char (point-min)) (set-buffer-modified-p nil) (toggle-read-only t) @@ -344,30 +356,30 @@ ledger buffer is at the bottom of the main window. The key to this is to ensure the window is selected when the buffer point is moved and recentered. If they aren't strange things happen." - (let ((recon-window (get-buffer-window (get-buffer ledger-recon-buffer-name)))) - (when recon-window - (fit-window-to-buffer recon-window) - (with-current-buffer buf - (add-hook 'kill-buffer-hook 'ledger-reconcile-quit nil t) - (if (get-buffer-window buf) - (select-window (get-buffer-window buf))) - (goto-char (point-max)) - (recenter -1)) - (select-window recon-window) - (ledger-reconcile-visit t)) - (add-hook 'post-command-hook 'ledger-reconcile-track-xact nil t))) + (let ((recon-window (get-buffer-window (get-buffer ledger-recon-buffer-name)))) + (when recon-window + (fit-window-to-buffer recon-window) + (with-current-buffer buf + (add-hook 'kill-buffer-hook 'ledger-reconcile-quit nil t) + (if (get-buffer-window buf) + (select-window (get-buffer-window buf))) + (goto-char (point-max)) + (recenter -1)) + (select-window recon-window) + (ledger-reconcile-visit t)) + (add-hook 'post-command-hook 'ledger-reconcile-track-xact nil t))) (defun ledger-reconcile-track-xact () "Force the ledger buffer to recenter on the transaction at point in the reconcile buffer." (if (and ledger-buffer-tracks-reconcile-buffer - (member this-command (list 'next-line - 'previous-line - 'mouse-set-point - 'ledger-reconcile-toggle - 'end-of-buffer - 'beginning-of-buffer))) + (member this-command (list 'next-line + 'previous-line + 'mouse-set-point + 'ledger-reconcile-toggle + 'end-of-buffer + 'beginning-of-buffer))) (save-excursion - (ledger-reconcile-visit t)))) + (ledger-reconcile-visit t)))) (defun ledger-reconcile-open-windows (buf rbuf) "Ensure that the ledger buffer BUF is split by RBUF." @@ -380,39 +392,39 @@ moved and recentered. If they aren't strange things happen." "Start reconciling, prompt for account." (interactive) (let ((account (ledger-read-account-with-prompt "Account to reconcile")) - (buf (current-buffer)) + (buf (current-buffer)) (rbuf (get-buffer ledger-recon-buffer-name))) - (add-hook 'after-save-hook 'ledger-reconcile-refresh-after-save nil t) + (add-hook 'after-save-hook 'ledger-reconcile-refresh-after-save nil t) (if rbuf ;; *Reconcile* already exists - (with-current-buffer rbuf - (set 'ledger-acct account) ;; already buffer local - (when (not (eq buf rbuf)) - ;; called from some other ledger-mode buffer - (ledger-reconcile-quit-cleanup) - (set 'ledger-buf buf)) ;; should already be buffer-local - - (unless (get-buffer-window rbuf) - (ledger-reconcile-open-windows buf rbuf))) - - ;; no recon-buffer, starting from scratch. - - (with-current-buffer (setq rbuf - (get-buffer-create ledger-recon-buffer-name)) - (ledger-reconcile-open-windows buf rbuf) - (ledger-reconcile-mode) - (make-local-variable 'ledger-target) - (set (make-local-variable 'ledger-buf) buf) - (set (make-local-variable 'ledger-acct) account))) + (with-current-buffer rbuf + (set 'ledger-acct account) ;; already buffer local + (when (not (eq buf rbuf)) + ;; called from some other ledger-mode buffer + (ledger-reconcile-quit-cleanup) + (set 'ledger-buf buf)) ;; should already be buffer-local + + (unless (get-buffer-window rbuf) + (ledger-reconcile-open-windows buf rbuf))) + + ;; no recon-buffer, starting from scratch. + + (with-current-buffer (setq rbuf + (get-buffer-create ledger-recon-buffer-name)) + (ledger-reconcile-open-windows buf rbuf) + (ledger-reconcile-mode) + (make-local-variable 'ledger-target) + (set (make-local-variable 'ledger-buf) buf) + (set (make-local-variable 'ledger-acct) account))) ;; Narrow the ledger buffer (with-current-buffer rbuf (save-excursion - (if ledger-narrow-on-reconcile - (ledger-occur-mode account ledger-buf))) + (if ledger-narrow-on-reconcile + (ledger-occur-mode account ledger-buf))) (if (> (ledger-reconcile-refresh) 0) - (ledger-reconcile-change-target)) + (ledger-reconcile-change-target)) (ledger-display-balance)))) (defvar ledger-reconcile-mode-abbrev-table) @@ -423,14 +435,13 @@ moved and recentered. If they aren't strange things happen." (setq ledger-target (ledger-read-commodity-string ledger-reconcile-target-prompt-string))) (defmacro ledger-reconcile-change-sort-key-and-refresh (sort-by) - `(lambda () - (interactive) + `(lambda () + (interactive) - (setq ledger-reconcile-sort-key ,sort-by) - (ledger-reconcile-refresh))) + (setq ledger-reconcile-sort-key ,sort-by) + (ledger-reconcile-refresh))) -(define-derived-mode ledger-reconcile-mode text-mode "Reconcile" - "A mode for reconciling ledger entries." +(defvar ledger-reconcile-mode-map (let ((map (make-sparse-keymap))) (define-key map [(control ?m)] 'ledger-reconcile-visit) (define-key map [return] 'ledger-reconcile-visit) @@ -447,38 +458,46 @@ moved and recentered. If they aren't strange things happen." (define-key map [?q] 'ledger-reconcile-quit) (define-key map [?b] 'ledger-display-balance) + (define-key map [(control ?c) (control ?o)] (ledger-reconcile-change-sort-key-and-refresh "(0)")) + (define-key map [(control ?c) (control ?a)] (ledger-reconcile-change-sort-key-and-refresh "(amount)")) (define-key map [(control ?c) (control ?d)] (ledger-reconcile-change-sort-key-and-refresh "(date)")) (define-key map [(control ?c) (control ?p)] (ledger-reconcile-change-sort-key-and-refresh "(payee)")) + map) + "Keymap for `ledger-reconcile-mode'.") + +(easy-menu-define ledger-reconcile-mode-menu ledger-reconcile-mode-map + "Ledger reconcile menu" + `("Reconcile" + ["Save" ledger-reconcile-save] + ["Refresh" ledger-reconcile-refresh] + ["Finish" ledger-reconcile-finish] + "---" + ["Reconcile New Account" ledger-reconcile] + "---" + ["Change Target Balance" ledger-reconcile-change-target] + ["Show Cleared Balance" ledger-display-balance] + "---" + ["Sort by payee" ,(ledger-reconcile-change-sort-key-and-refresh "(payee)")] + ["Sort by date" ,(ledger-reconcile-change-sort-key-and-refresh "(date)")] + ["Sort by amount" ,(ledger-reconcile-change-sort-key-and-refresh "(amount)")] + ["Sort by file order" ,(ledger-reconcile-change-sort-key-and-refresh "(0)")] + "---" + ["Toggle Entry" ledger-reconcile-toggle] + ["Add Entry" ledger-reconcile-add] + ["Delete Entry" ledger-reconcile-delete] + "---" + ["Next Entry" next-line] + ["Visit Source" ledger-reconcile-visit] + ["Previous Entry" previous-line] + "---" + ["Quit" ledger-reconcile-quit] + )) - (define-key map [menu-bar] (make-sparse-keymap "ledger-recon-menu")) - (define-key map [menu-bar ledger-recon-menu] (cons "Reconcile" map)) - (define-key map [menu-bar ledger-recon-menu qui] '("Quit" . ledger-reconcile-quit)) - (define-key map [menu-bar ledger-recon-menu sep1] '("--")) - (define-key map [menu-bar ledger-recon-menu pre] '("Previous Entry" . previous-line)) - (define-key map [menu-bar ledger-recon-menu vis] '("Visit Source" . ledger-reconcile-visit)) - (define-key map [menu-bar ledger-recon-menu nex] '("Next Entry" . next-line)) - (define-key map [menu-bar ledger-recon-menu sep2] '("--")) - (define-key map [menu-bar ledger-recon-menu del] '("Delete Entry" . ledger-reconcile-delete)) - (define-key map [menu-bar ledger-recon-menu add] '("Add Entry" . ledger-reconcile-add)) - (define-key map [menu-bar ledger-recon-menu tog] '("Toggle Entry" . ledger-reconcile-toggle)) - (define-key map [menu-bar ledger-recon-menu sep3] '("--")) - (define-key map [menu-bar ledger-recon-menu sort-amt] `("Sort by amount" . ,(ledger-reconcile-change-sort-key-and-refresh "(amount)"))) - (define-key map [menu-bar ledger-recon-menu sort-pay] `("Sort by date" . ,(ledger-reconcile-change-sort-key-and-refresh "(date)"))) - (define-key map [menu-bar ledger-recon-menu sort-dat] `("Sort by payee" . ,(ledger-reconcile-change-sort-key-and-refresh "(payee)"))) - (define-key map [menu-bar ledger-recon-menu sep4] '("--")) - (define-key map [menu-bar ledger-recon-menu bal] '("Show Cleared Balance" . ledger-display-balance)) - (define-key map [menu-bar ledger-recon-menu tgt] '("Change Target Balance" . ledger-reconcile-change-target)) - (define-key map [menu-bar ledger-recon-menu sep5] '("--")) - (define-key map [menu-bar ledger-recon-menu rna] '("Reconcile New Account" . ledger-reconcile)) - (define-key map [menu-bar ledger-recon-menu sep6] '("--")) - (define-key map [menu-bar ledger-recon-menu fin] '("Finish" . ledger-reconcile-finish)) - (define-key map [menu-bar ledger-recon-menu ref] '("Refresh" . ledger-reconcile-refresh)) - (define-key map [menu-bar ledger-recon-menu sav] '("Save" . ledger-reconcile-save)) - - (use-local-map map))) +(define-derived-mode ledger-reconcile-mode text-mode "Reconcile" + "A mode for reconciling ledger entries.") (provide 'ledger-reconcile) diff --git a/lisp/ledger-regex.el b/lisp/ledger-regex.el index 77ce38c6..8d838892 100644 --- a/lisp/ledger-regex.el +++ b/lisp/ledger-regex.el @@ -1,6 +1,6 @@ ;;; ledger-regex.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. (require 'rx) @@ -27,7 +27,7 @@ (defconst ledger-amount-regex (concat "\\( \\|\t\\| \t\\)[ \t]*-?" "\\([A-Z$€£_]+ *\\)?" - "\\(-?[0-9,]+?\\)" + "\\(-?[0-9,\\.]+?\\)" "\\(.[0-9]+\\)?" "\\( *[[:word:]€£_\"]+\\)?" "\\([ \t]*[@={]@?[^\n;]+?\\)?" @@ -68,10 +68,10 @@ "^--.+?\\($\\|[ ]\\)") (defconst ledger-account-any-status-regex - "^[ \t]+\\([*!]\\s-+\\)?\\([[(]?.+?\\)\\(\t\\|\n\\| [ \t]\\)") + "^[ \t]+\\([*!]\\s-+\\)?\\([[(]?.+?\\)\\(\t\\|\n\\| [ \t]\\)") (defun ledger-account-any-status-with-seed-regex (seed) - (concat "^[ \t]+\\([*!]\\s-+\\)?\\([[(]?" seed ".+?\\)\\(\t\\|\n\\| [ \t]\\)")) + (concat "^[ \t]+\\([*!]\\s-+\\)?\\([[(]?" seed ".+?\\)\\(\t\\|\n\\| [ \t]\\)")) (defconst ledger-account-pending-regex "\\(^[ \t]+\\)\\(!\\s-*.*?\\)\\( \\|\t\\|$\\)") diff --git a/lisp/ledger-report.el b/lisp/ledger-report.el index e785bc1b..af9ae62c 100644 --- a/lisp/ledger-report.el +++ b/lisp/ledger-report.el @@ -1,6 +1,6 @@ ;;; ledger-report.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: @@ -25,6 +25,7 @@ ;;; Code: +(require 'easymenu) (eval-when-compile (require 'cl)) @@ -84,45 +85,48 @@ text that should replace the format specifier." (setq inhibit-read-only t) (reverse-region (point) (point-max)))) +(defvar ledger-report-mode-map + (let ((map (make-sparse-keymap))) + (define-key map [? ] 'scroll-up) + (define-key map [backspace] 'scroll-down) + (define-key map [?r] 'ledger-report-redo) + (define-key map [(shift ?r)] 'ledger-report-reverse-lines) + (define-key map [?s] 'ledger-report-save) + (define-key map [?k] 'ledger-report-kill) + (define-key map [?e] 'ledger-report-edit) + (define-key map [?q] 'ledger-report-quit) + (define-key map [?g] 'ledger-report-redo) + (define-key map [(control ?c) (control ?l) (control ?r)] + 'ledger-report-redo) + (define-key map [(control ?c) (control ?l) (control ?S)] + 'ledger-report-save) + (define-key map [(control ?c) (control ?l) (control ?k)] + 'ledger-report-kill) + (define-key map [(control ?c) (control ?l) (control ?e)] + 'ledger-report-edit) + (define-key map [return] 'ledger-report-visit-source) + map) + "Keymap for `ledger-report-mode'.") + +(easy-menu-define ledger-report-mode-menu ledger-report-mode-map + "Ledger report menu" + '("Reports" + ["Save Report" ledger-report-save] + ["Edit Report" ledger-report-edit] + ["Re-run Report" ledger-report-redo] + ["Kill Report" ledger-report-kill] + "---" + ["Reverse report order" ledger-report-reverse-lines] + "---" + ["Scroll Up" scroll-up] + ["Visit Source" ledger-report-visit-source] + ["Scroll Down" scroll-down] + "---" + ["Quit" ledger-report-quit] + )) + (define-derived-mode ledger-report-mode text-mode "Ledger-Report" - "A mode for viewing ledger reports." - (let ((map (make-sparse-keymap))) - (define-key map [? ] 'scroll-up) - (define-key map [backspace] 'scroll-down) - (define-key map [?r] 'ledger-report-redo) - (define-key map [(shift ?r)] 'ledger-report-reverse-lines) - (define-key map [?s] 'ledger-report-save) - (define-key map [?k] 'ledger-report-kill) - (define-key map [?e] 'ledger-report-edit) - (define-key map [?q] 'ledger-report-quit) - (define-key map [(control ?c) (control ?l) (control ?r)] - 'ledger-report-redo) - (define-key map [(control ?c) (control ?l) (control ?S)] - 'ledger-report-save) - (define-key map [(control ?c) (control ?l) (control ?k)] - 'ledger-report-kill) - (define-key map [(control ?c) (control ?l) (control ?e)] - 'ledger-report-edit) - (define-key map [return] 'ledger-report-visit-source) - - - (define-key map [menu-bar] (make-sparse-keymap "ledger-rep")) - (define-key map [menu-bar ledger-rep] (cons "Reports" map)) - - (define-key map [menu-bar ledger-rep lrq] '("Quit" . ledger-report-quit)) - (define-key map [menu-bar ledger-rep s2] '("--")) - (define-key map [menu-bar ledger-rep lrd] '("Scroll Down" . scroll-down)) - (define-key map [menu-bar ledger-rep vis] '("Visit Source" . ledger-report-visit-source)) - (define-key map [menu-bar ledger-rep lru] '("Scroll Up" . scroll-up)) - (define-key map [menu-bar ledger-rep s1] '("--")) - (define-key map [menu-bar ledger-rep rev] '("Reverse report order" . ledger-report-reverse-lines)) - (define-key map [menu-bar ledger-rep s0] '("--")) - (define-key map [menu-bar ledger-rep lrk] '("Kill Report" . ledger-report-kill)) - (define-key map [menu-bar ledger-rep lrr] '("Re-run Report" . ledger-report-redo)) - (define-key map [menu-bar ledger-rep lre] '("Edit Report" . ledger-report-edit)) - (define-key map [menu-bar ledger-rep lrs] '("Save Report" . ledger-report-save)) - - (use-local-map map))) + "A mode for viewing ledger reports.") (defun ledger-report-value-format-specifier () "Return a valid meta-data tag name" diff --git a/lisp/ledger-schedule.el b/lisp/ledger-schedule.el index 7497c7d0..e1e06d69 100644 --- a/lisp/ledger-schedule.el +++ b/lisp/ledger-schedule.el @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, -;; Boston, MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: ;; @@ -30,6 +30,8 @@ ;; function slot of the symbol VARNAME. Then use VARNAME as the ;; function without have to use funcall. +(require 'ledger-init) + (defgroup ledger-schedule nil "Support for automatically recommendation transactions." :group 'ledger) @@ -49,14 +51,20 @@ :type 'integer :group 'ledger-schedule) -(defcustom ledger-schedule-file "~/FinanceData/ledger-schedule.ledger" +(defcustom ledger-schedule-file "~/ledger-schedule.ledger" "File to find scheduled transactions." :type 'file :group 'ledger-schedule) +(defvar ledger-schedule-available nil) + (defsubst between (val low high) (and (>= val low) (<= val high))) +(defun ledger-schedule-check-available () + (setq ledger-schedule-available (and ledger-schedule-file + (file-exists-p ledger-schedule-file)))) + (defun ledger-schedule-days-in-month (month year) "Return number of days in the MONTH, MONTH is from 1 to 12. If year is nil, assume it is not a leap year" @@ -235,7 +243,7 @@ returns true if the date meets the requirements" ((/= 0 (setq year-match (string-to-number str))) `(eq (nth 5 (decode-time date)) ,year-match)) (t - (error "Improperly specified year constraint: " str))))) + (error "Improperly specified year constraint: %s" str))))) (defun ledger-schedule-constrain-month (str) @@ -247,7 +255,7 @@ returns true if the date meets the requirements" `(eq (nth 4 (decode-time date)) ,month-match) (error "ledger-schedule-constrain-numerical-month: month out of range %S" month-match))) (t - (error "Improperly specified month constraint: " str))))) + (error "Improperly specified month constraint: %s" str))))) (defun ledger-schedule-constrain-day (str) (let ((day-match t)) @@ -256,7 +264,7 @@ returns true if the date meets the requirements" ((/= 0 (setq day-match (string-to-number str))) `(eq (nth 3 (decode-time date)) ,day-match)) (t - (error "Improperly specified day constraint: " str))))) + (error "Improperly specified day constraint: %s" str))))) (defun ledger-schedule-parse-date-descriptor (descriptor) "Parse the date descriptor, return the evaluator" @@ -282,7 +290,8 @@ returns true if the date meets the requirements" "Format CANDIDATE-ITEMS for display." (let ((candidates (ledger-schedule-list-upcoming-xacts candidate-items early horizon)) (schedule-buf (get-buffer-create ledger-schedule-buffer-name)) - (date-format (cdr (assoc "date-format" ledger-environment-alist)))) + (date-format (or (cdr (assoc "date-format" ledger-environment-alist)) + ledger-default-date-format))) (with-current-buffer schedule-buf (erase-buffer) (dolist (candidate candidates) @@ -291,38 +300,28 @@ returns true if the date meets the requirements" (ledger-mode)) (length candidates))) - -;; -;; Test harnesses for use in ielm -;; -(defvar auto-items) - -(defun ledger-schedule-test ( early horizon) - (ledger-schedule-create-auto-buffer - (ledger-schedule-scan-transactions ledger-schedule-file) - early - horizon - (get-buffer "2013.ledger"))) - - -(defun ledger-schedule-test-predict () - (let ((today (current-time)) - test-date items) - - (loop for day from 0 to ledger-schedule-look-forward by 1 do - (setq test-date (time-add today (days-to-time day))) - (dolist (item auto-items items) - (if (funcall (car item) test-date) - (setq items (append items (list (decode-time test-date) (cdr item))))))) - items)) - -(defun ledger-schedule-upcoming () - (interactive) +(defun ledger-schedule-upcoming (file look-backward look-forward) + "Generate upcoming transaction + +FILE is the file containing the scheduled transaction, +default to `ledger-schedule-file'. +LOOK-BACKWARD is the number of day in the past to look at +default to `ledger-schedule-look-backward' +LOOK-FORWARD is the number of day in the futur to look at +default to `ledger-schedule-look-forward' + +Use a prefix arg to change the default value" + (interactive (if current-prefix-arg + (list (read-file-name "Schedule File: " () ledger-schedule-file t) + (read-number "Look backward: " ledger-schedule-look-backward) + (read-number "Look forward: " ledger-schedule-look-forward)) + (list ledger-schedule-file ledger-schedule-look-backward ledger-schedule-look-forward))) (ledger-schedule-create-auto-buffer - (ledger-schedule-scan-transactions ledger-schedule-file) - ledger-schedule-look-backward - ledger-schedule-look-forward - (current-buffer))) + (ledger-schedule-scan-transactions file) + look-backward + look-forward + (current-buffer)) + (pop-to-buffer ledger-schedule-buffer-name)) (provide 'ledger-schedule) diff --git a/lisp/ledger-sort.el b/lisp/ledger-sort.el index c5a41952..d337cc4c 100644 --- a/lisp/ledger-sort.el +++ b/lisp/ledger-sort.el @@ -1,6 +1,6 @@ ;;; ledger-xact.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. @@ -49,7 +49,7 @@ (save-excursion (goto-char (point-min)) (if (ledger-sort-find-start) - (delete-region (match-beginning 0) (match-end 0)))) + (delete-region (match-beginning 0) (match-end 0)))) (beginning-of-line) (insert "\n; Ledger-mode: Start sort\n\n")) @@ -58,7 +58,7 @@ (save-excursion (goto-char (point-min)) (if (ledger-sort-find-end) - (delete-region (match-beginning 0) (match-end 0)))) + (delete-region (match-beginning 0) (match-end 0)))) (beginning-of-line) (insert "\n; Ledger-mode: End sort\n\n")) @@ -69,57 +69,57 @@ (defun ledger-sort-region (beg end) "Sort the region from BEG to END in chronological order." (interactive "r") ;; load beg and end from point and mark - ;; automagically + ;; automagically (let ((new-beg beg) - (new-end end) - point-delta - (bounds (ledger-find-xact-extents (point))) - target-xact) - - (setq point-delta (- (point) (car bounds))) - (setq target-xact (buffer-substring (car bounds) (cadr bounds))) - (setq inhibit-modification-hooks t) + (new-end end) + point-delta + (bounds (ledger-find-xact-extents (point))) + target-xact) + + (setq point-delta (- (point) (car bounds))) + (setq target-xact (buffer-substring (car bounds) (cadr bounds))) + (setq inhibit-modification-hooks t) (save-excursion (save-restriction - (goto-char beg) - (ledger-next-record-function) ;; make sure point is at the - ;; beginning of a xact - (setq new-beg (point)) - (goto-char end) - (ledger-next-record-function) ;; make sure end of region is at - ;; the beginning of next record - ;; after the region - (setq new-end (point)) - (narrow-to-region new-beg new-end) - (goto-char new-beg) - - (let ((inhibit-field-text-motion t)) - (sort-subr - nil - 'ledger-next-record-function - 'ledger-end-record-function - 'ledger-sort-startkey)))) - - (goto-char (point-min)) - (re-search-forward (regexp-quote target-xact)) - (goto-char (+ (match-beginning 0) point-delta)) + (goto-char beg) + (ledger-next-record-function) ;; make sure point is at the + ;; beginning of a xact + (setq new-beg (point)) + (goto-char end) + (ledger-next-record-function) ;; make sure end of region is at + ;; the beginning of next record + ;; after the region + (setq new-end (point)) + (narrow-to-region new-beg new-end) + (goto-char new-beg) + + (let ((inhibit-field-text-motion t)) + (sort-subr + nil + 'ledger-next-record-function + 'ledger-end-record-function + 'ledger-sort-startkey)))) + + (goto-char (point-min)) + (re-search-forward (regexp-quote target-xact)) + (goto-char (+ (match-beginning 0) point-delta)) (setq inhibit-modification-hooks nil))) (defun ledger-sort-buffer () "Sort the entire buffer." (interactive) (let (sort-start - sort-end) - (save-excursion - (goto-char (point-min)) - (setq sort-start (ledger-sort-find-start) - sort-end (ledger-sort-find-end))) + sort-end) + (save-excursion + (goto-char (point-min)) + (setq sort-start (ledger-sort-find-start) + sort-end (ledger-sort-find-end))) (ledger-sort-region (if sort-start - sort-start - (point-min)) - (if sort-end - sort-end - (point-max))))) + sort-start + (point-min)) + (if sort-end + sort-end + (point-max))))) (provide 'ledger-sort) diff --git a/lisp/ledger-state.el b/lisp/ledger-state.el index 121e97ca..fffaab14 100644 --- a/lisp/ledger-state.el +++ b/lisp/ledger-state.el @@ -1,6 +1,6 @@ ;;; ledger-state.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: diff --git a/lisp/ledger-test.el b/lisp/ledger-test.el index a275ae7f..f74c5428 100644 --- a/lisp/ledger-test.el +++ b/lisp/ledger-test.el @@ -1,6 +1,6 @@ ;;; ledger-test.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. (defgroup ledger-test nil "Definitions for the Ledger testing framework" diff --git a/lisp/ledger-texi.el b/lisp/ledger-texi.el index 68880550..c9e438c0 100644 --- a/lisp/ledger-texi.el +++ b/lisp/ledger-texi.el @@ -1,6 +1,6 @@ ;;; ledger-texi.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. (defgroup ledger-texi nil "Options for working on Ledger texi documentation" diff --git a/lisp/ledger-xact.el b/lisp/ledger-xact.el index 25413e43..35b0d62c 100644 --- a/lisp/ledger-xact.el +++ b/lisp/ledger-xact.el @@ -1,6 +1,6 @@ ;;; ledger-xact.el --- Helper code for use with the "ledger" command-line tool -;; Copyright (C) 2003-2013 John Wiegley (johnw AT gnu DOT org) +;; Copyright (C) 2003-2014 John Wiegley (johnw AT gnu DOT org) ;; This file is not part of GNU Emacs. @@ -16,8 +16,8 @@ ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to the -;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -;; MA 02111-1307, USA. +;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +;; MA 02110-1301 USA. ;;; Commentary: @@ -36,7 +36,8 @@ :group 'ledger :safe t) -(defvar highlight-overlay (list)) +(defvar ledger-xact-highlight-overlay (list)) +(make-variable-buffer-local 'ledger-xact-highlight-overlay) (defun ledger-find-xact-extents (pos) "Return point for beginning of xact and and of xact containing position. @@ -46,28 +47,28 @@ within the transaction." (save-excursion (goto-char pos) (list (progn - (backward-paragraph) - (if (/= (point) (point-min)) - (forward-line)) - (line-beginning-position)) - (progn - (forward-paragraph) - (line-beginning-position))))) + (backward-paragraph) + (if (/= (point) (point-min)) + (forward-line)) + (line-beginning-position)) + (progn + (forward-paragraph) + (line-beginning-position))))) (defun ledger-highlight-xact-under-point () "Move the highlight overlay to the current transaction." (if ledger-highlight-xact-under-point (let ((exts (ledger-find-xact-extents (point))) - (ovl highlight-overlay)) - (if (not highlight-overlay) - (setq ovl - (setq highlight-overlay - (make-overlay (car exts) - (cadr exts) - (current-buffer) t nil))) - (move-overlay ovl (car exts) (cadr exts))) - (overlay-put ovl 'face 'ledger-font-xact-highlight-face) - (overlay-put ovl 'priority 100)))) + (ovl ledger-xact-highlight-overlay)) + (if (not ledger-xact-highlight-overlay) + (setq ovl + (setq ledger-xact-highlight-overlay + (make-overlay (car exts) + (cadr exts) + (current-buffer) t nil))) + (move-overlay ovl (car exts) (cadr exts))) + (overlay-put ovl 'face 'ledger-font-xact-highlight-face) + (overlay-put ovl 'priority 100)))) (defun ledger-xact-payee () "Return the payee of the transaction containing point or nil." @@ -77,7 +78,7 @@ within the transaction." (let ((context-info (ledger-context-other-line i))) (if (eq (ledger-context-line-type context-info) 'xact) (ledger-context-field-value context-info 'payee) - nil)))) + nil)))) (defun ledger-time-less-p (t1 t2) "Say whether time value T1 is less than time value T2." @@ -93,7 +94,7 @@ MOMENT is an encoded date" (function (lambda (start date mark desc) (if (ledger-time-less-p moment date) - (throw 'found t))))))) + (throw 'found t))))))) (defun ledger-xact-iterate-transactions (callback) "Iterate through each transaction call CALLBACK for each." @@ -105,19 +106,19 @@ MOMENT is an encoded date" (let ((found-y-p (match-string 2))) (if found-y-p (setq current-year (string-to-number found-y-p)) ;; a Y directive was found - (let ((start (match-beginning 0)) - (year (match-string 4)) - (month (string-to-number (match-string 5))) - (day (string-to-number (match-string 6))) - (mark (match-string 7)) - (code (match-string 8)) - (desc (match-string 9))) - (if (and year (> (length year) 0)) - (setq year (string-to-number year))) - (funcall callback start - (encode-time 0 0 0 day month - (or year current-year)) - mark desc))))) + (let ((start (match-beginning 0)) + (year (match-string 4)) + (month (string-to-number (match-string 5))) + (day (string-to-number (match-string 6))) + (mark (match-string 7)) + (code (match-string 8)) + (desc (match-string 9))) + (if (and year (> (length year) 0)) + (setq year (string-to-number year))) + (funcall callback start + (encode-time 0 0 0 day month + (or year current-year)) + mark desc))))) (forward-line)))) (defsubst ledger-goto-line (line-number) @@ -128,29 +129,30 @@ MOMENT is an encoded date" (defun ledger-year-and-month () (let ((sep (if ledger-use-iso-dates "-" - "/"))) - (concat ledger-year sep ledger-month sep))) + "/"))) + (concat ledger-year sep ledger-month sep))) (defun ledger-copy-transaction-at-point (date) "Ask for a new DATE and copy the transaction under point to that date. Leave point on the first amount." (interactive (list - (read-string "Copy to date: " (ledger-year-and-month) - 'ledger-minibuffer-history))) + (ledger-read-date "Copy to date: "))) (let* ((here (point)) - (extents (ledger-find-xact-extents (point))) - (transaction (buffer-substring-no-properties (car extents) (cadr extents))) - encoded-date) + (extents (ledger-find-xact-extents (point))) + (transaction (buffer-substring-no-properties (car extents) (cadr extents))) + encoded-date) (if (string-match ledger-iso-date-regexp date) - (setq encoded-date - (encode-time 0 0 0 (string-to-number (match-string 4 date)) - (string-to-number (match-string 3 date)) - (string-to-number (match-string 2 date))))) + (setq encoded-date + (encode-time 0 0 0 (string-to-number (match-string 4 date)) + (string-to-number (match-string 3 date)) + (string-to-number (match-string 2 date))))) (ledger-xact-find-slot encoded-date) (insert transaction "\n") (backward-paragraph 2) (re-search-forward ledger-iso-date-regexp) (replace-match date) - (ledger-next-amount))) + (ledger-next-amount) + (if (re-search-forward "[-0-9]") + (goto-char (match-beginning 0))))) (defun ledger-delete-current-transaction (pos) "Delete the transaction surrounging point." @@ -164,7 +166,9 @@ If INSERT-AT-POINT is non-nil insert the transaction there, otherwise call `ledger-xact-find-slot' to insert it at the correct chronological place in the buffer." (interactive (list - (read-string "Transaction: " (ledger-year-and-month)))) + ;; Note: This isn't "just" the date - it can contain + ;; other text too + (ledger-read-date "Transaction: "))) (let* ((args (with-temp-buffer (insert transaction-text) (eshell-parse-arguments (point-min) (point-max)))) @@ -179,20 +183,20 @@ correct chronological place in the buffer." (string-to-number (match-string 2 date))))) (ledger-xact-find-slot date))) (if (> (length args) 1) - (save-excursion - (insert - (with-temp-buffer - (setq exit-code - (apply #'ledger-exec-ledger ledger-buf (current-buffer) "xact" - (mapcar 'eval args))) - (goto-char (point-min)) - (if (looking-at "Error: ") - (error (concat "Error in ledger-add-transaction: " (buffer-string))) - (buffer-string))) - "\n")) - (progn - (insert (car args) " \n\n") - (end-of-line -1))))) + (save-excursion + (insert + (with-temp-buffer + (setq exit-code + (apply #'ledger-exec-ledger ledger-buf (current-buffer) "xact" + (mapcar 'eval args))) + (goto-char (point-min)) + (if (looking-at "Error: ") + (error (concat "Error in ledger-add-transaction: " (buffer-string))) + (buffer-string))) + "\n")) + (progn + (insert (car args) " \n\n") + (end-of-line -1))))) (provide 'ledger-xact) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9fd7d295..6304a50c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -49,7 +49,8 @@ set(LEDGER_SOURCES times.cc error.cc utils.cc - strptime.cc) + strptime.cc + wcwidth.cc) if(HAVE_BOOST_PYTHON) list(APPEND LEDGER_SOURCES @@ -163,6 +164,9 @@ if(CMAKE_BUILD_TYPE STREQUAL "Debug") set(_args ${CMAKE_CXX_FLAGS}) list(APPEND _args ${CMAKE_CXX_FLAGS_DEBUG}) + if(BUILD_LIBRARY) + list(APPEND _args ${CMAKE_SHARED_LIBRARY_CXX_FLAGS}) + endif() list(APPEND _args "-x c++-header " ${_inc}) list(APPEND _args -c ${_header_filename} -o ${_pch_filename}) @@ -215,6 +219,9 @@ if(CMAKE_BUILD_TYPE STREQUAL "Debug") set(_args ${CMAKE_CXX_FLAGS}) list(APPEND _args ${CMAKE_CXX_FLAGS_DEBUG}) + if(BUILD_LIBRARY) + list(APPEND _args ${CMAKE_SHARED_LIBRARY_CXX_FLAGS}) + endif() list(APPEND _args ${GXX_WARNING_FLAGS}) list(APPEND _args "-x c++-header " ${_inc}) list(APPEND _args -c ${_header_filename} -o ${_gch_filename}) @@ -243,21 +250,65 @@ endif() add_pch_rule(${PROJECT_BINARY_DIR}/system.hh LEDGER_SOURCES main.cc global.cc) +include(GNUInstallDirs) + if(BUILD_LIBRARY) - add_library(libledger ${LEDGER_SOURCES} ${PROJECT_SOURCE_DIR}/lib/sha1.cpp) - set_target_properties(libledger PROPERTIES OUTPUT_NAME ledger) + set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}") + add_library(libledger SHARED ${LEDGER_SOURCES} ${PROJECT_SOURCE_DIR}/lib/sha1.cpp) + add_ledger_library_dependencies(libledger) + set_target_properties(libledger PROPERTIES + PREFIX "" + INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}" + VERSION ${Ledger_VERSION_MAJOR} + SOVERSION ${Ledger_VERSION_MAJOR}) add_executable(ledger main.cc global.cc) + target_link_libraries(ledger libledger) - install(TARGETS libledger DESTINATION lib) - install(FILES ${LEDGER_INCLUDES} DESTINATION include/ledger) + install(TARGETS libledger DESTINATION ${CMAKE_INSTALL_LIBDIR}) + install(FILES ${LEDGER_INCLUDES} + ${PROJECT_SOURCE_DIR}/lib/sha1.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ledger) else() add_executable(ledger ${LEDGER_SOURCES} ${PROJECT_SOURCE_DIR}/lib/sha1.cpp main.cc global.cc) + add_ledger_library_dependencies(ledger) endif() -add_ledger_library_dependencies(ledger) +if(USE_PYTHON) + execute_process(COMMAND ${PYTHON_EXECUTABLE} -c + "from __future__ import print_function +import distutils.sysconfig as s +print(s.get_python_lib(True, prefix=''))" + OUTPUT_VARIABLE _TMP_PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE) + set(PYTHON_SITE_PACKAGES ${_TMP_PYTHON_SITE_PACKAGES} + CACHE PATH "python module directory (${_TMP_PYTHON_SITE_PACKAGES})") + + if (PYTHON_SITE_PACKAGES) + if(WIN32 AND NOT CYGWIN) + set(_ledger_python_module_name "ledger.pyd") + elseif(CMAKE_HOST_APPLE) + set(_ledger_python_module_name "ledger.so") + else() + set(_ledger_python_module_name "ledger${CMAKE_SHARED_LIBRARY_SUFFIX}") + endif() + + # FIXME: symlink would be sufficient: + # maybe using install(CODE "...") and + # execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink ...). + # Windows will need a special case due to not supporting symlinks. + add_custom_command( + TARGET libledger POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + $<TARGET_FILE:libledger> "${CMAKE_BINARY_DIR}/${_ledger_python_module_name}") + install( + FILES "${CMAKE_BINARY_DIR}/${_ledger_python_module_name}" + DESTINATION ${PYTHON_SITE_PACKAGES}) + else() + message(WARNING "PYTHON_SITE_PACKAGES not set. Will not install python module.") + endif() +endif() -install(TARGETS ledger DESTINATION bin) +install(TARGETS ledger DESTINATION ${CMAKE_INSTALL_BINDIR}) ### CMakeLists.txt ends here diff --git a/src/account.cc b/src/account.cc index 58812db9..4b3a4e97 100644 --- a/src/account.cc +++ b/src/account.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/account.h b/src/account.h index daeee038..f6f764cc 100644 --- a/src/account.h +++ b/src/account.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -310,7 +310,7 @@ void put_account(property_tree::ptree& pt, const account_t& acct, //simple struct added to allow std::map to compare accounts in the accounts report struct account_compare { - bool operator() (const account_t& lhs, const account_t& rhs){ + bool operator() (const account_t& lhs, const account_t& rhs) const { return (lhs.fullname().compare(rhs.fullname()) < 0); } }; diff --git a/src/amount.cc b/src/amount.cc index 4fe73546..7bf4dfc6 100644 --- a/src/amount.cc +++ b/src/amount.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -196,8 +196,8 @@ namespace { for (const char * p = buf; *p; p++) { if (*p == '.') { - if (commodity_t::time_colon_by_default || - (comm && comm->has_flags(COMMODITY_STYLE_TIME_COLON))) + if (("h" == comm->symbol() || "m" == comm->symbol()) && (commodity_t::time_colon_by_default || + (comm && comm->has_flags(COMMODITY_STYLE_TIME_COLON)))) out << ':'; else if (commodity_t::decimal_comma_by_default || (comm && comm->has_flags(COMMODITY_STYLE_DECIMAL_COMMA))) @@ -213,8 +213,8 @@ namespace { out << *p; if (integer_digits > 3 && --integer_digits % 3 == 0) { - if (commodity_t::time_colon_by_default || - (comm && comm->has_flags(COMMODITY_STYLE_TIME_COLON))) + if (("h" == comm->symbol() || "m" == comm->symbol()) && (commodity_t::time_colon_by_default || + (comm && comm->has_flags(COMMODITY_STYLE_TIME_COLON)))) out << ':'; else if (commodity_t::decimal_comma_by_default || (comm && comm->has_flags(COMMODITY_STYLE_DECIMAL_COMMA))) @@ -744,7 +744,7 @@ void amount_t::in_place_unreduce() } if (shifted) { - if ("h" == comm->symbol() && commodity_t::time_colon_by_default) { + if (("h" == comm->symbol() || "m" == comm->symbol()) && commodity_t::time_colon_by_default) { amount_t floored = tmp.floored(); amount_t precision = tmp - floored; if (precision < 0.0) { diff --git a/src/amount.h b/src/amount.h index 938d4b7b..8fadaf9d 100644 --- a/src/amount.h +++ b/src/amount.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/src/annotate.cc b/src/annotate.cc index 8816a89c..ab5c6e17 100644 --- a/src/annotate.cc +++ b/src/annotate.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/annotate.h b/src/annotate.h index 998f7c83..0f8f8e68 100644 --- a/src/annotate.h +++ b/src/annotate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/archive.cc b/src/archive.cc index 6ac1c580..87faab3c 100644 --- a/src/archive.cc +++ b/src/archive.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/archive.h b/src/archive.h index 5c15a9fb..d5a5a90b 100644 --- a/src/archive.h +++ b/src/archive.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/balance.cc b/src/balance.cc index b702cb7b..752bf133 100644 --- a/src/balance.cc +++ b/src/balance.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/balance.h b/src/balance.h index a1ae51ef..ca1ee31b 100644 --- a/src/balance.h +++ b/src/balance.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/chain.cc b/src/chain.cc index b2f6f203..bb3955b8 100644 --- a/src/chain.cc +++ b/src/chain.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/chain.h b/src/chain.h index de7f68c7..f9f5c6c6 100644 --- a/src/chain.h +++ b/src/chain.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/commodity.cc b/src/commodity.cc index 535b31c9..ae852462 100644 --- a/src/commodity.cc +++ b/src/commodity.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/commodity.h b/src/commodity.h index a1988a3b..80945fe7 100644 --- a/src/commodity.h +++ b/src/commodity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -353,7 +353,7 @@ void put_commodity(property_tree::ptree& pt, const commodity_t& comm, //simple struct to allow std::map to compare commodities names struct commodity_compare { - bool operator() (const commodity_t* lhs, const commodity_t* rhs){ + bool operator() (const commodity_t* lhs, const commodity_t* rhs) const { return (lhs->symbol().compare(rhs->symbol()) < 0); } }; diff --git a/src/compare.cc b/src/compare.cc index 946cd835..34e41332 100644 --- a/src/compare.cc +++ b/src/compare.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/compare.h b/src/compare.h index 4a91f49f..defc38f3 100644 --- a/src/compare.h +++ b/src/compare.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/context.h b/src/context.h index e5457641..9f5bfe8f 100644 --- a/src/context.h +++ b/src/context.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/convert.cc b/src/convert.cc index 38ef2c22..2fcec38e 100644 --- a/src/convert.cc +++ b/src/convert.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/convert.h b/src/convert.h index 17fb4505..c82dd34c 100644 --- a/src/convert.h +++ b/src/convert.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/draft.cc b/src/draft.cc index 6aef2f12..63173234 100644 --- a/src/draft.cc +++ b/src/draft.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/draft.h b/src/draft.h index 1cc362ba..39786ec8 100644 --- a/src/draft.h +++ b/src/draft.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/emacs.cc b/src/emacs.cc index 9bfd1e4b..2f8954ac 100644 --- a/src/emacs.cc +++ b/src/emacs.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/emacs.h b/src/emacs.h index 368c4c4d..feb881b5 100644 --- a/src/emacs.h +++ b/src/emacs.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/error.cc b/src/error.cc index acee85c9..035c5f19 100644 --- a/src/error.cc +++ b/src/error.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/error.h b/src/error.h index 93d92109..c4aa2a71 100644 --- a/src/error.h +++ b/src/error.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/expr.cc b/src/expr.cc index aa1e07d2..84da6292 100644 --- a/src/expr.cc +++ b/src/expr.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/exprbase.h b/src/exprbase.h index 88d6f118..17a8ad95 100644 --- a/src/exprbase.h +++ b/src/exprbase.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/filters.cc b/src/filters.cc index fadd5b5a..4046ebda 100644 --- a/src/filters.cc +++ b/src/filters.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/filters.h b/src/filters.h index f256707b..48d1a0fb 100644 --- a/src/filters.h +++ b/src/filters.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/flags.h b/src/flags.h index d584e2d0..910b70a7 100644 --- a/src/flags.h +++ b/src/flags.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/format.cc b/src/format.cc index e0f74616..9b5e7d93 100644 --- a/src/format.cc +++ b/src/format.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/format.h b/src/format.h index 38f567bd..3e16bbb5 100644 --- a/src/format.h +++ b/src/format.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/generate.cc b/src/generate.cc index 5bf424bb..b69d7cd1 100644 --- a/src/generate.cc +++ b/src/generate.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/generate.h b/src/generate.h index 697feb64..622861e2 100644 --- a/src/generate.h +++ b/src/generate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/global.cc b/src/global.cc index 0061ad76..95e408eb 100644 --- a/src/global.cc +++ b/src/global.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/global.h b/src/global.h index 5fa67d2c..eda75112 100644 --- a/src/global.h +++ b/src/global.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -127,7 +127,7 @@ public: out << '-' << Ledger_VERSION_DATE; out << _(", the command-line accounting tool"); out << - _("\n\nCopyright (c) 2003-2013, John Wiegley. All rights reserved.\n\n\ + _("\n\nCopyright (c) 2003-2014, John Wiegley. All rights reserved.\n\n\ This program is made available under the terms of the BSD Public License.\n\ See LICENSE file included with the distribution for details and disclaimer."); out << std::endl; diff --git a/src/history.cc b/src/history.cc index 93883ae0..3601c093 100644 --- a/src/history.cc +++ b/src/history.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/history.h b/src/history.h index fa69d8da..68c46189 100644 --- a/src/history.h +++ b/src/history.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/item.cc b/src/item.cc index a29a3fd3..551c8fef 100644 --- a/src/item.cc +++ b/src/item.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/iterators.cc b/src/iterators.cc index 738f33be..f02c5f04 100644 --- a/src/iterators.cc +++ b/src/iterators.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/iterators.h b/src/iterators.h index 3ece313c..93d0d7ce 100644 --- a/src/iterators.h +++ b/src/iterators.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/journal.cc b/src/journal.cc index 3e2ecbea..160abe06 100644 --- a/src/journal.cc +++ b/src/journal.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -96,6 +96,7 @@ void journal_t::initialize() check_payees = false; day_break = false; checking_style = CHECK_PERMISSIVE; + recursive_aliases = false; } void journal_t::add_account(account_t * acct) @@ -121,26 +122,9 @@ account_t * journal_t::find_account_re(const string& regexp) account_t * journal_t::register_account(const string& name, post_t * post, account_t * master_account) { - account_t * result = NULL; - - // If there any account aliases, substitute before creating an account + // If there are any account aliases, substitute before creating an account // object. - if (account_aliases.size() > 0) { - accounts_map::const_iterator i = account_aliases.find(name); - if (i != account_aliases.end()) { - result = (*i).second; - } else { - // only check the very first account for alias expansion, in case - // that can be expanded successfully - size_t colon = name.find(':'); - if(colon != string::npos) { - accounts_map::const_iterator j = account_aliases.find(name.substr(0, colon)); - if (j != account_aliases.end()) { - result = find_account((*j).second->fullname() + name.substr(colon)); - } - } - } - } + account_t * result = expand_aliases(name); // Create the account object and associate it with the journal; this // is registering the account. @@ -151,7 +135,7 @@ account_t * journal_t::register_account(const string& name, post_t * post, // the payee indicates an account that should be used. if (result->name == _("Unknown")) { foreach (account_mapping_t& value, payees_for_unknown_accounts) { - if (value.first.match(post->xact->payee)) { + if (post && value.first.match(post->xact->payee)) { result = value.second; break; } @@ -178,7 +162,63 @@ account_t * journal_t::register_account(const string& name, post_t * post, } } } + return result; +} + +account_t * journal_t::expand_aliases(string name) { + // Aliases are expanded recursively, so if both alias Foo=Bar:Foo and + // alias Bar=Baaz:Bar are in effect, first Foo will be expanded to Bar:Foo, + // then Bar:Foo will be expanded to Baaz:Bar:Foo. + // The expansion loop keeps a list of already expanded names in order to + // prevent infinite excursion. Each alias may only be expanded at most once. + account_t * result = NULL; + if(no_aliases) + return result; + + bool keep_expanding = true; + std::list<string> already_seen; + // loop until no expansion can be found + do { + if (account_aliases.size() > 0) { + accounts_map::const_iterator i = account_aliases.find(name); + if (i != account_aliases.end()) { + if(std::find(already_seen.begin(), already_seen.end(), name) != already_seen.end()) { + throw_(std::runtime_error, + _f("Infinite recursion on alias expansion for %1%") + % name); + } + // there is an alias for the full account name, including colons + already_seen.push_back(name); + result = (*i).second; + name = result->fullname(); + } else { + // only check the very first account for alias expansion, in case + // that can be expanded successfully + size_t colon = name.find(':'); + if(colon != string::npos) { + string first_account_name = name.substr(0, colon); + accounts_map::const_iterator j = account_aliases.find(first_account_name); + if (j != account_aliases.end()) { + if(std::find(already_seen.begin(), already_seen.end(), first_account_name) != already_seen.end()) { + throw_(std::runtime_error, + _f("Infinite recursion on alias expansion for %1%") + % first_account_name); + } + already_seen.push_back(first_account_name); + result = find_account((*j).second->fullname() + name.substr(colon)); + name = result->fullname(); + } else { + keep_expanding = false; + } + } else { + keep_expanding = false; + } + } + } else { + keep_expanding = false; + } + } while(keep_expanding && recursive_aliases); return result; } diff --git a/src/journal.h b/src/journal.h index 716e2910..e4763482 100644 --- a/src/journal.h +++ b/src/journal.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -131,6 +131,8 @@ public: bool force_checking; bool check_payees; bool day_break; + bool recursive_aliases; + bool no_aliases; payee_mappings_t payee_mappings; account_mappings_t account_mappings; accounts_map account_aliases; @@ -167,6 +169,8 @@ public: account_t * find_account(const string& name, bool auto_create = true); account_t * find_account_re(const string& regexp); + account_t * expand_aliases(string name); + account_t * register_account(const string& name, post_t * post, account_t * master = NULL); string register_payee(const string& name, xact_t * xact); diff --git a/src/lookup.cc b/src/lookup.cc index 2a602569..aa1eeb65 100644 --- a/src/lookup.cc +++ b/src/lookup.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/lookup.h b/src/lookup.h index ee80faac..60ef334b 100644 --- a/src/lookup.h +++ b/src/lookup.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/main.cc b/src/main.cc index accae197..81118e43 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/mask.cc b/src/mask.cc index 56ef02d1..5c5d02f9 100644 --- a/src/mask.cc +++ b/src/mask.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/option.cc b/src/option.cc index 256ee45b..0629399e 100644 --- a/src/option.cc +++ b/src/option.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/option.h b/src/option.h index fe3e257b..21942436 100644 --- a/src/option.h +++ b/src/option.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -43,7 +43,8 @@ namespace ledger { posts_to_org_table::posts_to_org_table(report_t& _report, const optional<string>& _prepend_format) - : report(_report), last_xact(NULL), last_post(NULL) + : report(_report), last_xact(NULL), last_post(NULL), + header_printed(false), first_report_title(true) { first_line_format.parse_format ("|%(format_date(date))" @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/output.cc b/src/output.cc index 77d28eed..f8555fe5 100644 --- a/src/output.cc +++ b/src/output.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/output.h b/src/output.h index 31afbd13..38f1e59e 100644 --- a/src/output.h +++ b/src/output.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/parser.cc b/src/parser.cc index bcb23f48..7fbbff8a 100644 --- a/src/parser.cc +++ b/src/parser.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/parser.h b/src/parser.h index 8cc8027f..a056493a 100644 --- a/src/parser.h +++ b/src/parser.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pool.cc b/src/pool.cc index 2627c816..4526ac0c 100644 --- a/src/pool.cc +++ b/src/pool.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/post.cc b/src/post.cc index 1a24429b..4244a349 100644 --- a/src/post.cc +++ b/src/post.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/precmd.cc b/src/precmd.cc index e9c966e9..edd824f1 100644 --- a/src/precmd.cc +++ b/src/precmd.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/precmd.h b/src/precmd.h index 27925f42..f25fcb43 100644 --- a/src/precmd.h +++ b/src/precmd.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/predicate.h b/src/predicate.h index 6a1cc01c..964d4418 100644 --- a/src/predicate.h +++ b/src/predicate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/print.cc b/src/print.cc index 0683f2e3..c0817950 100644 --- a/src/print.cc +++ b/src/print.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/print.h b/src/print.h index 8d78e8cc..e882922e 100644 --- a/src/print.h +++ b/src/print.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pstream.h b/src/pstream.h index 4886dc0b..ed314068 100644 --- a/src/pstream.h +++ b/src/pstream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -83,7 +83,10 @@ class ptristream : public std::istream virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode) { - switch (way) { + // cast to avoid gcc '-Wswitch' warning + // as ios_base::beg/cur/end are not necesssarily values of 'way' enum type ios_base::seekdir + // based on https://svn.boost.org/trac/boost/ticket/7644 + switch (static_cast<int>(way)) { case std::ios::cur: setg(ptr, gptr()+off, ptr+len); break; diff --git a/src/ptree.cc b/src/ptree.cc index e7afdcd1..6609aed9 100644 --- a/src/ptree.cc +++ b/src/ptree.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/ptree.h b/src/ptree.h index 154c8837..dc1161f3 100644 --- a/src/ptree.h +++ b/src/ptree.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_account.cc b/src/py_account.cc index fbd68140..3054512e 100644 --- a/src/py_account.cc +++ b/src/py_account.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_amount.cc b/src/py_amount.cc index 50e16a70..01fb370c 100644 --- a/src/py_amount.cc +++ b/src/py_amount.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_balance.cc b/src/py_balance.cc index 65e3c401..8bf30050 100644 --- a/src/py_balance.cc +++ b/src/py_balance.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_commodity.cc b/src/py_commodity.cc index fd932fc7..18903a86 100644 --- a/src/py_commodity.cc +++ b/src/py_commodity.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -315,6 +315,7 @@ void export_commodity() scope().attr("COMMODITY_STYLE_SUFFIXED") = COMMODITY_STYLE_SUFFIXED; scope().attr("COMMODITY_STYLE_SEPARATED") = COMMODITY_STYLE_SEPARATED; scope().attr("COMMODITY_STYLE_DECIMAL_COMMA") = COMMODITY_STYLE_DECIMAL_COMMA; + scope().attr("COMMODITY_STYLE_TIME_COLON") = COMMODITY_STYLE_TIME_COLON; scope().attr("COMMODITY_STYLE_THOUSANDS") = COMMODITY_STYLE_THOUSANDS; scope().attr("COMMODITY_NOMARKET") = COMMODITY_NOMARKET; scope().attr("COMMODITY_BUILTIN") = COMMODITY_BUILTIN; diff --git a/src/py_expr.cc b/src/py_expr.cc index c680bab4..c62cb3e1 100644 --- a/src/py_expr.cc +++ b/src/py_expr.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_format.cc b/src/py_format.cc index 43266b29..ba590e62 100644 --- a/src/py_format.cc +++ b/src/py_format.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_item.cc b/src/py_item.cc index 02b978c5..5d9a4ae2 100644 --- a/src/py_item.cc +++ b/src/py_item.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_journal.cc b/src/py_journal.cc index 7cce6b11..cc2b996d 100644 --- a/src/py_journal.cc +++ b/src/py_journal.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_post.cc b/src/py_post.cc index 6061d6ee..d6ff5402 100644 --- a/src/py_post.cc +++ b/src/py_post.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_session.cc b/src/py_session.cc index 7e2f9e8a..25d13cc0 100644 --- a/src/py_session.cc +++ b/src/py_session.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_times.cc b/src/py_times.cc index 599aa60c..44a6f3cd 100644 --- a/src/py_times.cc +++ b/src/py_times.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_utils.cc b/src/py_utils.cc index dc572621..0dc3d2bf 100644 --- a/src/py_utils.cc +++ b/src/py_utils.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_value.cc b/src/py_value.cc index 8b565661..669e0d73 100644 --- a/src/py_value.cc +++ b/src/py_value.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/py_xact.cc b/src/py_xact.cc index 0b07f582..5e355ad9 100644 --- a/src/py_xact.cc +++ b/src/py_xact.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pyfstream.h b/src/pyfstream.h index 12bbecfd..d1aca260 100644 --- a/src/pyfstream.h +++ b/src/pyfstream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pyinterp.cc b/src/pyinterp.cc index e15ff503..9d6638fc 100644 --- a/src/pyinterp.cc +++ b/src/pyinterp.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -34,6 +34,7 @@ #include "pyinterp.h" #include "pyutils.h" #include "account.h" +#include "report.h" #include "xact.h" #include "post.h" @@ -76,6 +77,12 @@ void initialize_for_python() export_xact(); export_session(); export_journal(); + + if (! scope_t::default_scope) { + python_session.reset(new ledger::python_interpreter_t); + shared_ptr<session_t> session_ptr = python_session; + scope_t::default_scope = new report_t(*session_ptr); + } } struct python_run diff --git a/src/pyinterp.h b/src/pyinterp.h index e961f4c0..5ea40567 100644 --- a/src/pyinterp.h +++ b/src/pyinterp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pyledger.cc b/src/pyledger.cc index ee7b99c9..27a07deb 100644 --- a/src/pyledger.cc +++ b/src/pyledger.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/pyutils.h b/src/pyutils.h index 6bb9d0bd..0a50d0eb 100644 --- a/src/pyutils.h +++ b/src/pyutils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/query.cc b/src/query.cc index 209205ae..7e96b040 100644 --- a/src/query.cc +++ b/src/query.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/query.h b/src/query.h index 10820a59..f2161eb8 100644 --- a/src/query.h +++ b/src/query.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/quotes.cc b/src/quotes.cc index 2df51ec1..c29f18d0 100644 --- a/src/quotes.cc +++ b/src/quotes.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/quotes.h b/src/quotes.h index 813bdfa3..34c506dd 100644 --- a/src/quotes.h +++ b/src/quotes.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/report.cc b/src/report.cc index 29077f10..9756b60b 100644 --- a/src/report.cc +++ b/src/report.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/report.h b/src/report.h index 5897e8f6..120a7020 100644 --- a/src/report.h +++ b/src/report.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -521,7 +521,7 @@ public: "%(quoted(code))," "%(quoted(payee))," "%(quoted(display_account))," - "%(quoted(commodity))," + "%(quoted(commodity(scrub(display_amount))))," "%(quoted(quantity(scrub(display_amount))))," "%(quoted(cleared ? \"*\" : (pending ? \"!\" : \"\")))," "%(quoted(join(note | xact.note)))\n"); diff --git a/src/scope.cc b/src/scope.cc index 10ae45a9..7eaf50c3 100644 --- a/src/scope.cc +++ b/src/scope.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/scope.h b/src/scope.h index d6291439..30b825a3 100644 --- a/src/scope.h +++ b/src/scope.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/select.cc b/src/select.cc index b7e4c920..8cfb6666 100644 --- a/src/select.cc +++ b/src/select.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/select.h b/src/select.h index 346067a2..09555db8 100644 --- a/src/select.h +++ b/src/select.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/session.cc b/src/session.cc index e5425a50..b386607a 100644 --- a/src/session.cc +++ b/src/session.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -113,6 +113,11 @@ std::size_t session_t::read_data(const string& master_account) if (HANDLED(day_break)) journal->day_break = true; + if (HANDLED(recursive_aliases)) + journal->recursive_aliases = true; + if (HANDLED(no_aliases)) + journal->no_aliases = true; + if (HANDLED(permissive)) journal->checking_style = journal_t::CHECK_PERMISSIVE; else if (HANDLED(pedantic)) @@ -344,12 +349,18 @@ option_t<session_t> * session_t::lookup_option(const char * p) case 'm': OPT(master_account_); break; + case 'n': + OPT(no_aliases); + break; case 'p': OPT(price_db_); else OPT(price_exp_); else OPT(pedantic); else OPT(permissive); break; + case 'r': + OPT(recursive_aliases); + break; case 's': OPT(strict); break; diff --git a/src/session.h b/src/session.h index 21be3cc7..d20ba74a 100644 --- a/src/session.h +++ b/src/session.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -109,6 +109,8 @@ public: HANDLER(permissive).report(out); HANDLER(price_db_).report(out); HANDLER(price_exp_).report(out); + HANDLER(recursive_aliases).report(out); + HANDLER(no_aliases).report(out); HANDLER(strict).report(out); HANDLER(value_expr_).report(out); } @@ -164,6 +166,8 @@ public: OPTION(session_t, price_db_); OPTION(session_t, strict); OPTION(session_t, value_expr_); + OPTION(session_t, recursive_aliases); + OPTION(session_t, no_aliases); }; /** diff --git a/src/stats.cc b/src/stats.cc index 81d71a46..31bceea3 100644 --- a/src/stats.cc +++ b/src/stats.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/stats.h b/src/stats.h index 5583e704..7502fc20 100644 --- a/src/stats.h +++ b/src/stats.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/stream.cc b/src/stream.cc index c00c4cc5..e4eb7800 100644 --- a/src/stream.cc +++ b/src/stream.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -80,18 +80,10 @@ namespace { close(pfd[1]); close(pfd[0]); - // Find command name: its the substring starting right of the - // rightmost '/' character in the pager pathname. See manpage for - // strrchr. -#if BOOST_VERSION >= 103700 - path basename(pager_path.filename()); -#else - path basename(pager_path.leaf()); -#endif - execlp(pager_path.string().c_str(), basename.string().c_str(), NULL); + execlp("/bin/sh", "/bin/sh", "-c", pager_path.string().c_str(), NULL); // We should never, ever reach here - perror((std::string("execlp: ") + pager_path.string()).c_str()); + perror("execlp: /bin/sh"); exit(1); } else { // parent diff --git a/src/stream.h b/src/stream.h index bb63873a..577a3291 100644 --- a/src/stream.h +++ b/src/stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/system.hh.in b/src/system.hh.in index ff7ea75b..fd5c47c6 100644 --- a/src/system.hh.in +++ b/src/system.hh.in @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/temps.cc b/src/temps.cc index b4778b49..75669a2a 100644 --- a/src/temps.cc +++ b/src/temps.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/temps.h b/src/temps.h index 99110496..eedea4c1 100644 --- a/src/temps.h +++ b/src/temps.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/textual.cc b/src/textual.cc index 9e19ee37..627a1835 100644 --- a/src/textual.cc +++ b/src/textual.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -416,7 +416,7 @@ void instance_t::read_next_directive(bool& error_flag) price_xact_directive(line); break; case 'Y': // set the current year - apply_year_directive(line); + apply_year_directive(line + 1); break; } } @@ -865,7 +865,7 @@ void instance_t::apply_year_directive(char * line) // This must be set to the last day of the year, otherwise partial // dates like "11/01" will refer to last year's november, not the // current year. - unsigned short year(lexical_cast<unsigned short>(skip_ws(line + 1))); + unsigned short year(lexical_cast<unsigned short>(skip_ws(line))); DEBUG("times.epoch", "Setting current year to " << year); epoch = datetime_t(date_t(year, 12, 31)); } @@ -977,6 +977,11 @@ void instance_t::account_alias_directive(account_t * account, string alias) // (account), add a reference to the account in the `account_aliases' // map, which is used by the post parser to resolve alias references. trim(alias); + // Ensure that no alias like "alias Foo=Foo" is registered. + if ( alias == account->fullname()) { + throw_(parse_error, _f("Illegal alias %1%=%2%") + % alias % account->fullname()); + } std::pair<accounts_map::iterator, bool> result = context.journal->account_aliases.insert (accounts_map::value_type(alias, account)); diff --git a/src/timelog.cc b/src/timelog.cc index 64017d50..8f157d62 100644 --- a/src/timelog.cc +++ b/src/timelog.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/timelog.h b/src/timelog.h index 1ce0be28..50c93aab 100644 --- a/src/timelog.h +++ b/src/timelog.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/times.cc b/src/times.cc index b1cb3494..3fd9a1df 100644 --- a/src/times.cc +++ b/src/times.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/times.h b/src/times.h index 4b89cc0c..2a5b9277 100644 --- a/src/times.h +++ b/src/times.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/token.cc b/src/token.cc index d0ec185b..aa78cd5a 100644 --- a/src/token.cc +++ b/src/token.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -522,7 +522,8 @@ void expr_t::token_t::expected(const char wanted, char c) void expr_t::token_t::expected(const kind_t wanted) { try { - if (wanted == '\0' || wanted == -1) + if (wanted == expr_t::token_t::ERROR || + wanted == expr_t::token_t::UNKNOWN) throw_(parse_error, _f("Invalid token '%1%'") % *this); else throw_(parse_error, diff --git a/src/token.h b/src/token.h index 51fa1d78..febd8620 100644 --- a/src/token.h +++ b/src/token.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/unistring.h b/src/unistring.h index eb38f8b1..340115eb 100644 --- a/src/unistring.h +++ b/src/unistring.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -44,6 +44,8 @@ namespace ledger { +int mk_wcwidth(boost::uint32_t ucs); + /** * @class unistring * @@ -81,6 +83,14 @@ public: return utf32chars.size(); } + std::size_t width() const { + std::size_t width = 0; + foreach (const boost::uint32_t& ch, utf32chars) { + width += mk_wcwidth(ch); + } + return width; + } + std::string extract(const std::string::size_type begin = 0, const std::string::size_type len = 0) const { @@ -133,7 +143,7 @@ inline void justify(std::ostream& out, unistring temp(str); - int spacing = width - int(temp.length()); + int spacing = width - int(temp.width()); while (spacing-- > 0) out << ' '; diff --git a/src/utils.cc b/src/utils.cc index 4f810f93..2256d22a 100644 --- a/src/utils.cc +++ b/src/utils.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/utils.h b/src/utils.h index c4d11636..70b3bae9 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/value.cc b/src/value.cc index 98e48c2f..70a8ab43 100644 --- a/src/value.cc +++ b/src/value.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -870,6 +870,8 @@ bool value_t::is_less_than(const value_t& val) const return as_long() < val.as_long(); case AMOUNT: return val.as_amount() > as_long(); + case BALANCE: + return val.to_amount() > as_long(); default: break; } @@ -886,6 +888,8 @@ bool value_t::is_less_than(const value_t& val) const return as_amount() < val.as_amount(); else return commodity_t::compare_by_commodity()(&as_amount(), &val.as_amount()); + case BALANCE: + return val.to_amount() > as_amount(); default: break; } @@ -904,6 +908,8 @@ bool value_t::is_less_than(const value_t& val) const } return ! no_amounts; } + case BALANCE: + return val.to_amount() > to_amount(); default: break; } @@ -990,6 +996,8 @@ bool value_t::is_greater_than(const value_t& val) const return as_long() > val.as_long(); case AMOUNT: return val.as_amount() < as_long(); + case BALANCE: + return val.to_amount() < as_long(); default: break; } @@ -1001,6 +1009,8 @@ bool value_t::is_greater_than(const value_t& val) const return as_amount() > val.as_long(); case AMOUNT: return as_amount() > val.as_amount(); + case BALANCE: + return val.to_amount() < as_amount(); default: break; } @@ -1019,6 +1029,8 @@ bool value_t::is_greater_than(const value_t& val) const } return ! no_amounts; } + case BALANCE: + return val.to_amount() < to_amount(); default: break; } diff --git a/src/value.h b/src/value.h index 93760234..3308e160 100644 --- a/src/value.h +++ b/src/value.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/views.cc b/src/views.cc index 2646e84b..f0931e87 100644 --- a/src/views.cc +++ b/src/views.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/views.h b/src/views.h index 94bedda5..bc4e5011 100644 --- a/src/views.h +++ b/src/views.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/src/wcwidth.c.patch b/src/wcwidth.c.patch new file mode 100644 index 00000000..5864a056 --- /dev/null +++ b/src/wcwidth.c.patch @@ -0,0 +1,74 @@ +--- wcwidth.c 2007-05-26 18:06:24.000000000 +0800 ++++ wcwidth.cc 2014-02-13 18:36:18.668331252 +0800 +@@ -59,15 +59,23 @@ + * Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c + */ + +-#include <wchar.h> ++/* This file is modified to work with C++ and present Unicode ++ * characters in uint32_t type. ++ */ ++ ++#include <system.hh> ++ ++namespace ledger { + +-struct interval { +- int first; +- int last; +-}; ++namespace { ++ struct interval { ++ int first; ++ int last; ++ }; ++} + + /* auxiliary function for binary search in interval table */ +-static int bisearch(wchar_t ucs, const struct interval *table, int max) { ++static int bisearch(boost::uint32_t ucs, const struct interval *table, int max) { + int min = 0; + int mid; + +@@ -119,7 +127,7 @@ + * in ISO 10646. + */ + +-int mk_wcwidth(wchar_t ucs) ++int mk_wcwidth(boost::uint32_t ucs) + { + /* sorted list of non-overlapping intervals of non-spacing characters */ + /* generated by "uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B c" */ +@@ -204,7 +212,7 @@ + } + + +-int mk_wcswidth(const wchar_t *pwcs, size_t n) ++int mk_wcswidth(const boost::uint32_t *pwcs, size_t n) + { + int w, width = 0; + +@@ -227,7 +235,7 @@ + * the traditional terminal character-width behaviour. It is not + * otherwise recommended for general use. + */ +-int mk_wcwidth_cjk(wchar_t ucs) ++int mk_wcwidth_cjk(boost::uint32_t ucs) + { + /* sorted list of non-overlapping intervals of East Asian Ambiguous + * characters, generated by "uniset +WIDTH-A -cat=Me -cat=Mn -cat=Cf c" */ +@@ -295,7 +303,7 @@ + } + + +-int mk_wcswidth_cjk(const wchar_t *pwcs, size_t n) ++int mk_wcswidth_cjk(const boost::uint32_t *pwcs, size_t n) + { + int w, width = 0; + +@@ -307,3 +315,5 @@ + + return width; + } ++ ++} // namespace ledger diff --git a/src/wcwidth.cc b/src/wcwidth.cc new file mode 100644 index 00000000..c23f83d7 --- /dev/null +++ b/src/wcwidth.cc @@ -0,0 +1,319 @@ +/* + * This is an implementation of wcwidth() and wcswidth() (defined in + * IEEE Std 1002.1-2001) for Unicode. + * + * http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html + * http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html + * + * In fixed-width output devices, Latin characters all occupy a single + * "cell" position of equal width, whereas ideographic CJK characters + * occupy two such cells. Interoperability between terminal-line + * applications and (teletype-style) character terminals using the + * UTF-8 encoding requires agreement on which character should advance + * the cursor by how many cell positions. No established formal + * standards exist at present on which Unicode character shall occupy + * how many cell positions on character terminals. These routines are + * a first attempt of defining such behavior based on simple rules + * applied to data provided by the Unicode Consortium. + * + * For some graphical characters, the Unicode standard explicitly + * defines a character-cell width via the definition of the East Asian + * FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. + * In all these cases, there is no ambiguity about which width a + * terminal shall use. For characters in the East Asian Ambiguous (A) + * class, the width choice depends purely on a preference of backward + * compatibility with either historic CJK or Western practice. + * Choosing single-width for these characters is easy to justify as + * the appropriate long-term solution, as the CJK practice of + * displaying these characters as double-width comes from historic + * implementation simplicity (8-bit encoded characters were displayed + * single-width and 16-bit ones double-width, even for Greek, + * Cyrillic, etc.) and not any typographic considerations. + * + * Much less clear is the choice of width for the Not East Asian + * (Neutral) class. Existing practice does not dictate a width for any + * of these characters. It would nevertheless make sense + * typographically to allocate two character cells to characters such + * as for instance EM SPACE or VOLUME INTEGRAL, which cannot be + * represented adequately with a single-width glyph. The following + * routines at present merely assign a single-cell width to all + * neutral characters, in the interest of simplicity. This is not + * entirely satisfactory and should be reconsidered before + * establishing a formal standard in this area. At the moment, the + * decision which Not East Asian (Neutral) characters should be + * represented by double-width glyphs cannot yet be answered by + * applying a simple rule from the Unicode database content. Setting + * up a proper standard for the behavior of UTF-8 character terminals + * will require a careful analysis not only of each Unicode character, + * but also of each presentation form, something the author of these + * routines has avoided to do so far. + * + * http://www.unicode.org/unicode/reports/tr11/ + * + * Markus Kuhn -- 2007-05-26 (Unicode 5.0) + * + * Permission to use, copy, modify, and distribute this software + * for any purpose and without fee is hereby granted. The author + * disclaims all warranties with regard to this software. + * + * Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c + */ + +/* This file is modified to work with C++ and present Unicode + * characters in uint32_t type. + */ + +#include <system.hh> + +namespace ledger { + +namespace { + struct interval { + boost::uint32_t first; + boost::uint32_t last; + }; +} + +/* auxiliary function for binary search in interval table */ +static int bisearch(boost::uint32_t ucs, const struct interval *table, int max) { + int min = 0; + int mid; + + if (ucs < table[0].first || ucs > table[max].last) + return 0; + while (max >= min) { + mid = (min + max) / 2; + if (ucs > table[mid].last) + min = mid + 1; + else if (ucs < table[mid].first) + max = mid - 1; + else + return 1; + } + + return 0; +} + + +/* The following two functions define the column width of an ISO 10646 + * character as follows: + * + * - The null character (U+0000) has a column width of 0. + * + * - Other C0/C1 control characters and DEL will lead to a return + * value of -1. + * + * - Non-spacing and enclosing combining characters (general + * category code Mn or Me in the Unicode database) have a + * column width of 0. + * + * - SOFT HYPHEN (U+00AD) has a column width of 1. + * + * - Other format characters (general category code Cf in the Unicode + * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0. + * + * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) + * have a column width of 0. + * + * - Spacing characters in the East Asian Wide (W) or East Asian + * Full-width (F) category as defined in Unicode Technical + * Report #11 have a column width of 2. + * + * - All remaining characters (including all printable + * ISO 8859-1 and WGL4 characters, Unicode control characters, + * etc.) have a column width of 1. + * + * This implementation assumes that wchar_t characters are encoded + * in ISO 10646. + */ + +int mk_wcwidth(boost::uint32_t ucs) +{ + /* sorted list of non-overlapping intervals of non-spacing characters */ + /* generated by "uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B c" */ + static const struct interval combining[] = { + { 0x0300, 0x036F }, { 0x0483, 0x0486 }, { 0x0488, 0x0489 }, + { 0x0591, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, + { 0x05C4, 0x05C5 }, { 0x05C7, 0x05C7 }, { 0x0600, 0x0603 }, + { 0x0610, 0x0615 }, { 0x064B, 0x065E }, { 0x0670, 0x0670 }, + { 0x06D6, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED }, + { 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A }, + { 0x07A6, 0x07B0 }, { 0x07EB, 0x07F3 }, { 0x0901, 0x0902 }, + { 0x093C, 0x093C }, { 0x0941, 0x0948 }, { 0x094D, 0x094D }, + { 0x0951, 0x0954 }, { 0x0962, 0x0963 }, { 0x0981, 0x0981 }, + { 0x09BC, 0x09BC }, { 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD }, + { 0x09E2, 0x09E3 }, { 0x0A01, 0x0A02 }, { 0x0A3C, 0x0A3C }, + { 0x0A41, 0x0A42 }, { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, + { 0x0A70, 0x0A71 }, { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC }, + { 0x0AC1, 0x0AC5 }, { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD }, + { 0x0AE2, 0x0AE3 }, { 0x0B01, 0x0B01 }, { 0x0B3C, 0x0B3C }, + { 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B43 }, { 0x0B4D, 0x0B4D }, + { 0x0B56, 0x0B56 }, { 0x0B82, 0x0B82 }, { 0x0BC0, 0x0BC0 }, + { 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 }, { 0x0C46, 0x0C48 }, + { 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 }, { 0x0CBC, 0x0CBC }, + { 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD }, + { 0x0CE2, 0x0CE3 }, { 0x0D41, 0x0D43 }, { 0x0D4D, 0x0D4D }, + { 0x0DCA, 0x0DCA }, { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 }, + { 0x0E31, 0x0E31 }, { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E }, + { 0x0EB1, 0x0EB1 }, { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC }, + { 0x0EC8, 0x0ECD }, { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 }, + { 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E }, + { 0x0F80, 0x0F84 }, { 0x0F86, 0x0F87 }, { 0x0F90, 0x0F97 }, + { 0x0F99, 0x0FBC }, { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 }, + { 0x1032, 0x1032 }, { 0x1036, 0x1037 }, { 0x1039, 0x1039 }, + { 0x1058, 0x1059 }, { 0x1160, 0x11FF }, { 0x135F, 0x135F }, + { 0x1712, 0x1714 }, { 0x1732, 0x1734 }, { 0x1752, 0x1753 }, + { 0x1772, 0x1773 }, { 0x17B4, 0x17B5 }, { 0x17B7, 0x17BD }, + { 0x17C6, 0x17C6 }, { 0x17C9, 0x17D3 }, { 0x17DD, 0x17DD }, + { 0x180B, 0x180D }, { 0x18A9, 0x18A9 }, { 0x1920, 0x1922 }, + { 0x1927, 0x1928 }, { 0x1932, 0x1932 }, { 0x1939, 0x193B }, + { 0x1A17, 0x1A18 }, { 0x1B00, 0x1B03 }, { 0x1B34, 0x1B34 }, + { 0x1B36, 0x1B3A }, { 0x1B3C, 0x1B3C }, { 0x1B42, 0x1B42 }, + { 0x1B6B, 0x1B73 }, { 0x1DC0, 0x1DCA }, { 0x1DFE, 0x1DFF }, + { 0x200B, 0x200F }, { 0x202A, 0x202E }, { 0x2060, 0x2063 }, + { 0x206A, 0x206F }, { 0x20D0, 0x20EF }, { 0x302A, 0x302F }, + { 0x3099, 0x309A }, { 0xA806, 0xA806 }, { 0xA80B, 0xA80B }, + { 0xA825, 0xA826 }, { 0xFB1E, 0xFB1E }, { 0xFE00, 0xFE0F }, + { 0xFE20, 0xFE23 }, { 0xFEFF, 0xFEFF }, { 0xFFF9, 0xFFFB }, + { 0x10A01, 0x10A03 }, { 0x10A05, 0x10A06 }, { 0x10A0C, 0x10A0F }, + { 0x10A38, 0x10A3A }, { 0x10A3F, 0x10A3F }, { 0x1D167, 0x1D169 }, + { 0x1D173, 0x1D182 }, { 0x1D185, 0x1D18B }, { 0x1D1AA, 0x1D1AD }, + { 0x1D242, 0x1D244 }, { 0xE0001, 0xE0001 }, { 0xE0020, 0xE007F }, + { 0xE0100, 0xE01EF } + }; + + /* test for 8-bit control characters */ + if (ucs == 0) + return 0; + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) + return -1; + + /* binary search in table of non-spacing characters */ + if (bisearch(ucs, combining, + sizeof(combining) / sizeof(struct interval) - 1)) + return 0; + + /* if we arrive here, ucs is not a combining or C0/C1 control character */ + + return 1 + + (ucs >= 0x1100 && + (ucs <= 0x115f || /* Hangul Jamo init. consonants */ + ucs == 0x2329 || ucs == 0x232a || + (ucs >= 0x2e80 && ucs <= 0xa4cf && + ucs != 0x303f) || /* CJK ... Yi */ + (ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */ + (ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */ + (ucs >= 0xfe10 && ucs <= 0xfe19) || /* Vertical forms */ + (ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */ + (ucs >= 0xff00 && ucs <= 0xff60) || /* Fullwidth Forms */ + (ucs >= 0xffe0 && ucs <= 0xffe6) || + (ucs >= 0x20000 && ucs <= 0x2fffd) || + (ucs >= 0x30000 && ucs <= 0x3fffd))); +} + + +int mk_wcswidth(const boost::uint32_t *pwcs, size_t n) +{ + int w, width = 0; + + for (;*pwcs && n-- > 0; pwcs++) + if ((w = mk_wcwidth(*pwcs)) < 0) + return -1; + else + width += w; + + return width; +} + + +/* + * The following functions are the same as mk_wcwidth() and + * mk_wcswidth(), except that spacing characters in the East Asian + * Ambiguous (A) category as defined in Unicode Technical Report #11 + * have a column width of 2. This variant might be useful for users of + * CJK legacy encodings who want to migrate to UCS without changing + * the traditional terminal character-width behaviour. It is not + * otherwise recommended for general use. + */ +int mk_wcwidth_cjk(boost::uint32_t ucs) +{ + /* sorted list of non-overlapping intervals of East Asian Ambiguous + * characters, generated by "uniset +WIDTH-A -cat=Me -cat=Mn -cat=Cf c" */ + static const struct interval ambiguous[] = { + { 0x00A1, 0x00A1 }, { 0x00A4, 0x00A4 }, { 0x00A7, 0x00A8 }, + { 0x00AA, 0x00AA }, { 0x00AE, 0x00AE }, { 0x00B0, 0x00B4 }, + { 0x00B6, 0x00BA }, { 0x00BC, 0x00BF }, { 0x00C6, 0x00C6 }, + { 0x00D0, 0x00D0 }, { 0x00D7, 0x00D8 }, { 0x00DE, 0x00E1 }, + { 0x00E6, 0x00E6 }, { 0x00E8, 0x00EA }, { 0x00EC, 0x00ED }, + { 0x00F0, 0x00F0 }, { 0x00F2, 0x00F3 }, { 0x00F7, 0x00FA }, + { 0x00FC, 0x00FC }, { 0x00FE, 0x00FE }, { 0x0101, 0x0101 }, + { 0x0111, 0x0111 }, { 0x0113, 0x0113 }, { 0x011B, 0x011B }, + { 0x0126, 0x0127 }, { 0x012B, 0x012B }, { 0x0131, 0x0133 }, + { 0x0138, 0x0138 }, { 0x013F, 0x0142 }, { 0x0144, 0x0144 }, + { 0x0148, 0x014B }, { 0x014D, 0x014D }, { 0x0152, 0x0153 }, + { 0x0166, 0x0167 }, { 0x016B, 0x016B }, { 0x01CE, 0x01CE }, + { 0x01D0, 0x01D0 }, { 0x01D2, 0x01D2 }, { 0x01D4, 0x01D4 }, + { 0x01D6, 0x01D6 }, { 0x01D8, 0x01D8 }, { 0x01DA, 0x01DA }, + { 0x01DC, 0x01DC }, { 0x0251, 0x0251 }, { 0x0261, 0x0261 }, + { 0x02C4, 0x02C4 }, { 0x02C7, 0x02C7 }, { 0x02C9, 0x02CB }, + { 0x02CD, 0x02CD }, { 0x02D0, 0x02D0 }, { 0x02D8, 0x02DB }, + { 0x02DD, 0x02DD }, { 0x02DF, 0x02DF }, { 0x0391, 0x03A1 }, + { 0x03A3, 0x03A9 }, { 0x03B1, 0x03C1 }, { 0x03C3, 0x03C9 }, + { 0x0401, 0x0401 }, { 0x0410, 0x044F }, { 0x0451, 0x0451 }, + { 0x2010, 0x2010 }, { 0x2013, 0x2016 }, { 0x2018, 0x2019 }, + { 0x201C, 0x201D }, { 0x2020, 0x2022 }, { 0x2024, 0x2027 }, + { 0x2030, 0x2030 }, { 0x2032, 0x2033 }, { 0x2035, 0x2035 }, + { 0x203B, 0x203B }, { 0x203E, 0x203E }, { 0x2074, 0x2074 }, + { 0x207F, 0x207F }, { 0x2081, 0x2084 }, { 0x20AC, 0x20AC }, + { 0x2103, 0x2103 }, { 0x2105, 0x2105 }, { 0x2109, 0x2109 }, + { 0x2113, 0x2113 }, { 0x2116, 0x2116 }, { 0x2121, 0x2122 }, + { 0x2126, 0x2126 }, { 0x212B, 0x212B }, { 0x2153, 0x2154 }, + { 0x215B, 0x215E }, { 0x2160, 0x216B }, { 0x2170, 0x2179 }, + { 0x2190, 0x2199 }, { 0x21B8, 0x21B9 }, { 0x21D2, 0x21D2 }, + { 0x21D4, 0x21D4 }, { 0x21E7, 0x21E7 }, { 0x2200, 0x2200 }, + { 0x2202, 0x2203 }, { 0x2207, 0x2208 }, { 0x220B, 0x220B }, + { 0x220F, 0x220F }, { 0x2211, 0x2211 }, { 0x2215, 0x2215 }, + { 0x221A, 0x221A }, { 0x221D, 0x2220 }, { 0x2223, 0x2223 }, + { 0x2225, 0x2225 }, { 0x2227, 0x222C }, { 0x222E, 0x222E }, + { 0x2234, 0x2237 }, { 0x223C, 0x223D }, { 0x2248, 0x2248 }, + { 0x224C, 0x224C }, { 0x2252, 0x2252 }, { 0x2260, 0x2261 }, + { 0x2264, 0x2267 }, { 0x226A, 0x226B }, { 0x226E, 0x226F }, + { 0x2282, 0x2283 }, { 0x2286, 0x2287 }, { 0x2295, 0x2295 }, + { 0x2299, 0x2299 }, { 0x22A5, 0x22A5 }, { 0x22BF, 0x22BF }, + { 0x2312, 0x2312 }, { 0x2460, 0x24E9 }, { 0x24EB, 0x254B }, + { 0x2550, 0x2573 }, { 0x2580, 0x258F }, { 0x2592, 0x2595 }, + { 0x25A0, 0x25A1 }, { 0x25A3, 0x25A9 }, { 0x25B2, 0x25B3 }, + { 0x25B6, 0x25B7 }, { 0x25BC, 0x25BD }, { 0x25C0, 0x25C1 }, + { 0x25C6, 0x25C8 }, { 0x25CB, 0x25CB }, { 0x25CE, 0x25D1 }, + { 0x25E2, 0x25E5 }, { 0x25EF, 0x25EF }, { 0x2605, 0x2606 }, + { 0x2609, 0x2609 }, { 0x260E, 0x260F }, { 0x2614, 0x2615 }, + { 0x261C, 0x261C }, { 0x261E, 0x261E }, { 0x2640, 0x2640 }, + { 0x2642, 0x2642 }, { 0x2660, 0x2661 }, { 0x2663, 0x2665 }, + { 0x2667, 0x266A }, { 0x266C, 0x266D }, { 0x266F, 0x266F }, + { 0x273D, 0x273D }, { 0x2776, 0x277F }, { 0xE000, 0xF8FF }, + { 0xFFFD, 0xFFFD }, { 0xF0000, 0xFFFFD }, { 0x100000, 0x10FFFD } + }; + + /* binary search in table of non-spacing characters */ + if (bisearch(ucs, ambiguous, + sizeof(ambiguous) / sizeof(struct interval) - 1)) + return 2; + + return mk_wcwidth(ucs); +} + + +int mk_wcswidth_cjk(const boost::uint32_t *pwcs, size_t n) +{ + int w, width = 0; + + for (;*pwcs && n-- > 0; pwcs++) + if ((w = mk_wcwidth_cjk(*pwcs)) < 0) + return -1; + else + width += w; + + return width; +} + +} // namespace ledger diff --git a/src/xact.cc b/src/xact.cc index 7ea15322..58d2ac33 100644 --- a/src/xact.cc +++ b/src/xact.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003-2013, John Wiegley. All rights reserved. + * Copyright (c) 2003-2014, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 94ce0a0a..796ef0a2 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -38,4 +38,16 @@ add_subdirectory(manual) add_subdirectory(baseline) add_subdirectory(regress) +if(PYTHONINTERP_FOUND) + set(_class DocTests) + file(GLOB ${_class}_TESTS ${PROJECT_SOURCE_DIR}/doc/*.texi) + foreach(TestFile ${${_class}_TESTS}) + get_filename_component(TestFile_Name ${TestFile} NAME_WE) + add_test(${_class}Test_${TestFile_Name} + ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/test/DocTests.py + --ledger ${LEDGER_LOCATION} --file ${TestFile}) + set_target_properties(check PROPERTIES DEPENDS ${_class}Test_${TestFile_Name}) + endforeach() +endif() + ### CMakeLists.txt ends here diff --git a/test/DocTests.py b/test/DocTests.py new file mode 100755 index 00000000..d2931686 --- /dev/null +++ b/test/DocTests.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os +import re +import sys +import hashlib +import argparse +import subprocess + +from difflib import unified_diff + +class DocTests: + def __init__(self, args): + scriptpath = os.path.dirname(os.path.realpath(__file__)) + self.ledger = os.path.abspath(args.ledger) + self.sourcepath = os.path.abspath(args.file) + self.verbose = args.verbose + + self.examples = dict() + self.test_files = list() + self.testin_token = 'command' + self.testout_token = 'output' + self.testdat_token = 'input' + self.validate_token = 'validate' + self.testwithdat_token = 'with_input' + + def read_example(self): + endexample = re.compile(r'^@end\s+smallexample\s*$') + example = str() + while True: + line = self.file.readline() + self.current_line += 1 + if len(line) <= 0 or endexample.match(line): break + example += line.replace("@@","@").replace("@{","{").replace("@}","}") + return example + + def test_id(self, example): + return hashlib.sha1(example.rstrip()).hexdigest()[0:7].upper() + + def find_examples(self): + startexample = re.compile(r'^@smallexample\s+@c\s+(%s|%s|%s)(?::([\dA-Fa-f]+|validate))?(?:,(.*))?' + % (self.testin_token, self.testout_token, self.testdat_token)) + while True: + line = self.file.readline() + self.current_line += 1 + if len(line) <= 0: break + + startmatch = startexample.match(line) + if (startmatch): + test_begin_pos = self.file.tell() + test_begin_line = self.current_line + test_kind = startmatch.group(1) + test_id = startmatch.group(2) + test_options = dict() + for pair in re.split(r',\s*', str(startmatch.group(3))): + kv = re.split(r':\s*', pair, 2) + try: + test_options[kv[0]] = kv[1] + except IndexError: + pass + example = self.read_example() + test_end_pos = self.file.tell() + test_end_line = self.current_line + + if not test_id: + print >> sys.stderr, 'Example', test_kind, 'in line', test_begin_line, 'is missing id.' + test_id = self.test_id(example) + if test_kind == self.testin_token: + print >> sys.stderr, 'Use', self.test_id(example) + elif test_kind == self.testin_token and test_id != self.validate_token and test_id != self.test_id(example): + print >> sys.stderr, 'Expected test id', test_id, 'for example' \ + , test_kind, 'on line', test_begin_line, 'to be', self.test_id(example) + + if test_id == self.validate_token: + test_id = "Val-" + str(test_begin_line) + if test_kind == self.testin_token: + test_kind = "validate-command" + elif test_kind == self.testdat_token: + test_kind = "validate-data" + try: + self.examples[test_id] + except KeyError: + self.examples[test_id] = dict() + + try: + example = self.examples[test_id][test_kind][test_kind] + example + except KeyError: + pass + + self.examples[test_id][test_kind] = { + 'bpos': test_begin_pos, + 'epos': test_end_pos, + 'blin': test_begin_line, + 'elin': test_end_line, + 'opts': test_options, + test_kind: example, + } + + def parse_command(self, test_id, example): + validate_command = False + try: + command = example[self.testin_token][self.testin_token] + except KeyError: + if 'validate-data' in example: + command = '$ ledger bal' + elif 'validate-command' in example: + validate_command = True + command = example['validate-command']['validate-command'] + else: + return None + + command = command.rstrip().split() + if command[0] == '$': command.remove('$') + index = command.index('ledger') + command[index] = self.ledger + command.insert(index+1, '--init-file') + command.insert(index+2, '/dev/null') + try: + findex = command.index('-f') + except ValueError: + try: + findex = command.index('--file') + except ValueError: + findex = index+1 + command.insert(findex, '--file') + if validate_command: + command.insert(findex+1, 'sample.dat') + else: + command.insert(findex+1, test_id + '.dat') + return (command, findex+1) + + def test_examples(self): + failed = set() + for test_id in self.examples: + validation = False + if "validate-data" in self.examples[test_id] or "validate-command" in self.examples[test_id]: + validation = True + example = self.examples[test_id] + try: + (command, findex) = self.parse_command(test_id, example) + except TypeError: + failed.add(test_id) + continue + + try: + output = example[self.testout_token][self.testout_token] + except KeyError: + output = None + + try: + input = example[self.testdat_token][self.testdat_token] + except KeyError: + try: + with_input = example[self.testin_token]['opts'][self.testwithdat_token] + input = self.examples[with_input][self.testdat_token][self.testdat_token] + except KeyError: + try: + input = example['validate-data']['validate-data'] + except KeyError: + input = None + + if command and (output or validation): + test_file_created = False + if findex: + scriptpath = os.path.dirname(os.path.realpath(__file__)) + test_input_dir = scriptpath + '/../test/input/' + test_file = command[findex] + if not os.path.exists(test_file): + if input: + test_file_created = True + with open(test_file, 'w') as f: + f.write(input) + elif os.path.exists(test_input_dir + test_file): + command[findex] = test_input_dir + test_file + error = False + try: + verify = subprocess.check_output(command) + except: + verify = str() + error = True + valid = (output == verify) or (not error and validation) + if valid and test_file_created: + os.remove(test_file) + if self.verbose > 0: + print test_id, ':', 'Passed' if valid else 'FAILED' + else: + sys.stdout.write('.' if valid else 'E') + + if not valid: + failed.add(test_id) + if self.verbose > 1: + print ' '.join(command) + if not validation: + for line in unified_diff(output.split('\n'), verify.split('\n'), fromfile='generated', tofile='expected'): + print(line) + print + if not self.verbose: + print + if len(failed) > 0: + print "\nThe following examples failed:" + print " ", "\n ".join(failed) + return len(failed) + + def main(self): + self.file = open(self.sourcepath) + self.current_line = 0 + self.find_examples() + failed_examples = self.test_examples() + self.file.close() + return failed_examples + +if __name__ == "__main__": + def getargs(): + parser = argparse.ArgumentParser(description='DocTests', prefix_chars='-') + parser.add_argument('-v', '--verbose', + dest='verbose', + action='count', + help='be verbose. Add -vv for more verbosity') + parser.add_argument('-l', '--ledger', + dest='ledger', + type=str, + action='store', + required=True, + help='the path to the ledger executable to test with') + parser.add_argument('-f', '--file', + dest='file', + type=str, + action='store', + required=True, + help='the texinfo documentation file to run the examples from') + return parser.parse_args() + + args = getargs() + script = DocTests(args) + status = script.main() + sys.exit(status) diff --git a/test/baseline/dir-alias-fail.test b/test/baseline/dir-alias-fail.test new file mode 100644 index 00000000..e063a330 --- /dev/null +++ b/test/baseline/dir-alias-fail.test @@ -0,0 +1,12 @@ +--pedantic +--explicit +alias Foo=Foo + +2011-01-01 Test + Foo 10 EUR + Bar +test source -> 1 +__ERROR__ +While parsing file "$FILE", line 3: +Error: Illegal alias Foo=Foo +end test diff --git a/test/baseline/dir-alias-recursive.test b/test/baseline/dir-alias-recursive.test new file mode 100644 index 00000000..d9addcd1 --- /dev/null +++ b/test/baseline/dir-alias-recursive.test @@ -0,0 +1,12 @@ +alias A=B:A +alias B=C:B +alias C=D:C + +2001-01-01 Test + A 10 EUR + Foo + +test reg --recursive-aliases +01-Jan-01 Test D:C:B:A 10 EUR 10 EUR + Foo -10 EUR 0 +end test diff --git a/test/baseline/dir-alias.test b/test/baseline/dir-alias.test new file mode 100644 index 00000000..6245d944 --- /dev/null +++ b/test/baseline/dir-alias.test @@ -0,0 +1,13 @@ +alias A=B:A +alias B=C:B +alias C=D:C + +2001-01-01 Test + A 10 EUR + Foo + +test reg +01-Jan-01 Test B:A 10 EUR 10 EUR + Foo -10 EUR 0 +end test + diff --git a/test/input/drewr3.dat b/test/input/drewr3.dat index e72ccd70..0e16466b 100644 --- a/test/input/drewr3.dat +++ b/test/input/drewr3.dat @@ -69,15 +69,4 @@ end tag Income:Sales end tag -apply account Expenses -bucket Assets:Checking -2011/04/25 Tom's Used Cars - Auto $ 5,500.00 - ; :nobudget: - -end account -apply payee Amazon.com B.*k Store - -2011/04/27 Book Store - Books $20.00 diff --git a/test/regress/6E7C2DF9.test b/test/regress/6E7C2DF9.test new file mode 100644 index 00000000..c55fbdcc --- /dev/null +++ b/test/regress/6E7C2DF9.test @@ -0,0 +1,24 @@ +Y 2010 +10/10 * TwentyTen + Account:Ten $ 10.10 + Assets:Cash + +apply year 2011 +11/11 * TwentyEleven + Account:Eleven $ 11.11 + Assets:Cash + +2012/12/12 * TwentyTwelve + Account:Twelve $ 12.12 + Assets:Cash + +11/11 * TwentyEleven Again + Account:Eleven $ 11.11 + Assets:Cash + +test reg --sort date account +10-Oct-10 TwentyTen Account:Ten $ 10.10 $ 10.10 +11-Nov-11 TwentyEleven Account:Eleven $ 11.11 $ 21.21 +11-Nov-11 TwentyEleven Again Account:Eleven $ 11.11 $ 32.32 +12-Dec-12 TwentyTwelve Account:Twelve $ 12.12 $ 44.44 +end test diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 5ecd5a87..b3639c06 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -1,5 +1,5 @@ macro(add_ledger_test _name) - add_ledger_library_dependencies(${_name}) + target_link_libraries(${_name} libledger) add_test(Ledger${_name} ${PROJECT_BINARY_DIR}/${_name}) endmacro(add_ledger_test _name) diff --git a/tools/spellcheck.sh b/tools/spellcheck.sh index ae86a3d6..7a51a18d 100755 --- a/tools/spellcheck.sh +++ b/tools/spellcheck.sh @@ -1,3 +1,3 @@ #!/bin/sh -aspell check --mode=texinfo ledger3.texi
\ No newline at end of file +aspell check --mode=texinfo $(dirname $0)/../doc/ledger3.texi |