vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

beancountcomplete.vim (7372B)


      1 " Vim completion script
      2 " Language: beancount
      3 " Maintainer: Nathan Grigg
      4 " Latest Revision: 2021-03-06
      5 
      6 let s:using_python3 = has('python3') || has('python3/dyn')
      7 
      8 " Equivalent to python's startswith
      9 " Matches based on user's ignorecase preference
     10 function! s:startswith(string, prefix) abort
     11     return strpart(a:string, 0, strlen(a:prefix)) == a:prefix
     12 endfunction
     13 
     14 function! s:count_expression(text, expression) abort
     15     return len(split(a:text, a:expression, 1)) - 1
     16 endfunction
     17 
     18 function! s:sort_accounts_by_depth(name1, name2) abort
     19     let l:depth1 = s:count_expression(a:name1, ':')
     20     let l:depth2 = s:count_expression(a:name2, ':')
     21     return l:depth1 == l:depth2 ? 0 : l:depth1 > l:depth2 ? 1 : -1
     22 endfunction
     23 
     24 let s:directives = ['open', 'close', 'commodity', 'txn', 'balance', 'pad', 'note', 'document', 'price', 'event', 'query', 'custom']
     25 
     26 " ------------------------------
     27 " Completion functions
     28 " ------------------------------
     29 function! beancountcomplete#complete(findstart, base) abort
     30     if a:findstart
     31         let l:col = searchpos('\s', 'bn', line('.'))[1]
     32         if l:col == 0
     33             return -1
     34         else
     35             return l:col
     36         endif
     37     endif
     38 
     39     let l:partial_line = strpart(getline('.'), 0, getpos('.')[2]-1)
     40     " Match directive types
     41     if l:partial_line =~# '^\d\d\d\d\(-\|/\)\d\d\1\d\d $'
     42         return beancountcomplete#complete_basic(s:directives, a:base, '')
     43     endif
     44 
     45     " If we are using python3, now is a good time to load everything
     46     call beancountcomplete#load_everything()
     47 
     48     " Split out the first character (for cases where we don't want to match the
     49     " leading character: ", #, etc)
     50     let l:first = strpart(a:base, 0, 1)
     51     let l:rest = strpart(a:base, 1)
     52 
     53     if l:partial_line =~# '^\d\d\d\d\(-\|/\)\d\d\1\d\d event $' && l:first ==# '"'
     54         return beancountcomplete#complete_basic(b:beancount_events, l:rest, '"')
     55     endif
     56 
     57     let l:two_tokens = searchpos('\S\+\s', 'bn', line('.'))[1]
     58     let l:prev_token = strpart(getline('.'), l:two_tokens, getpos('.')[2] - l:two_tokens)
     59     " Match curriences if previous token is number
     60     if l:prev_token =~# '^\d\+\([\.,]\d\+\)*'
     61         call beancountcomplete#load_currencies()
     62         return beancountcomplete#complete_basic(b:beancount_currencies, a:base, '')
     63     endif
     64 
     65     if l:first ==# '#'
     66         call beancountcomplete#load_tags()
     67         return beancountcomplete#complete_basic(b:beancount_tags, l:rest, '#')
     68     elseif l:first ==# '^'
     69         call beancountcomplete#load_links()
     70         return beancountcomplete#complete_basic(b:beancount_links, l:rest, '^')
     71     elseif l:first ==# '"'
     72         call beancountcomplete#load_payees()
     73         return beancountcomplete#complete_basic(b:beancount_payees, l:rest, '"')
     74     else
     75         call beancountcomplete#load_accounts()
     76         return beancountcomplete#complete_account(a:base)
     77     endif
     78 endfunction
     79 
     80 function! beancountcomplete#get_root() abort
     81     if exists('b:beancount_root')
     82         return b:beancount_root
     83     endif
     84     return expand('%')
     85 endfunction
     86 
     87 function! beancountcomplete#load_everything() abort
     88     if s:using_python3 && !exists('b:beancount_loaded')
     89         let l:root = beancountcomplete#get_root()
     90 python3 << EOF
     91 import vim
     92 from beancount import loader
     93 from beancount.core import data
     94 
     95 accounts = set()
     96 currencies = set()
     97 events = set()
     98 links = set()
     99 payees = set()
    100 tags = set()
    101 
    102 entries, errors, options_map = loader.load_file(vim.eval('l:root'))
    103 for index, entry in enumerate(entries):
    104     if isinstance(entry, data.Open):
    105         accounts.add(entry.account)
    106         if entry.currencies:
    107             currencies.update(entry.currencies)
    108     elif isinstance(entry, data.Commodity):
    109         currencies.add(entry.currency)
    110     elif isinstance(entry, data.Event):
    111         events.add(entry.type)
    112     elif isinstance(entry, data.Transaction):
    113         if entry.tags:
    114             tags.update(entry.tags)
    115         if entry.links:
    116             links.update(entry.links)
    117         if entry.payee:
    118             payees.add(entry.payee)
    119 
    120 vim.bindeval('b:')['beancount_accounts'] = sorted(accounts)
    121 vim.bindeval('b:')['beancount_currencies'] = sorted(currencies)
    122 vim.bindeval('b:')['beancount_events'] = sorted(events)
    123 vim.bindeval('b:')['beancount_links'] = sorted(links)
    124 vim.bindeval('b:')['beancount_payees'] = sorted(payees)
    125 vim.bindeval('b:')['beancount_tags'] = sorted(tags)
    126 vim.bindeval('b:')['beancount_loaded'] = 1
    127 EOF
    128     endif
    129 endfunction
    130 
    131 function! beancountcomplete#load_accounts() abort
    132     if !s:using_python3 && !exists('b:beancount_accounts')
    133         let l:root = beancountcomplete#get_root()
    134         let b:beancount_accounts = beancountcomplete#query_single(l:root, 'select distinct account;')
    135     endif
    136 endfunction
    137 
    138 function! beancountcomplete#load_tags() abort
    139     if !s:using_python3 && !exists('b:beancount_tags')
    140         let l:root = beancountcomplete#get_root()
    141         let b:beancount_tags = beancountcomplete#query_single(l:root, 'select distinct tags;')
    142     endif
    143 endfunction
    144 
    145 function! beancountcomplete#load_links() abort
    146     if !s:using_python3 && !exists('b:beancount_links')
    147         let l:root = beancountcomplete#get_root()
    148         let b:beancount_links = beancountcomplete#query_single(l:root, 'select distinct links;')
    149     endif
    150 endfunction
    151 
    152 function! beancountcomplete#load_currencies() abort
    153     if !s:using_python3 && !exists('b:beancount_currencies')
    154         let l:root = beancountcomplete#get_root()
    155         let b:beancount_currencies = beancountcomplete#query_single(l:root, 'select distinct currency;')
    156     endif
    157 endfunction
    158 
    159 function! beancountcomplete#load_payees() abort
    160     if !s:using_python3 && !exists('b:beancount_payees')
    161         let l:root = beancountcomplete#get_root()
    162         let b:beancount_payees = beancountcomplete#query_single(l:root, 'select distinct payee;')
    163     endif
    164 endfunction
    165 
    166 " General completion function
    167 function! beancountcomplete#complete_basic(input, base, prefix) abort
    168     let l:matches = filter(copy(a:input), 's:startswith(v:val, a:base)')
    169 
    170     return map(l:matches, 'a:prefix . v:val')
    171 endfunction
    172 
    173 " Complete account name.
    174 function! beancountcomplete#complete_account(base) abort
    175     if g:beancount_account_completion ==? 'chunks'
    176         let l:pattern = '^\V' . substitute(a:base, ':', '\\[^:]\\*:', 'g') . '\[^:]\*'
    177     else
    178         let l:pattern = '^\V\.\*' . substitute(a:base, ':', '\\.\\*:\\.\\*', 'g') . '\.\*'
    179     endif
    180 
    181     let l:matches = []
    182     let l:index = -1
    183     while 1
    184         let l:index = match(b:beancount_accounts, l:pattern, l:index + 1)
    185         if l:index == -1 | break | endif
    186         call add(l:matches, matchstr(b:beancount_accounts[l:index], l:pattern))
    187     endwhile
    188 
    189     if g:beancount_detailed_first
    190         let l:matches = reverse(sort(l:matches, 's:sort_accounts_by_depth'))
    191     endif
    192 
    193     return l:matches
    194 endfunction
    195 
    196 function! beancountcomplete#query_single(root_file, query) abort
    197     if s:using_python3
    198 python3 << EOF
    199 import vim
    200 import subprocess
    201 
    202 # We intentionally want to ignore stderr so it doesn't mess up our query processing
    203 output = subprocess.check_output(
    204     ['bean-query', vim.eval('a:root_file'), vim.eval('a:query')],
    205     stderr=subprocess.DEVNULL,
    206     text=True,
    207 ).splitlines()
    208 output = output[2:]
    209 result_list = sorted(y for y in (x.strip() for x in output) if y)
    210 EOF
    211         return py3eval('result_list')
    212     else
    213         return []
    214     endif
    215 endfunction