1 " Vim completion script
3 " Maintainer: Bram Moolenaar <Bram@vim.org>
4 " Last Change: 2007 Aug 30
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('.')
122 if stridx(strpart(line, 0, col), ';') != -1
123 " Handle multiple declarations on the same line.
125 while line[col2] != ';'
128 let line = strpart(line, col2 + 1)
131 if stridx(strpart(line, 0, col), ',') != -1
132 " Handle multiple declarations on the same line in a function
135 while line[col2] != ','
138 if strpart(line, col2 + 1, col - col2 - 1) =~ ' *[^ ][^ ]* *[^ ]'
139 let line = strpart(line, col2 + 1)
144 " Completing one word and it's a local variable: May add '[', '.' or
148 if match(line, '\<' . match . '\s*\[') > 0
151 let res = s:Nextitem(strpart(line, 0, col), [''], 0, 1)
153 " There are members, thus add "." or "->".
154 if match(line, '\*[ \t(]*' . match . '\>') > 0
161 let res = [{'match': match, 'tagline' : '', 'kind' : kind, 'info' : line}]
163 " Completing "var.", "var.something", etc.
164 let res = s:Nextitem(strpart(line, 0, col), items[-1], 0, 1)
169 " Only one part, no "." or "->": complete from tags file.
170 let tags = taglist('^' . base)
172 " Remove members, these can't appear without something in front.
173 call filter(tags, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1')
175 " Remove static matches in other files.
176 call filter(tags, '!has_key(v:val, "static") || !v:val["static"] || bufnr("%") == bufnr(v:val["filename"])')
178 call extend(res, map(tags, 's:Tag2item(v:val)'))
182 " Find the variable in the tags file(s)
183 let diclist = taglist('^' . items[0] . '$')
185 " Remove members, these can't appear without something in front.
186 call filter(diclist, 'has_key(v:val, "kind") ? v:val["kind"] != "m" : 1')
189 for i in range(len(diclist))
190 " New ctags has the "typeref" field. Patched version has "typename".
191 if has_key(diclist[i], 'typename')
192 call extend(res, s:StructMembers(diclist[i]['typename'], items[1:], 1))
193 elseif has_key(diclist[i], 'typeref')
194 call extend(res, s:StructMembers(diclist[i]['typeref'], items[1:], 1))
197 " For a variable use the command, which must be a search pattern that
198 " shows the declaration of the variable.
199 if diclist[i]['kind'] == 'v'
200 let line = diclist[i]['cmd']
201 if line[0] == '/' && line[1] == '^'
202 let col = match(line, '\<' . items[0] . '\>')
203 call extend(res, s:Nextitem(strpart(line, 2, col - 2), items[1:], 0, 1))
209 if len(res) == 0 && searchdecl(items[0], 1) == 0
210 " Found, now figure out the type.
211 " TODO: join previous line if it makes sense
212 let line = getline('.')
214 let res = s:Nextitem(strpart(line, 0, col), items[1:], 0, 1)
217 " If the last item(s) are [...] they need to be added to the matches.
218 let last = len(items) - 1
221 if items[last][0] != '['
224 let brackets = items[last] . brackets
228 return map(res, 's:Tagline2item(v:val, brackets)')
231 function! s:GetAddition(line, match, memarg, bracket)
232 " Guess if the item is an array.
233 if a:bracket && match(a:line, a:match . '\s*\[') > 0
237 " Check if the item has members.
238 if len(s:SearchMembers(a:memarg, [''], 0)) > 0
239 " If there is a '*' before the name use "->".
240 if match(a:line, '\*[ \t(]*' . a:match . '\>') > 0
249 " Turn the tag info "val" into an item for completion.
250 " "val" is is an item in the list returned by taglist().
251 " If it is a variable we may add "." or "->". Don't do it for other types,
252 " such as a typedef, by not including the info that s:GetAddition() uses.
253 function! s:Tag2item(val)
254 let res = {'match': a:val['name']}
256 let res['extra'] = s:Tagcmd2extra(a:val['cmd'], a:val['name'], a:val['filename'])
258 let s = s:Dict2info(a:val)
263 let res['tagline'] = ''
264 if has_key(a:val, "kind")
265 let kind = a:val['kind']
266 let res['kind'] = kind
268 let res['tagline'] = "\t" . a:val['cmd']
269 let res['dict'] = a:val
271 let res['match'] = a:val['name'] . '('
278 " Use all the items in dictionary for the "info" entry.
279 function! s:Dict2info(dict)
281 for k in sort(keys(a:dict))
282 let info .= k . repeat(' ', 10 - len(k))
284 let info .= substitute(matchstr(a:dict['cmd'], '/^\s*\zs.*\ze$/'), '\\\(.\)', '\1', 'g')
286 let info .= a:dict[k]
293 " Parse a tag line and return a dictionary with items like taglist()
294 function! s:ParseTagline(line)
295 let l = split(a:line, "\t")
299 let d['filename'] = l[1]
303 " Find end of cmd, it may contain Tabs.
304 while n < len(l) && l[n] !~ '/;"$'
306 let d['cmd'] .= " " . l[n]
309 for i in range(n + 1, len(l) - 1)
315 let d[matchstr(l[i], '[^:]*')] = matchstr(l[i], ':\zs.*')
323 " Turn a match item "val" into an item for completion.
324 " "val['match']" is the matching item.
325 " "val['tagline']" is the tagline in which the last part was found.
326 function! s:Tagline2item(val, brackets)
327 let line = a:val['tagline']
328 let add = s:GetAddition(line, a:val['match'], [a:val], a:brackets == '')
329 let res = {'word': a:val['match'] . a:brackets . add }
331 if has_key(a:val, 'info')
332 " Use info from Tag2item().
333 let res['info'] = a:val['info']
335 " Parse the tag line and add each part to the "info" entry.
336 let s = s:Dict2info(s:ParseTagline(line))
342 if has_key(a:val, 'kind')
343 let res['kind'] = a:val['kind']
345 let res['kind'] = 'f'
347 let s = matchstr(line, '\t\(kind:\)\=\zs\S\ze\(\t\|$\)')
353 if has_key(a:val, 'extra')
354 let res['menu'] = a:val['extra']
358 " Isolate the command after the tag and filename.
359 let s = matchstr(line, '[^\t]*\t[^\t]*\t\zs\(/^.*$/\|[^\t]*\)\ze\(;"\t\|\t\|$\)')
361 let res['menu'] = s:Tagcmd2extra(s, a:val['match'], matchstr(line, '[^\t]*\t\zs[^\t]*\ze\t'))
366 " Turn a command from a tag line to something that is useful in the menu
367 function! s:Tagcmd2extra(cmd, name, fname)
369 " The command is a search command, useful to see what it is.
370 let x = matchstr(a:cmd, '^/^\s*\zs.*\ze$/')
371 let x = substitute(x, '\<' . a:name . '\>', '@@', '')
372 let x = substitute(x, '\\\(.\)', '\1', 'g')
373 let x = x . ' - ' . a:fname
374 elseif a:cmd =~ '^\d*$'
375 " The command is a line number, the file name is more useful.
376 let x = a:fname . ' - ' . a:cmd
378 " Not recognized, use command and file name.
379 let x = a:cmd . ' - ' . a:fname
384 " Find composing type in "lead" and match items[0] with it.
385 " Repeat this recursively for items[1], if it's there.
386 " When resolving typedefs "depth" is used to avoid infinite recursion.
387 " Return the list of matches.
388 function! s:Nextitem(lead, items, depth, all)
390 " Use the text up to the variable name and split it in tokens.
391 let tokens = split(a:lead, '\s\+\|\<')
393 " Try to recognize the type of the variable. This is rough guessing...
395 for tidx in range(len(tokens))
397 " Skip tokens starting with a non-ID character.
398 if tokens[tidx] !~ '^\h'
402 " Recognize "struct foobar" and "union foobar".
403 " Also do "class foobar" when it's C++ after all (doesn't work very well
405 if (tokens[tidx] == 'struct' || tokens[tidx] == 'union' || tokens[tidx] == 'class') && tidx + 1 < len(tokens)
406 let res = s:StructMembers(tokens[tidx] . ':' . tokens[tidx + 1], a:items, a:all)
410 " TODO: add more reserved words
411 if index(['int', 'short', 'char', 'float', 'double', 'static', 'unsigned', 'extern'], tokens[tidx]) >= 0
415 " Use the tags file to find out if this is a typedef.
416 let diclist = taglist('^' . tokens[tidx] . '$')
417 for tagidx in range(len(diclist))
418 let item = diclist[tagidx]
420 " New ctags has the "typeref" field. Patched version has "typename".
421 if has_key(item, 'typeref')
422 call extend(res, s:StructMembers(item['typeref'], a:items, a:all))
425 if has_key(item, 'typename')
426 call extend(res, s:StructMembers(item['typename'], a:items, a:all))
430 " Only handle typedefs here.
431 if item['kind'] != 't'
435 " Skip matches local to another file.
436 if has_key(item, 'static') && item['static'] && bufnr('%') != bufnr(item['filename'])
440 " For old ctags we recognize "typedef struct aaa" and
441 " "typedef union bbb" in the tags file command.
442 let cmd = item['cmd']
443 let ei = matchend(cmd, 'typedef\s\+')
445 let cmdtokens = split(strpart(cmd, ei), '\s\+\|\<')
446 if len(cmdtokens) > 1
447 if cmdtokens[0] == 'struct' || cmdtokens[0] == 'union' || cmdtokens[0] == 'class'
449 " Use the first identifier after the "struct" or "union"
450 for ti in range(len(cmdtokens) - 1)
451 if cmdtokens[ti] =~ '^\w'
452 let name = cmdtokens[ti]
457 call extend(res, s:StructMembers(cmdtokens[0] . ':' . name, a:items, a:all))
460 " Could be "typedef other_T some_T".
461 call extend(res, s:Nextitem(cmdtokens[0], a:items, a:depth + 1, a:all))
475 " Search for members of structure "typename" in tags files.
476 " Return a list with resulting matches.
477 " Each match is a dictionary with "match" and "tagline" entries.
478 " When "all" is non-zero find all, otherwise just return 1 if there is any
480 function! s:StructMembers(typename, items, all)
481 " Todo: What about local structures?
482 let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")'))
487 let typename = a:typename
491 let n = '1' " stop at first found match
492 if has_key(s:grepCache, a:typename)
493 let qflist = s:grepCache[a:typename]
501 exe 'silent! ' . n . 'vimgrep /\t' . typename . '\(\t\|$\)/j ' . fnames
503 let qflist = getqflist()
504 if len(qflist) > 0 || match(typename, "::") < 0
507 " No match for "struct:context::name", remove "context::" and try again.
508 let typename = substitute(typename, ':[^:]*::', ':', '')
512 " Store the result to be able to use it again later.
513 let s:grepCache[a:typename] = qflist
517 " Put matching members in matches[].
520 let memb = matchstr(l['text'], '[^\t]*')
521 if memb =~ '^' . a:items[0]
522 " Skip matches local to another file.
523 if match(l['text'], "\tfile:") < 0 || bufnr('%') == bufnr(matchstr(l['text'], '\t\zs[^\t]*'))
524 let item = {'match': memb, 'tagline': l['text']}
526 " Add the kind of item.
527 let s = matchstr(l['text'], '\t\(kind:\)\=\zs\S\ze\(\t\|$\)')
531 let item['match'] = memb . '('
535 call add(matches, item)
541 " Skip over [...] items
544 if idx >= len(a:items)
545 return matches " No further items, return the result.
547 if a:items[idx][0] != '['
553 " More items following. For each of the possible members find the
554 " matching following members.
555 return s:SearchMembers(matches, a:items[idx :], a:all)
558 " Failed to find anything.
562 " For matching members, find matches for following items.
563 " When "all" is non-zero find all, otherwise just return 1 if there is any
565 function! s:SearchMembers(matches, items, all)
567 for i in range(len(a:matches))
569 if has_key(a:matches[i], 'dict')
570 if has_key(a:matches[i].dict, 'typename')
571 let typename = a:matches[i].dict['typename']
572 elseif has_key(a:matches[i].dict, 'typeref')
573 let typename = a:matches[i].dict['typeref']
575 let line = "\t" . a:matches[i].dict['cmd']
577 let line = a:matches[i]['tagline']
578 let e = matchend(line, '\ttypename:')
580 let e = matchend(line, '\ttyperef:')
584 let typename = matchstr(line, '[^\t]*', e)
589 call extend(res, s:StructMembers(typename, a:items, a:all))
591 " Use the search command (the declaration itself).
592 let s = match(line, '\t\zs/^')
594 let e = match(line, '\<' . a:matches[i]['match'] . '\>', s)
596 call extend(res, s:Nextitem(strpart(line, s, e - s), a:items, 0, a:all))
600 if a:all == 0 && len(res) > 0