ccomplete.vim (20960B)
1 vim9script noclear 2 3 # Vim completion script 4 # Language: C 5 # Maintainer: The Vim Project <https://github.com/vim/vim> 6 # Last Change: 2026 Aug 25 7 # Rewritten in Vim9 script by github user lacygoill 8 # Former Maintainer: Bram Moolenaar <Bram@vim.org> 9 10 var prepended: string 11 var grepCache: dict<list<dict<any>>> 12 13 # This function is used for the 'omnifunc' option. 14 export def Complete(findstart: bool, abase: string): any # {{{1 15 if findstart 16 # Locate the start of the item, including ".", "->" and "[...]". 17 var line: string = getline('.') 18 var start: number = charcol('.') - 1 19 var lastword: number = -1 20 while start > 0 21 if line[start - 1] =~ '\w' 22 --start 23 elseif line[start - 1] =~ '\.' 24 if lastword == -1 25 lastword = start 26 endif 27 --start 28 elseif start > 1 && line[start - 2] == '-' 29 && line[start - 1] == '>' 30 if lastword == -1 31 lastword = start 32 endif 33 start -= 2 34 elseif line[start - 1] == ']' 35 # Skip over [...]. 36 var n: number = 0 37 --start 38 while start > 0 39 --start 40 if line[start] == '[' 41 if n == 0 42 break 43 endif 44 --n 45 elseif line[start] == ']' # nested [] 46 ++n 47 endif 48 endwhile 49 else 50 break 51 endif 52 endwhile 53 54 # Return the column of the last word, which is going to be changed. 55 # Remember the text that comes before it in prepended. 56 if lastword == -1 57 prepended = '' 58 return byteidx(line, start) 59 endif 60 prepended = line[start : lastword - 1] 61 return byteidx(line, lastword) 62 endif 63 64 # Return list of matches. 65 66 var base: string = prepended .. abase 67 68 # Don't do anything for an empty base, would result in all the tags in the 69 # tags file. 70 if base == '' 71 return [] 72 endif 73 74 # init cache for vimgrep to empty 75 grepCache = {} 76 77 # Split item in words, keep empty word after "." or "->". 78 # "aa" -> ['aa'], "aa." -> ['aa', ''], "aa.bb" -> ['aa', 'bb'], etc. 79 # We can't use split, because we need to skip nested [...]. 80 # "aa[...]" -> ['aa', '[...]'], "aa.bb[...]" -> ['aa', 'bb', '[...]'], etc. 81 var items: list<string> 82 var s: number = 0 83 var arrays: number = 0 84 while 1 85 var e: number = base->charidx(match(base, '\.\|->\|\[', s)) 86 if e < 0 87 if s == 0 || base[s - 1] != ']' 88 items->add(base[s :]) 89 endif 90 break 91 endif 92 if s == 0 || base[s - 1] != ']' 93 items->add(base[s : e - 1]) 94 endif 95 if base[e] == '.' 96 # skip over '.' 97 s = e + 1 98 elseif base[e] == '-' 99 # skip over '->' 100 s = e + 2 101 else 102 # Skip over [...]. 103 var n: number = 0 104 s = e 105 ++e 106 while e < strcharlen(base) 107 if base[e] == ']' 108 if n == 0 109 break 110 endif 111 --n 112 elseif base[e] == '[' # nested [...] 113 ++n 114 endif 115 ++e 116 endwhile 117 ++e 118 items->add(base[s : e - 1]) 119 ++arrays 120 s = e 121 endif 122 endwhile 123 124 if complete_check() 125 return v:none 126 endif 127 128 # Find the variable items[0]. 129 # 1. in current function (like with "gd") 130 # 2. in tags file(s) (like with ":tag") 131 # 3. in current file (like with "gD") 132 var res: list<dict<any>> 133 if items[0]->searchdecl(false, true) == 0 134 # Found, now figure out the type. 135 # TODO: join previous line if it makes sense 136 var line: string = getline('.') 137 var col: number = charcol('.') 138 if line[: col - 1]->stridx(';') >= 0 139 # Handle multiple declarations on the same line. 140 var col2: number = col - 1 141 while line[col2] != ';' 142 if complete_check() 143 return res 144 endif 145 --col2 146 endwhile 147 line = line[col2 + 1 :] 148 col -= col2 149 endif 150 if line[: col - 1]->stridx(',') >= 0 151 # Handle multiple declarations on the same line in a function 152 # declaration. 153 var col2: number = col - 1 154 while line[col2] != ',' 155 if complete_check() 156 return res 157 endif 158 --col2 159 endwhile 160 if line[col2 + 1 : col - 1] =~ ' *[^ ][^ ]* *[^ ]' 161 line = line[col2 + 1 :] 162 col -= col2 163 endif 164 endif 165 if len(items) == 1 166 # Completing one word and it's a local variable: May add '[', '.' or 167 # '->'. 168 var match: string = items[0] 169 var kind: string = 'v' 170 if match(line, '\<' .. match .. '\s*\[') > 0 171 match ..= '[' 172 else 173 res = line[: col - 1]->Nextitem([''], 0, true) 174 if len(res) > 0 175 # There are members, thus add "." or "->". 176 if match(line, '\*[ \t(]*' .. match .. '\>') > 0 177 match ..= '->' 178 else 179 match ..= '.' 180 endif 181 endif 182 endif 183 res = [{match: match, tagline: '', kind: kind, info: line}] 184 elseif len(items) == arrays + 1 185 # Completing one word and it's a local array variable: build tagline 186 # from declaration line 187 var match: string = items[0] 188 var kind: string = 'v' 189 var tagline: string = "\t/^" .. line .. '$/' 190 res = [{match: match, tagline: tagline, kind: kind, info: line}] 191 else 192 # Completing "var.", "var.something", etc. 193 res = line[: col - 1]->Nextitem(items[1 :], 0, true) 194 endif 195 endif 196 197 if len(items) == 1 || len(items) == arrays + 1 198 # Only one part, no "." or "->": complete from tags file. 199 var tags: list<dict<any>> 200 if len(items) == 1 201 tags = taglist('^' .. base) 202 else 203 tags = taglist('^' .. items[0] .. '$') 204 endif 205 206 tags 207 # Remove members, these can't appear without something in front. 208 ->filter((_, v: dict<any>): bool => 209 v->has_key('kind') ? v.kind != 'm' : true) 210 # Remove static matches in other files. 211 ->filter((_, v: dict<any>): bool => 212 !v->has_key('static') 213 || !v['static'] 214 || bufnr('%') == bufnr(v['filename'])) 215 216 res = res->extend(tags->map((_, v: dict<any>) => Tag2item(v))) 217 endif 218 219 if len(res) == 0 220 # Find the variable in the tags file(s) 221 var diclist: list<dict<any>> = taglist('^' .. items[0] .. '$') 222 # Remove members, these can't appear without something in front. 223 ->filter((_, v: dict<any>): bool => 224 v->has_key('kind') ? v.kind != 'm' : true) 225 226 res = [] 227 for i: number in len(diclist)->range() 228 if complete_check() 229 return res 230 endif 231 # New ctags has the "typeref" field. Patched version has "typename". 232 if diclist[i]->has_key('typename') 233 res = res->extend(diclist[i]['typename']->StructMembers(items[1 :], true)) 234 elseif diclist[i]->has_key('typeref') 235 res = res->extend(diclist[i]['typeref']->StructMembers(items[1 :], true)) 236 endif 237 238 # For a variable use the command, which must be a search pattern that 239 # shows the declaration of the variable. 240 if diclist[i]['kind'] == 'v' 241 var line: string = diclist[i]['cmd'] 242 if line[: 1] == '/^' 243 var col: number = line->charidx(match(line, '\<' .. items[0] .. '\>')) 244 res = res->extend(line[2 : col - 1]->Nextitem(items[1 :], 0, true)) 245 endif 246 endif 247 endfor 248 endif 249 250 if len(res) == 0 && items[0]->searchdecl(true) == 0 251 # Found, now figure out the type. 252 # TODO: join previous line if it makes sense 253 var line: string = getline('.') 254 var col: number = charcol('.') 255 res = line[: col - 1]->Nextitem(items[1 :], 0, true) 256 endif 257 258 # If the last item(s) are [...] they need to be added to the matches. 259 var last: number = len(items) - 1 260 var brackets: string = '' 261 while last >= 0 262 if complete_check() 263 return res 264 endif 265 if items[last][0] != '[' 266 break 267 endif 268 brackets = items[last] .. brackets 269 --last 270 endwhile 271 272 return res->map((_, v: dict<any>): dict<string> => Tagline2item(v, brackets)) 273 enddef 274 275 def GetAddition( # {{{1 276 line: string, 277 match: string, 278 memarg: list<dict<any>>, 279 bracket: bool): string 280 # Guess if the item is an array. 281 if bracket && match(line, match .. '\s*\[') > 0 282 return '[' 283 endif 284 285 # Check if the item has members. 286 if SearchMembers(memarg, [''], false)->len() > 0 287 # If there is a '*' before the name use "->". 288 if match(line, '\*[ \t(]*' .. match .. '\>') > 0 289 return '->' 290 else 291 return '.' 292 endif 293 endif 294 return '' 295 enddef 296 297 def Tag2item(val: dict<any>): dict<any> # {{{1 298 # Turn the tag info "val" into an item for completion. 299 # "val" is is an item in the list returned by taglist(). 300 # If it is a variable we may add "." or "->". Don't do it for other types, 301 # such as a typedef, by not including the info that GetAddition() uses. 302 var res: dict<any> = {match: val['name']} 303 304 res['extra'] = Tagcmd2extra(val['cmd'], val['name'], val['filename']) 305 306 var s: string = Dict2info(val) 307 if s != '' 308 res['info'] = s 309 endif 310 311 res['tagline'] = '' 312 if val->has_key('kind') 313 var kind: string = val['kind'] 314 res['kind'] = kind 315 if kind == 'v' 316 res['tagline'] = "\t" .. val['cmd'] 317 res['dict'] = val 318 elseif kind == 'f' 319 res['match'] = val['name'] .. '(' 320 endif 321 endif 322 323 return res 324 enddef 325 326 def Dict2info(dict: dict<any>): string # {{{1 327 # Use all the items in dictionary for the "info" entry. 328 var info: string = '' 329 for k: string in dict->keys()->sort() 330 if complete_check() 331 return info 332 endif 333 info ..= k .. repeat(' ', 10 - strlen(k)) 334 if k == 'cmd' 335 info ..= dict['cmd'] 336 ->matchstr('/^\s*\zs.*\ze$/') 337 ->substitute('\\\(.\)', '\1', 'g') 338 else 339 var dictk: any = dict[k] 340 if typename(dictk) != 'string' 341 info ..= dictk->string() 342 else 343 info ..= dictk 344 endif 345 endif 346 info ..= "\n" 347 endfor 348 return info 349 enddef 350 351 def ParseTagline(line: string): dict<any> # {{{1 352 # Parse a tag line and return a dictionary with items like taglist() 353 var l: list<string> = split(line, "\t") 354 var d: dict<any> 355 if len(l) >= 3 356 d['name'] = l[0] 357 d['filename'] = l[1] 358 d['cmd'] = l[2] 359 var n: number = 2 360 if l[2] =~ '^/' 361 # Find end of cmd, it may contain Tabs. 362 while n < len(l) && l[n] !~ '/;"$' 363 ++n 364 d['cmd'] ..= ' ' .. l[n] 365 endwhile 366 endif 367 for i: number in range(n + 1, len(l) - 1) 368 if complete_check() 369 return d 370 endif 371 if l[i] == 'file:' 372 d['static'] = 1 373 elseif l[i] !~ ':' 374 d['kind'] = l[i] 375 else 376 d[l[i]->matchstr('[^:]*')] = l[i]->matchstr(':\zs.*') 377 endif 378 endfor 379 endif 380 381 return d 382 enddef 383 384 def Tagline2item(val: dict<any>, brackets: string): dict<string> # {{{1 385 # Turn a match item "val" into an item for completion. 386 # "val['match']" is the matching item. 387 # "val['tagline']" is the tagline in which the last part was found. 388 var line: string = val['tagline'] 389 var add: string = GetAddition(line, val['match'], [val], brackets == '') 390 var res: dict<string> = {word: val['match'] .. brackets .. add} 391 392 if val->has_key('info') 393 # Use info from Tag2item(). 394 res['info'] = val['info'] 395 else 396 # Parse the tag line and add each part to the "info" entry. 397 var s: string = ParseTagline(line)->Dict2info() 398 if s != '' 399 res['info'] = s 400 endif 401 endif 402 403 if val->has_key('kind') 404 res['kind'] = val['kind'] 405 elseif add == '(' 406 res['kind'] = 'f' 407 else 408 var s: string = line->matchstr('\t\(kind:\)\=\zs\S\ze\(\t\|$\)') 409 if s != '' 410 res['kind'] = s 411 endif 412 endif 413 414 if val->has_key('extra') 415 res['menu'] = val['extra'] 416 return res 417 endif 418 419 # Isolate the command after the tag and filename. 420 var s: string = line->matchstr('[^\t]*\t[^\t]*\t\zs\(/^.*$/\|[^\t]*\)\ze\(;"\t\|\t\|$\)') 421 if s != '' 422 res['menu'] = s->Tagcmd2extra(val['match'], line->matchstr('[^\t]*\t\zs[^\t]*\ze\t')) 423 endif 424 return res 425 enddef 426 427 def Tagcmd2extra( # {{{1 428 cmd: string, 429 name: string, 430 fname: string): string 431 # Turn a command from a tag line to something that is useful in the menu 432 var x: string 433 if cmd =~ '^/^' 434 # The command is a search command, useful to see what it is. 435 x = cmd 436 ->matchstr('^/^\s*\zs.*\ze$/') 437 ->substitute('\<' .. name .. '\>', '@@', '') 438 ->substitute('\\\(.\)', '\1', 'g') 439 .. ' - ' .. fname 440 elseif cmd =~ '^\d*$' 441 # The command is a line number, the file name is more useful. 442 x = fname .. ' - ' .. cmd 443 else 444 # Not recognized, use command and file name. 445 x = cmd .. ' - ' .. fname 446 endif 447 return x 448 enddef 449 450 def Nextitem( # {{{1 451 lead: string, 452 items: list<string>, 453 depth: number, 454 all: bool): list<dict<string>> 455 # Find composing type in "lead" and match items[0] with it. 456 # Repeat this recursively for items[1], if it's there. 457 # When resolving typedefs "depth" is used to avoid infinite recursion. 458 # Return the list of matches. 459 460 # Use the text up to the variable name and split it in tokens. 461 var tokens: list<string> = split(lead, '\s\+\|\<') 462 463 # Try to recognize the type of the variable. This is rough guessing... 464 var res: list<dict<string>> 465 for tidx: number in len(tokens)->range() 466 if complete_check() 467 return res 468 endif 469 470 # Skip tokens starting with a non-ID character. 471 if tokens[tidx] !~ '^\h' 472 continue 473 endif 474 475 # Recognize "struct foobar" and "union foobar". 476 # Also do "class foobar" when it's C++ after all (doesn't work very well 477 # though). 478 if (tokens[tidx] == 'struct' 479 || tokens[tidx] == 'union' 480 || tokens[tidx] == 'class') 481 && tidx + 1 < len(tokens) 482 res = StructMembers(tokens[tidx] .. ':' .. tokens[tidx + 1], items, all) 483 break 484 endif 485 486 # TODO: add more reserved words 487 if ['int', 'short', 'char', 'float', 488 'double', 'static', 'unsigned', 'extern']->index(tokens[tidx]) >= 0 489 continue 490 endif 491 492 # Use the tags file to find out if this is a typedef or struct 493 var diclist: list<dict<any>> = taglist('^' .. tokens[tidx] .. '$') 494 for tagidx: number in len(diclist)->range() 495 496 if complete_check() 497 return res 498 endif 499 500 var item: dict<any> = diclist[tagidx] 501 502 # New ctags has the "typeref" field. Patched version has "typename". 503 if item->has_key('typeref') 504 res = res->extend(item['typeref']->StructMembers(items, all)) 505 continue 506 endif 507 if item->has_key('typename') 508 res = res->extend(item['typename']->StructMembers(items, all)) 509 continue 510 endif 511 512 # handle struct 513 if item['kind'] == 's' 514 res = StructMembers('struct:' .. tokens[tidx], items, all) 515 break 516 endif 517 518 519 # Only handle typedefs here. 520 if item['kind'] != 't' 521 continue 522 endif 523 524 # Skip matches local to another file. 525 if item->has_key('static') && item['static'] 526 && bufnr('%') != bufnr(item['filename']) 527 continue 528 endif 529 530 # For old ctags we recognize "typedef struct aaa" and 531 # "typedef union bbb" in the tags file command. 532 var cmd: string = item['cmd'] 533 var ei: number = cmd->charidx(matchend(cmd, 'typedef\s\+')) 534 if ei > 1 535 var cmdtokens: list<string> = cmd[ei :]->split('\s\+\|\<') 536 if len(cmdtokens) > 1 537 if cmdtokens[0] == 'struct' 538 || cmdtokens[0] == 'union' 539 || cmdtokens[0] == 'class' 540 var name: string = '' 541 # Use the first identifier after the "struct" or "union" 542 for ti: number in (len(cmdtokens) - 1)->range() 543 if cmdtokens[ti] =~ '^\w' 544 name = cmdtokens[ti] 545 break 546 endif 547 endfor 548 if name != '' 549 res = res->extend(StructMembers(cmdtokens[0] .. ':' .. name, items, all)) 550 endif 551 elseif depth < 10 552 # Could be "typedef other_T some_T". 553 res = res->extend(cmdtokens[0]->Nextitem(items, depth + 1, all)) 554 endif 555 endif 556 endif 557 endfor 558 if len(res) > 0 559 break 560 endif 561 endfor 562 563 return res 564 enddef 565 566 def StructMembers( # {{{1 567 atypename: string, 568 items: list<string>, 569 all: bool): list<dict<string>> 570 571 # Search for members of structure "typename" in tags files. 572 # Return a list with resulting matches. 573 # Each match is a dictionary with "match" and "tagline" entries. 574 # When "all" is true find all, otherwise just return 1 if there is any member. 575 576 # Todo: What about local structures? 577 var fnames: string = tagfiles() 578 ->map((_, v: string) => escape(v, ' \#%|')) 579 ->join() 580 if fnames == '' 581 return [] 582 endif 583 584 var typename: string = atypename 585 var qflist: list<dict<any>> 586 var cached: number = 0 587 var n: string 588 if !all 589 n = '1' # stop at first found match 590 if grepCache->has_key(typename) 591 qflist = grepCache[typename] 592 cached = 1 593 endif 594 else 595 n = '' 596 endif 597 if !cached 598 while 1 599 if complete_check() 600 return [] 601 endif 602 # Match "typename" literally (\V): escaping alone is not enough, as e.g. 603 # an unclosed "[" makes vimgrep's pattern skipping fail and the rest of 604 # the tag value is then parsed as Ex commands. 605 execute 'silent! keepjumps noautocmd ' 606 .. n .. 'vimgrep ' .. '/\t\V' .. escape(typename, '/\') .. '\m\(\t\|$\)/j ' 607 .. fnames 608 609 qflist = getqflist() 610 if len(qflist) > 0 || match(typename, '::') < 0 611 break 612 endif 613 # No match for "struct:context::name", remove "context::" and try again. 614 typename = typename->substitute(':[^:]*::', ':', '') 615 endwhile 616 617 if !all 618 # Store the result to be able to use it again later. 619 grepCache[typename] = qflist 620 endif 621 endif 622 623 # Skip over [...] items 624 var idx: number = 0 625 var target: string 626 while 1 627 if complete_check() 628 return [] 629 endif 630 if idx >= len(items) 631 target = '' # No further items, matching all members 632 break 633 endif 634 if items[idx][0] != '[' 635 target = items[idx] 636 break 637 endif 638 ++idx 639 endwhile 640 # Put matching members in matches[]. 641 var matches: list<dict<string>> 642 for l: dict<any> in qflist 643 var memb: string = l['text']->matchstr('[^\t]*') 644 if memb =~ '^' .. target 645 # Skip matches local to another file. 646 if match(l['text'], "\tfile:") < 0 647 || bufnr('%') == l['text']->matchstr('\t\zs[^\t]*')->bufnr() 648 var item: dict<string> = {match: memb, tagline: l['text']} 649 650 # Add the kind of item. 651 var s: string = l['text']->matchstr('\t\(kind:\)\=\zs\S\ze\(\t\|$\)') 652 if s != '' 653 item['kind'] = s 654 if s == 'f' 655 item['match'] = memb .. '(' 656 endif 657 endif 658 659 matches->add(item) 660 endif 661 endif 662 endfor 663 664 if len(matches) > 0 665 # Skip over next [...] items 666 ++idx 667 while 1 668 if complete_check() 669 return matches 670 endif 671 if idx >= len(items) 672 return matches # No further items, return the result. 673 endif 674 if items[idx][0] != '[' 675 break 676 endif 677 ++idx 678 endwhile 679 680 # More items following. For each of the possible members find the 681 # matching following members. 682 return SearchMembers(matches, items[idx :], all) 683 endif 684 685 # Failed to find anything. 686 return [] 687 enddef 688 689 def SearchMembers( # {{{1 690 matches: list<dict<any>>, 691 items: list<string>, 692 all: bool): list<dict<string>> 693 694 # For matching members, find matches for following items. 695 # When "all" is true find all, otherwise just return 1 if there is any member. 696 var res: list<dict<string>> 697 for i: number in len(matches)->range() 698 if complete_check() 699 return res 700 endif 701 var typename: string = '' 702 var line: string 703 if matches[i]->has_key('dict') 704 if matches[i]['dict']->has_key('typename') 705 typename = matches[i]['dict']['typename'] 706 elseif matches[i]['dict']->has_key('typeref') 707 typename = matches[i]['dict']['typeref'] 708 endif 709 line = "\t" .. matches[i]['dict']['cmd'] 710 else 711 line = matches[i]['tagline'] 712 var eb: number = matchend(line, '\ttypename:') 713 var e: number = charidx(line, eb) 714 if e < 0 715 eb = matchend(line, '\ttyperef:') 716 e = charidx(line, eb) 717 endif 718 if e > 0 719 # Use typename field 720 typename = line->matchstr('[^\t]*', eb) 721 endif 722 endif 723 724 if typename != '' 725 res = res->extend(StructMembers(typename, items, all)) 726 else 727 # Use the search command (the declaration itself). 728 var sb: number = line->match('\t\zs/^') 729 var s: number = charidx(line, sb) 730 if s > 0 731 var e: number = line 732 ->charidx(match(line, '\<' .. matches[i]['match'] .. '\>', sb)) 733 if e > 0 734 res = res->extend(line[s : e - 1]->Nextitem(items, 0, all)) 735 endif 736 endif 737 endif 738 if !all && len(res) > 0 739 break 740 endif 741 endfor 742 return res 743 enddef 744 #}}}1 745 746 # vim: et sw=2 sts=2