Vim Recipes Extending Creating Command-Line Commands

Creating Command-Line Commands

Problem

You want to create your own :command command.

Solution

Use the :command command like so::command name command, where name is the command you're creating and command the command name should execute. (name must start with an initial capital)

For example, :command Ls !ls -all % lets you use :Ls to view the long listing for the current file on POSIX systems, thus showing the permissions, owner, group, etc.

Discussion

The command can be anything you could enter at the : prompt.

You can modify how the command is defined by supplying :command with a list of arguments with the syntax :command arg1, arg2, … ,argN name command. These are not to be confused with arguments passed to the command, itself, however.

To create a command that accepts arguments you use the syntax :command -nargs=spec name command, where spec is:

1
One argument.
*
Any number of arguments.
?
Zero or one arguments.
+
One or more arguments.

You reference the arguments in command with the <args> placeholder. The <q-args> quotes special characters in the argument. For example, you could use :command -nargs=1 Ci !cd %:h && git commit %:t -m <q-args> to quickly change to the directory containing the current file (%:h is the current pathname with the last component removed) and commit the current file (%:t is the last component of the current pathname) to a Git repository by typing :Ci message, without worrying about using quotation marks and the likeFor more robust integration with Git see the Integrating Vim with Git recipe.

To create a command that accepts a count you use the -count=default argument, then reference the count in command as <count>.

To create a command that accepts a range you use the -range=spec argument. If you don't supply a spec (i.e. -range), the range defaults to the current line. A spec of % means that the range defaults to the whole file. You can reference the range in the command with the placeholders <line1> and <line2> which denote the first and last line of the given range, respectively.