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

How do I create my own custom ex commands in Vim?

Answer

:command

Explanation

:command lets you define new Ex (colon-prefixed) commands with custom names, optional argument handling, and completion. User-defined commands must start with an uppercase letter to avoid clashing with built-in commands.

How it works

:command[!] [-nargs=N] [-complete=type] Name {body}
  • -nargs=0 (default) — no arguments; -nargs=1 — one arg; -nargs=* — any number; -nargs=? — zero or one
  • Inside {body}, <args> expands to all arguments as a single string; <f-args> splits them by spaces for function calls
  • Adding ! to :command! replaces an existing command with the same name
  • Commands are only available in the session they're defined in unless you add them to your vimrc

Example

Create a command that opens your vimrc for editing:

:command! Vimrc edit $MYVIMRC

Now :Vimrc opens your config file from anywhere.

Create a command that greps the current word under the cursor:

:command! -nargs=1 Grep vimgrep /<args>/ **

Usage: :Grep myFunction searches all files recursively.

Tips

  • Use -complete=file to get filename tab-completion on arguments: :command! -nargs=1 -complete=file Open edit <args>
  • Use -complete=command when your argument is another Ex command or mapping
  • Inspect existing user commands with :command (no arguments) — it lists all currently defined user commands
  • Delete a user command with :delcommand Name

Next

How do I complete identifiers using ctags from within insert mode?