vimtricks.wiki Concise Vim tricks, one at a time.

How do I trigger a custom user-defined completion function in insert mode?

Answer

<C-x><C-u>

Explanation

Vim's <C-x><C-u> invokes a user-defined completion function, letting you plug any completion logic you want into the standard insert-mode completion popup. You set the function with :set completefunc=YourFunc and Vim calls it with a standard interface whenever you press <C-x><C-u>.

How it works

  1. Define a Vimscript function with two arguments: findstart (1 or 0) and base (the prefix typed so far)
  2. When called with findstart=1, return the column where the completion begins
  3. When called with findstart=0, return a list of matching candidates
  4. Point completefunc at your function: :set completefunc=MyCompleteFunc
  5. In insert mode, press <C-x><C-u> to invoke it

Example

function! ColorComplete(findstart, base)
  if a:findstart
    " Find the start of the word
    let line = getline('.')
    let start = col('.') - 1
    while start > 0 && line[start - 1] =~ '\w'
      let start -= 1
    endwhile
    return start
  else
    " Return matching color names
    let colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple']
    return filter(colors, 'v:val =~ "^" . a:base')
  endif
endfunction

set completefunc=ColorComplete

Now typing re and pressing <C-x><C-u> suggests red.

Tips

  • Neovim users: completefunc also works, but plugins often use nvim_create_user_command and Lua APIs instead
  • The completion list items can be strings or dictionaries with keys like word, menu, info, kind for rich popup content
  • <C-n> / <C-p> navigate the popup; <C-e> cancels; <CR> or <C-y> accepts
  • For simpler cases, :set complete+=k/path/to/wordlist may be enough without a custom function

Next

How do I permanently add a word to my personal spell file so Vim stops marking it as misspelled?