How do I add custom tab completion to my own Ex commands?
Answer
:command -complete=file -nargs=1 E edit <args>
Explanation
When defining custom commands with :command, the -complete option adds tab completion for arguments. Vim provides many built-in completion types, and you can also write custom completion functions for full control over suggestions.
How it works
-complete=file— completes file names-complete=dir— completes directory names-complete=buffer— completes buffer names-complete=command— completes Ex commands-complete=custom,FuncName— uses a custom function-nargs=1— command takes exactly one argument
Example
" Command with file completion
:command -complete=file -nargs=1 E edit <args>
" Custom completion function
function! ColorComplete(A, L, P)
return "red\ngreen\nblue\nyellow"
endfunction
:command -complete=custom,ColorComplete -nargs=1 SetColor echo <args>
:SetColor <Tab>
Completes: red, green, blue, yellow
Tips
- Use
-complete=customlist,Funcfor returning a List instead of newline-separated string - The function receives: ArgLead (current arg), CmdLine (full line), CursorPos
- Built-in types include:
color,event,highlight,mapping,option,shellcmd,tag - Combine with
-nargs=*for commands accepting multiple arguments