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
- Define a Vimscript function with two arguments:
findstart(1 or 0) andbase(the prefix typed so far) - When called with
findstart=1, return the column where the completion begins - When called with
findstart=0, return a list of matching candidates - Point
completefuncat your function::set completefunc=MyCompleteFunc - 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:
completefuncalso works, but plugins often usenvim_create_user_commandand Lua APIs instead - The completion list items can be strings or dictionaries with keys like
word,menu,info,kindfor 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/wordlistmay be enough without a custom function