robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqMerge pull request #40228 from zeertzjq/vim-ff7fcb8710431c696

master
7.2 KiB215 linesraw
1" Vim completion script
2" Language: beancount
3" Maintainer: Nathan Grigg
4" Latest Revision: 2021-03-06
5
6let s:using_python3 = has('python3') || has('python3/dyn')
7
8" Equivalent to python's startswith
9" Matches based on user's ignorecase preference
10function! s:startswith(string, prefix) abort
11    return strpart(a:string, 0, strlen(a:prefix)) == a:prefix
12endfunction
13
14function! s:count_expression(text, expression) abort
15    return len(split(a:text, a:expression, 1)) - 1
16endfunction
17
18function! 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
22endfunction
23
24let s:directives = ['open', 'close', 'commodity', 'txn', 'balance', 'pad', 'note', 'document', 'price', 'event', 'query', 'custom']
25
26" ------------------------------
27" Completion functions
28" ------------------------------
29function! 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
78endfunction
79
80function! beancountcomplete#get_root() abort
81    if exists('b:beancount_root')
82        return b:beancount_root
83    endif
84    return expand('%')
85endfunction
86
87function! beancountcomplete#load_everything() abort
88    if s:using_python3 && !exists('b:beancount_loaded')
89        let l:root = beancountcomplete#get_root()
90python3 << EOF
91import vim
92from beancount import loader
93from beancount.core import data
94
95accounts = set()
96currencies = set()
97events = set()
98links = set()
99payees = set()
100tags = set()
101
102entries, errors, options_map = loader.load_file(vim.eval('l:root'))
103for 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
120vim.bindeval('b:')['beancount_accounts'] = sorted(accounts)
121vim.bindeval('b:')['beancount_currencies'] = sorted(currencies)
122vim.bindeval('b:')['beancount_events'] = sorted(events)
123vim.bindeval('b:')['beancount_links'] = sorted(links)
124vim.bindeval('b:')['beancount_payees'] = sorted(payees)
125vim.bindeval('b:')['beancount_tags'] = sorted(tags)
126vim.bindeval('b:')['beancount_loaded'] = 1
127EOF
128    endif
129endfunction
130
131function! 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
136endfunction
137
138function! 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
143endfunction
144
145function! 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
150endfunction
151
152function! 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
157endfunction
158
159function! 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
164endfunction
165
166" General completion function
167function! 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')
171endfunction
172
173" Complete account name.
174function! 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
194endfunction
195
196function! beancountcomplete#query_single(root_file, query) abort
197    if s:using_python3
198python3 << EOF
199import vim
200import subprocess
201
202# We intentionally want to ignore stderr so it doesn't mess up our query processing
203output = subprocess.check_output(
204    ['bean-query', vim.eval('a:root_file'), vim.eval('a:query')],
205    stderr=subprocess.DEVNULL,
206    text=True,
207).splitlines()
208output = output[2:]
209result_list = sorted(y for y in (x.strip() for x in output) if y)
210EOF
211        return py3eval('result_list')
212    else
213        return []
214    endif
215endfunction