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

How do I create a custom Ex command?

Answer

:command Name action

Explanation

The :command command defines a new user Ex command. This lets you create shortcuts for frequently used sequences.

How it works

  • :command Name action creates command :Name
  • User commands must start with an uppercase letter
  • :command! Name action overwrites an existing command

Example

command! W w                          " :W saves (for typos)
command! Q q                          " :Q quits (for typos)
command! Trim %s/\s\+$//e             " :Trim removes trailing whitespace
command! JsonFormat %!python3 -m json.tool  " :JsonFormat pretty-prints JSON

Tips

  • -nargs=* allows arguments: command! -nargs=1 G grep <args> **/*
  • -range allows a range prefix
  • -bang allows an ! suffix
  • :delcommand Name removes a command
  • :command with no arguments lists all user commands

Next

How do you yank a single word into a named register?