Automatically Sort and Align Ledger Transactions in VIM

One of my goals for 2018 is to track all of my finances using plaintextaccounting.
For now, I am using ledger-cli and vim.

I won't go into detail on how to use ledger or plaintextaccount in this post, but wanted to share a quick tip. Ledger
files can quickly grow in size, and if you have multiple accounts you may not enter transactions in the correct order.
By default, Ledger processes transactions in the order it sees them - not by the date of the transaction.

Here is what I'm currently using.

  • The vim-ledger vim plugin.
  • These settings and this function in my .vimrc:
" For ledger
au BufNewFile,BufRead *.ldg,*.ledger setf ledger | comp ledger
let g:ledger_maxwidth = 120
let g:ledger_fold_blanks = 1
function LedgerSort()
    :%! ledger -f - print --sort 'date, amount'
    :%LedgerAlign
endfunction
command LedgerSort call LedgerSort()

LedgerSort essentially just passes the entire file to ledger print,
and then uses the LedgerAlign function from the vim-ledger plugin to
align all of the dollar amounts on the right.

Now I add my new transactions at the bottom of a ledger file, not worrying about the order, and then run :LedgerSort when done to order
and format the new transactions. Having your file version-controlled makes it a lot easier to see the differences, so that you know where
the transactions were moved to in the file (if they were out of order).

One caveat is that ledger print doesn't preserve everything in a ledger file. I haven't run into an issue with it yet, but I did
notice it doesn't preserve certain things like comments outside of a transaction. Metadata inside a transaction is still preserved though.