I have written a Vim function to clear transactions in a ledger file.
I thought I would share it in case anyone might find it useful. It is
my first Vim script attempt so it may not be perfect. I would
appreciate any feedback!

" Clear (or unclear) a transaction in a ledger file in Vim.
" In any line of a transaction including the date, payee, description
line or
" the account, amount lines, call this function to mark the
transaction as
" cleared (or not cleared).
" Function can be called with a key mapping as below.
" nnoremap <silent> glc :call Ledger_toggle_cleared<CR>
" Author: Chad Voegele
function! Ledger_toggle_cleared() "{{{1
  let keep_line = line('.')
  let keep_col = col('.')
  let top_trans = line('.')
  let cur_line = getline(top_trans)

  " make sure line contains non-white space characters and is not a
comment or
  " include
  if cur_line =~ '\S' && cur_line !~ '\(^!\|^;\)'

    " find the date, payee, description line
    while cur_line !~ '^\(\d\+\/\d\+\/\d\+\|\d\+\/\d\+\)'
      let top_trans = top_trans - 1

      " make sure we don't go past the top of the file
      if top_trans == 0
        break
      endif

      let cur_line = getline(top_trans)
    endwhile

    if top_trans != 0

      " toggle transaction as cleared
      if getline(top_trans) !~ '^\(\d\+\/\d\+\/\d\+\|\d\+\/\d\+\)\s\*'
        execute ':'.top_trans.'s/^\(\d\+\/\d\+\/\d\+\|\d\+\/\d\+\)/&
*/'
        execute ":call cursor(keep_line, keep_col)"
      elseif getline(top_trans) =~ '^\(\d\+\/\d\+\/\d\+\|\d\+\/\d\+\)\s
\*'
        execute ':'.top_trans.'s/*\s//'
        execute ":call cursor(keep_line, keep_col)"
      endif
    endif
  endif
endf

Reply via email to