2

What is the purpose of user command in Vi/Vim? I noticed that a lot of commands are usually used to call functions like this:

command! TrimWhitespace call TrimWhitespace()

From my observation, command seems to provide quick way to call a function without having to type call from the command mode.

But I also see example like this, which executes Vim commands.

command! Vimrc :vsplit $MYVIMRC

Vim's help page is quite terse and confusing on this subject and I would like more clarification. Are these ex commands or Vimscript? In Vim's help page, I see more complex examples like this (not that I want to know what it does, but rather why we use them):

command! -nargs=+ -complete=file MyEdit
    \ for f in expand(<q-args>, 0, 1) |
    \ exe '<mods> split ' . f |
    \ endfor

function! SpecialEdit(files, mods)
for f in expand(a:files, 0, 1)
    exe a:mods . ' split ' . f
endfor
endfunction
command! -nargs=+ -complete=file Sedit
    \ call SpecialEdit(<q-args>, <q-mods>)
6

Let's get this confusion out of the way first:

Are these ex commands or Vimscript?

Vim scripts are made of ex commands. From :help script:

Your first experience with Vim scripts is the vimrc file.  Vim reads it when
it starts up and executes the commands.  You can set options to values you
prefer.  And you can use any colon command in it (commands that start with a
":"; these are sometimes referred to as Ex commands or command-line commands).

The : in :vsplit in your second example is unnecessary, but Vim seems content to just ignore superfluous :s at the front of ex commands (:::::::::::vsplit seems to work just as well as :vsplit).

Also, note that :call, from your first example, is just another ex command.


On to your main question. :command has three forms, depending on the number of arguments.

With no arguments, :command just lists all the user-defined commands. This will include commands defined in plugins, your vimrc, in command-line mode, etc.

With one argument, it lists all user-defined commands that start with that argument.

With two or more arguments, :command defines a new user command.

As far as why anyone would use this, well, why would anyone use any tool? Because it makes it easier and/or faster to do things. Some specific advantages commands have over simply :calling functions:

  1. No need to type :call before the command name.
  2. The command can be abbreviated, as long as it's unambiguous. (From your first example, you might be able to get away with just :TrimW. Compare that to :call TrimWhitespace(). 1/3 as much typing.)
  3. Commands can support completion for their arguments. As far as I'm aware, functions do not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.