Skip to content

Instantly share code, notes, and snippets.

@kljohann
Created July 22, 2013 18:58
Show Gist options
  • Save kljohann/6056539 to your computer and use it in GitHub Desktop.
Save kljohann/6056539 to your computer and use it in GitHub Desktop.
Join transactions in a ledger file. All transaction metadata will be transferred to the first transaction. Postings of other transactions will be lost. I use this to reconcile auto-generated (by converting from CSV) postings.
function! LedgerJoinTransactions(begin, end)
let xacts = ledger#transactions(a:begin, a:end)
if len(xacts) < 2
return
endif
let target = remove(xacts, 0)
call reverse(xacts)
" safe view / position
let view = winsaveview()
let fe = &foldenable
set nofoldenable
let save_register = @s
normal! qsq
let date = split(target.date, '=')
" TODO: set ignorecase, smartcase and magic for search()
for src in xacts
call cursor(src.head, 0)
let posting = search('^\s\+[^[:blank:];]', 'nW', src.tail)
let meta_start = src.head + 1
let meta_count = posting - meta_start
if meta_count < 1
continue
endif
silent execute 'keepjumps :'.meta_start.'yank S '.meta_count
silent execute 'keepjumps :'.src.head.','.prevnonblank(src.tail).'delete _'
if len(date) < 2 && get(src, 'state', '') == '*' && !empty(src.date)
call add(date, split(src.date, '=')[0])
endif
endfor
let @s = @s[1:] " delete first CR
silent execute 'keepjumps :'.target.head.'put s'
if len(filter(copy(xacts), 'get(v:val, "state", "") == "*"')) == len(xacts)
let target.state = '*'
endif
let target.date = join(date[0:1], '=')
call setline(target.head, target.format_head())
" restore view / position
let &foldenable = fe
let @s = save_register
call winrestview(view)
endf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment