How do I create my own custom Ex commands in Vim?
Answer
:command {Name} {action}
Explanation
:command defines a user-defined Ex command — a custom command that you invoke with :Name just like built-in commands. User commands must start with an uppercase letter (to distinguish them from built-in commands which are all lowercase). This is the foundation for creating convenient shortcuts, project-specific workflows, and plugin interfaces.
Basic syntax
:command {Name} {replacement}
Examples
Create a command to strip trailing whitespace:
:command! TrimWhitespace %s/\s\+$//e
Now :TrimWhitespace works like a built-in command.
Create a command that takes arguments:
:command! -nargs=1 Grep vimgrep /<args>/ **/*
Usage: :Grep TODO searches all files for TODO.
Create a command with a range:
:command! -range=% JSONFormat <line1>,<line2>!python3 -m json.tool
Usage: :'<,'>JSONFormat or :%JSONFormat
Flags
| Flag | Meaning |
|---|---|
-nargs=0 |
No arguments (default) |
-nargs=1 |
Exactly one argument |
-nargs=* |
Any number of arguments |
-nargs=? |
Zero or one argument |
-range |
Accept a line range |
-bang |
Accept ! suffix (:Name!) |
-complete=file |
Tab-complete filenames |
! after command |
Overwrite if already defined |
Tips
:command(no args) lists all user-defined commands:delcommand {Name}removes a user command- Use
<q-args>for quoted arguments,<f-args>for function call arguments :command!(with bang) silently overwrites — use this in vimrc to avoid errors on re-source