1 " Vim completion script
3 " Maintainer: Bram Moolenaar <Bram@vim.org>
4 " Last Change: 2006 May 08
7 " This function is used for the 'omnifunc' option.
8 function! ccomplete#Complete(findstart, base)
10 " Locate the start of the item, including ".", "->" and "[...]".
11 let line = getline('.')
12 let start = col('.') - 1
15 if line[start - 1] =~ '\w'
17 elseif line[start - 1] =~ '\.'
22 elseif start > 1 && line[start - 2] == '-' && line[start - 1] == '>'
27 elseif line[start - 1] == ']'
38 elseif line[start] == ']' " nested []
47 " Return the column of the last word, which is going to be changed.
48 " Remember the text that comes before it in s:prepended.
53 let s:prepended = strpart(line, start, lastword - start)
57 " Return list of matches.
59 let base = s:prepended . a:base
61 " Don't do anything for an empty base, would result in all the tags in the
67 " init cache for vimgrep to empty
70 " Split item in words, keep empty word after "." or "->".
71 " "aa" -> ['aa'], "aa." -> ['aa', ''], "aa.bb" -> ['aa', 'bb'], etc.
72 " We can't use split, because we need to skip nested [...].
76 let e = match(base, '\.\|->\|\[', s)
78 if s == 0 || base[s - 1] != ']'
79 call add(items, strpart(base, s))
83 if s == 0 || base[s - 1] != ']'
84 call add(items, strpart(base, s, e - s))
87 let s = e + 1 " skip over '.'
89 let s = e + 2 " skip over '->'
101 elseif base[e] == '[' " nested [...]
107 call add(items, strpart(base, s, e - s))
112 " Find the variable items[0].
113 " 1. in current function (like with "gd")
114 " 2. in tags file(s) (like with ":tag")
115 " 3. in current file (like with "gD")
117 if searchdecl(items[0], 0, 1) == 0
118 " Found, now figure out the type.
119 " TODO: join previous line if it makes sense
120 let line = getline('.')
123 " Completing one word and it's a local variable: May add '[', '.' or
127 if match(line, '\<' . match . '\s*\[') > 0
130 let res = s:Nextitem(strpart(line, 0, col), [''], 0, 1)
132 " There are members, thus add "." or "->".
133 if match(line, '\*[ \t(]*' . match . '\>') > 0
140 let res = [{'match': match, 'tagline' : '', 'kind' : kind, 'info' : line}]
142 " Completing "var.", "var.something", etc.
143 let res = s:Nextitem(strpart(line, 0, col), items[1:], 0, 1)
148 " Only one part, no "." or "->": complete from tags file.
149 let tags = taglist('^' . base)
151 " Remove members, these can't appear without something in front.
152 call filter(tags, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1')
154 " Remove static matches in other files.
155 call filter(tags, '!has_key(v:val, "static") || !v:val["static"] || bufnr("%") == bufnr(v:val["filename"])')
157 call extend(res, map(tags, 's:Tag2item(v:val)'))
161 " Find the variable in the tags file(s)
162 let diclist = taglist('^' . items[0] . '$')
164 " Remove members, these can't appear without something in front.
165 call filter(diclist, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1')
168 for i in range(len(diclist))
169 " New ctags has the "typeref" field. Patched version has "typename".
170 if has_key(diclist[i], 'typename')
171 call extend(res, s:StructMembers(diclist[i]['typename'], items[1:], 1))
172 elseif has_key(diclist[i], 'typeref')
173 call extend(res, s:StructMembers(diclist[i]['typeref'], items[1:], 1))
176 " For a variable use the command, which must be a search pattern that
177 " shows the declaration of the variable.
178 if diclist[i]['kind'] == 'v'
179 let line = diclist[i]['cmd']
180 if line[0] == '/' && line[1] == '^'
181 let col = match(line, '\<' . items[0] . '\>')
182 call extend(res, s:Nextitem(strpart(line, 2, col - 2), items[1:], 0, 1))
188 if len(res) == 0 && searchdecl(items[0], 1) == 0
189 " Found, now figure out the type.
190 " TODO: join previous line if it makes sense
191 let line = getline('.')
193 let res = s:Nextitem(strpart(line, 0, col), items[1:], 0, 1)
196 " If the last item(s) are [...] they need to be added to the matches.
197 let last = len(items) - 1
200 if items[last][0] != '['
203 let brackets = items[last] . brackets
207 return map(res, 's:Tagline2item(v:val, brackets)')
210 function! s:GetAddition(line, match, memarg, bracket)
211 " Guess if the item is an array.
212 if a:bracket && match(a:line, a:match . '\s*\[') > 0
216 " Check if the item has members.
217 if len(s:SearchMembers(a:memarg, [''], 0)) > 0
218 " If there is a '*' before the name use "->".
219 if match(a:line, '\*[ \t(]*' . a:match . '\>') > 0
228 " Turn the tag info "val" into an item for completion.
229 " "val" is is an item in the list returned by taglist().
230 " If it is a variable we may add "." or "->". Don't do it for other types,
231 " such as a typedef, by not including the info that s:GetAddition() uses.
232 function! s:Tag2item(val)
233 let res = {'match': a:val['name']}
235 let res['extra'] = s:Tagcmd2extra(a:val['cmd'], a:val['name'], a:val['filename'])
237 let s = s:Dict2info(a:val)
242 let res['tagline'] = ''
243 if has_key(a:val, "kind")
244 let kind = a:val['kind']
245 let res['kind'] = kind
247 let res['tagline'] = "\t" . a:val['cmd']
248 let res['dict'] = a:val
250 let res['match'] = a:val['name'] . '('
257 " Use all the items in dictionary for the "info" entry.
258 function! s:Dict2info(dict)
260 for k in sort(keys(a:dict))
261 let info .= k . repeat(' ', 10 - len(k))
263 let info .= substitute(matchstr(a:dict['cmd'], '/^\s*\zs.*\ze$/'), '\\\(.\)', '\1', 'g')
265 let info .= a:dict[k]
272 " Parse a tag line and return a dictionary with items like taglist()
273 function! s:ParseTagline(line)
274 let l = split(a:line, "\t")
278 let d['filename'] = l[1]
282 " Find end of cmd, it may contain Tabs.
283 while n < len(l) && l[n] !~ '/;"$'
285 let d['cmd'] .= " " . l[n]
288 for i in range(n + 1, len(l) - 1)
294 let d[matchstr(l[i], '[^:]*')] = matchstr(l[i], ':\zs.*')
302 " Turn a match item "val" into an item for completion.
303 " "val['match']" is the matching item.
304 " "val['tagline']" is the tagline in which the last part was found.
305 function! s:Tagline2item(val, brackets)
306 let line = a:val['tagline']
307 let add = s:GetAddition(line, a:val['match'], [a:val], a:brackets == '')
308 let res = {'word': a:val['match'] . a:brackets . add }
310 if has_key(a:val, 'info')
311 " Use info from Tag2item().
312 let res['info'] = a:val['info']
314 " Parse the tag line and add each part to the "info" entry.
315 let s = s:Dict2info(s:ParseTagline(line))
321 if has_key(a:val, 'kind')
322 let res['kind'] = a:val['kind']
324 let res['kind'] = 'f'
326 let s = matchstr(line, '\t\(kind:\)\=\zs\S\ze\(\t\|$\)')
332 if has_key(a:val, 'extra')
333 let res['menu'] = a:val['extra']
337 " Isolate the command after the tag and filename.
338 let s = matchstr(line, '[^\t]*\t[^\t]*\t\zs\(/^.*$/\|[^\t]*\)\ze\(;"\t\|\t\|$\)')
340 let res['menu'] = s:Tagcmd2extra(s, a:val['match'], matchstr(line, '[^\t]*\t\zs[^\t]*\ze\t'))
345 " Turn a command from a tag line to something that is useful in the menu
346 function! s:Tagcmd2extra(cmd, name, fname)
348 " The command is a search command, useful to see what it is.
349 let x = matchstr(a:cmd, '^/^\s*\zs.*\ze$/')
350 let x = substitute(x, '\<' . a:name . '\>', '@@', '')
351 let x = substitute(x, '\\\(.\)', '\1', 'g')
352 let x = x . ' - ' . a:fname
353 elseif a:cmd =~ '^\d*$'
354 " The command is a line number, the file name is more useful.
355 let x = a:fname . ' - ' . a:cmd
357 " Not recognized, use command and file name.
358 let x = a:cmd . ' - ' . a:fname
363 " Find composing type in "lead" and match items[0] with it.
364 " Repeat this recursively for items[1], if it's there.
365 " When resolving typedefs "depth" is used to avoid infinite recursion.
366 " Return the list of matches.
367 function! s:Nextitem(lead, items, depth, all)
369 " Use the text up to the variable name and split it in tokens.
370 let tokens = split(a:lead, '\s\+\|\<')
372 " Try to recognize the type of the variable. This is rough guessing...
374 for tidx in range(len(tokens))
376 " Skip tokens starting with a non-ID character.
377 if tokens[tidx] !~ '^\h'
381 " Recognize "struct foobar" and "union foobar".
382 " Also do "class foobar" when it's C++ after all (doesn't work very well
384 if (tokens[tidx] == 'struct' || tokens[tidx] == 'union' || tokens[tidx] == 'class') && tidx + 1 < len(tokens)
385 let res = s:StructMembers(tokens[tidx] . ':' . tokens[tidx + 1], a:items, a:all)
389 " TODO: add more reserved words
390 if index(['int', 'short', 'char', 'float', 'double', 'static', 'unsigned', 'extern'], tokens[tidx]) >= 0
394 " Use the tags file to find out if this is a typedef.
395 let diclist = taglist('^' . tokens[tidx] . '$')
396 for tagidx in range(len(diclist))
397 let item = diclist[tagidx]
399 " New ctags has the "typeref" field. Patched version has "typename".
400 if has_key(item, 'typeref')
401 call extend(res, s:StructMembers(item['typeref'], a:items, a:all))
404 if has_key(item, 'typename')
405 call extend(res, s:StructMembers(item['typename'], a:items, a:all))
409 " Only handle typedefs here.
410 if item['kind'] != 't'
414 " Skip matches local to another file.
415 if has_key(item, 'static') && item['static'] && bufnr('%') != bufnr(item['filename'])
419 " For old ctags we recognize "typedef struct aaa" and
420 " "typedef union bbb" in the tags file command.
421 let cmd = item['cmd']
422 let ei = matchend(cmd, 'typedef\s\+')
424 let cmdtokens = split(strpart(cmd, ei), '\s\+\|\<')
425 if len(cmdtokens) > 1
426 if cmdtokens[0] == 'struct' || cmdtokens[0] == 'union' || cmdtokens[0] == 'class'
428 " Use the first identifier after the "struct" or "union"
429 for ti in range(len(cmdtokens) - 1)
430 if cmdtokens[ti] =~ '^\w'
431 let name = cmdtokens[ti]
436 call extend(res, s:StructMembers(cmdtokens[0] . ':' . name, a:items, a:all))
439 " Could be "typedef other_T some_T".
440 call extend(res, s:Nextitem(cmdtokens[0], a:items, a:depth + 1, a:all))
454 " Search for members of structure "typename" in tags files.
455 " Return a list with resulting matches.
456 " Each match is a dictionary with "match" and "tagline" entries.
457 " When "all" is non-zero find all, otherwise just return 1 if there is any
459 function! s:StructMembers(typename, items, all)
460 " Todo: What about local structures?
461 let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")'))
466 let typename = a:typename
470 let n = '1' " stop at first found match
471 if has_key(s:grepCache, a:typename)
472 let qflist = s:grepCache[a:typename]
480 exe 'silent! ' . n . 'vimgrep /\t' . typename . '\(\t\|$\)/j ' . fnames
482 let qflist = getqflist()
483 if len(qflist) > 0 || match(typename, "::") < 0
486 " No match for "struct:context::name", remove "context::" and try again.
487 let typename = substitute(typename, ':[^:]*::', ':', '')
491 " Store the result to be able to use it again later.
492 let s:grepCache[a:typename] = qflist
496 " Put matching members in matches[].
499 let memb = matchstr(l['text'], '[^\t]*')
500 if memb =~ '^' . a:items[0]
501 " Skip matches local to another file.
502 if match(l['text'], "\tfile:") < 0 || bufnr('%') == bufnr(matchstr(l['text'], '\t\zs[^\t]*'))
503 let item = {'match': memb, 'tagline': l['text']}
505 " Add the kind of item.
506 let s = matchstr(l['text'], '\t\(kind:\)\=\zs\S\ze\(\t\|$\)')
510 let item['match'] = memb . '('
514 call add(matches, item)
520 " Skip over [...] items
523 if idx >= len(a:items)
524 return matches " No further items, return the result.
526 if a:items[idx][0] != '['
532 " More items following. For each of the possible members find the
533 " matching following members.
534 return s:SearchMembers(matches, a:items[idx :], a:all)
537 " Failed to find anything.
541 " For matching members, find matches for following items.
542 " When "all" is non-zero find all, otherwise just return 1 if there is any
544 function! s:SearchMembers(matches, items, all)
546 for i in range(len(a:matches))
548 if has_key(a:matches[i], 'dict')
549 if has_key(a:matches[i].dict, 'typename')
550 let typename = a:matches[i].dict['typename']
551 elseif has_key(a:matches[i].dict, 'typeref')
552 let typename = a:matches[i].dict['typeref']
554 let line = "\t" . a:matches[i].dict['cmd']
556 let line = a:matches[i]['tagline']
557 let e = matchend(line, '\ttypename:')
559 let e = matchend(line, '\ttyperef:')
563 let typename = matchstr(line, '[^\t]*', e)
568 call extend(res, s:StructMembers(typename, a:items, a:all))
570 " Use the search command (the declaration itself).
571 let s = match(line, '\t\zs/^')
573 let e = match(line, '\<' . a:matches[i]['match'] . '\>', s)
575 call extend(res, s:Nextitem(strpart(line, s, e - s), a:items, 0, a:all))
579 if a:all == 0 && len(res) > 0