Custom commands in vim

How to create a custom command in vim

command -nargs=*

Argument handling (copied from the vim documentation)

By default, a user defined command will take no arguments (and an error is

reported if any are supplied). However, it is possible to specify that the
command can take arguments, using the -nargs attribute. Valid cases are:

-nargs=0 No arguments are allowed (the default)
-nargs=1 Exactly one argument is required
-nargs=* Any number of arguments are allowed (0, 1, or many)
-nargs=? 0 or 1 arguments are allowed
-nargs=+ Arguments must be supplied, but any number are allowed

Arguments are considered to be separated by (unescaped) spaces or Tabs in this context.

cmd_name

This has to start with a capital letter always

Command_action

Command action will generally be a call to a function, because we typically achieve more with functions that with commands (personal opinion). Commands are primarily used to provide an easy handle for calling functions, instead of the complicated

:call Func_name (“arg1”,”arg2″….)

way in which functions have to be called.

Now when all we are trying to do is pass the arguments passed to the commands as arguments to the function, vim provides us with the following options of parsing the arguments (as copied from the vim documentation)

Inside the command definition, the arguments are represented by the  keyword.

For example: :command -nargs=+ Say :echo “”

Now when you type

:Say Hello World

Vim echoes “Hello World”. However, if you add a double quote, it won’t work.

For example: :Say he said “hello”

To get special characters turned into a string, properly escaped to use as an expression,

use “”: :command -nargs=+ Say :echo

Now the above “:Say” command will result in this to be executed

:echo “he said \”hello\””

The  keyword contains the same information as the  keyword, except in a format suitable for use as function call arguments.

For example: :command -nargs=* DoIt :call AFunction()

: DoIt a b c

Executes the following command: :call AFunction(“a”, “b”, “c”)

 

Advertisements
Custom commands in vim

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s