Usr_41
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
VIM USER MANUALby Bram Moolenaar
Write a Vim script
The Vim script language is used for the startup vimrc file, syntax files, andmany other things. This chapter explains the items that can be used in a Vimscript. There are a lot of them, thus this is a long chapter.
41.1 Introduction
41.2 Variables
41.3 Expressions
41.4 Conditionals
41.5 Executing an expression
41.6 Using functions
41.7 Defining a function
41.8 Lists and Dictionaries
41.9 Exceptions
41.10 Various remarks
41.11 Writing a plugin
41.12 Writing a filetype plugin
41.13 Writing a compiler plugin
41.14 Writing a plugin that loads quickly
41.15 Writing library scripts
41.16 Distributing Vim scripts
Your first experience with Vim scripts is the vimrc file. Vim reads it whenit starts up and executes the commands. You can set options to values youprefer. 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). Syntax files are also Vim scripts. As are files that set options for aspecific file type. A complicated macro can be defined by a separate Vimscript file. You can think of other uses yourself.
If you are familiar with Python, you can find a comparison betweenPython and Vim script here, with pointers to other documents:
https://gist.github.com/yegappan/16d964a37ead0979b05e655aa036cad0And if you are familiar with #"https://w0rp.com/blog/post/vim-script-for-the-javascripter/">https://w0rp.com/blog/post/vim-script-for-the-javascripter/
Let's start with a simple example:
:let i = 1:while i < 5: echo "count is" i: let i += 1:endwhile
Note:The ":" characters are not really needed here. You only need to usethem when you type a command. In a Vim script file they can be leftout. We will use them here anyway to make clear these are coloncommands and make them stand out from Normal mode commands.Note:You can try out the examples by yanking the lines from the text hereand executing them with :@"
The output of the example code is:
count is 1
count is 2
count is 3
count is 4
In the first line the ":let" command assigns a value to a variable. Thegeneric form is:
:let {variable} = {expression}In this case the variable name is "i" and the expression is a simple value,the number one. The ":while" command starts a loop. The generic form is:
:while {condition}: {statements}:endwhileThe statements until the matching ":endwhile" are executed for as long as thecondition is true. The condition used here is the expression "i < 5". Thisis true when the variable i is smaller than five.
Note:If you happen to write a while loop that keeps on running, you caninterrupt it by pressing
CTRL-C (
CTRL-Break on MS-Windows).
The ":echo" command prints its arguments. In this case the string "count is"and the value of the variable i. Since i is one, this will print:
Then there is the ":let i += 1" command. This does the same thing as":let i = i + 1". This adds one to the variable i and assigns the new valueto the same variable.
The example was given to explain the commands, but would you really want tomake such a loop, it can be written much more compact:
:for i in range(1, 4): echo "count is" i:endfor
We won't explain how
:for and
range() work until later. Follow the linksif you are impatient.
FOUR KINDS OF NUMBERS
Numbers can be decimal, hexadecimal, octal or binary.
A hexadecimal number starts with "0x" or "0X". For example "0x1f" is decimal
31.
An octal number starts with "0o", "0O" or a zero and another digit. "0o17" isdecimal 15.
A binary number starts with "0b" or "0B". For example "0b101" is decimal 5.
A decimal number is just digits. Careful: don't put a zero before a decimalnumber, it will be interpreted as an octal number!
The ":echo" command always prints decimal numbers. Example:
:echo 0x7f 0o36
A number is made negative with a minus sign. This also works for hexadecimal,octal and binary numbers. A minus sign is also used for subtraction. Comparethis with the previous example:
:echo 0x7f -0o36
White space in an expression is ignored. However, it's recommended to use itfor separating items, to make the expression easier to read. For example, toavoid the confusion with a negative number above, put a space between theminus sign and the following number:
:echo 0x7f - 0o36
41.2 Variables
A variable name consists of ASCII letters, digits and the underscore. Itcannot start with a digit. Valid variable names are:
counter_aap3very_long_variable_name_with_underscoresFuncLengthLENGTH
Invalid names are "foo.bar" and "6var". These variables are global. To see a list of currently defined variablesuse this command:
:let
You can use global variables everywhere. This also means that when thevariable "count" is used in one script file, it might also be used in anotherfile. This leads to confusion at least, and real problems at worst. To avoidthis, you can use a variable local to a script file by prepending "s:". Forexample, one script contains this code:
:let s:count = 1:while s:count < 5: source other.vim: let s:count += 1:endwhile
Since "s:count" is local to this script, you can be sure that sourcing the"other.vim" script will not change this variable. If "other.vim" also uses an"s:count" variable, it will be a different copy, local to that script. Moreabout script-local variables here:
script-variable.
b:namevariable local to a bufferw:namevariable local to a windowg:nameglobal variable (also in a function)v:namevariable predefined by Vim
DELETING VARIABLES
Variables take up memory and show up in the output of the ":let" command. Todelete a variable use the ":unlet" command. Example:
:unlet s:count
This deletes the script-local variable "s:count" to free up the memory ituses. If you are not sure if the variable exists, and don't want an errormessage when it doesn't, append !:
:unlet! s:count
When a script has been processed to the end, the local variables declaredthere will not be deleted. Functions defined in the script can use them.Example:
:if !exists("s:call_count"): let s:call_count = 0:endif:let s:call_count = s:call_count + 1:echo "called" s:call_count "times"
The "exists()" function checks if a variable has already been defined. Itsargument is the name of the variable you want to check. Not the variableitself! If you would do this:
:if !exists(s:call_count)
Then the value of s:call_count will be used as the name of the variable thatexists() checks. That's not what you want. The exclamation mark ! negates a value. When the value was true, itbecomes false. When it was false, it becomes true. You can read it as "not".Thus "if !exists()" can be read as "if not exists()". What Vim calls true is anything that is not zero. Zero is false.
Note:Vim automatically converts a string to a number when it is looking fora number. When using a string that doesn't start with a digit theresulting number is zero. Thus look out for this:
:if "true"
The "true" will be interpreted as a zero, thus as false!
STRING VARIABLES AND CONSTANTS
So far only numbers were used for the variable value. Strings can be used aswell. Numbers and strings are the basic types of variables that Vim supports.The type is dynamic, it is set each time when assigning a value to thevariable with ":let". More about types in
41.8. To assign a string value to a variable, you need to use a string constant.There are two types of these. First the string in double quotes:
:let name = "peter":echo name
If you want to include a double quote inside the string, put a backslash infront of it:
:let name = "\"peter\"":echo name
To avoid the need for a backslash, you can use a string in single quotes:
:let name = '"peter"':echo name
Inside a single-quote string all the characters are as they are. Only thesingle quote itself is special: you need to use two to get one. A backslashis taken literally, thus you can't use it to change the meaning of thecharacter after it. In double-quote strings it is possible to use special characters. Here area few useful ones:
\t<Tab>\n<NL>, line break\r<CR>,<Enter>\e<Esc>\b<BS>, backspace\""\\\, backslash\<Esc><Esc>\<C-W>CTRL-W
The last two are just examples. The "\<name>" form can be used to includethe special key "name". See
expr-quote for the full list of special items in a string.
Vim has a rich, yet simple way to handle expressions. You can read thedefinition here:
expression-syntax. Here we will show the most commonitems. The numbers, strings and variables mentioned above are expressions bythemselves. Thus everywhere an expression is expected, you can use a number,string or variable. Other basic items in an expression are:
$NAMEenvironment variable&nameoption@rregister
Examples:
:echo "The value of 'tabstop' is" &ts:echo "Your home directory is" $HOME:if @a > 5
The &name form can be used to save an option value, set it to a new value,do something and restore the old value. Example:
:let save_ic = &ic:set noic:/The Start/,$delete:let &ic = save_ic
This makes sure the "The Start" pattern is used with the
'ignorecase' optionoff. Still, it keeps the value that the user had set. (Another way to dothis would be to add "\C" to the pattern, see
/\C.)
MATHEMATICS
It becomes more interesting if we combine these basic items. Let's start withmathematics on numbers:
a + badda - bsubtracta * bmultiplya / bdividea % bmodulo
The usual precedence is used. Example:
:echo 10 + 5 * 2
Grouping is done with parentheses. No surprises here. Example:
:echo (10 + 5) * 2
Strings can be concatenated with ".." (see
expr6). Example:
:echo "foo" .. "bar"
When the ":echo" command gets multiple arguments, it separates them with aspace. In the example the argument is a single expression, thus no space isinserted.
Borrowed from the C language is the conditional expression:
a ? b : c
If "a" evaluates to true "b" is used, otherwise "c" is used. Example:
:let i = 4:echo i > 5 ? "i is big" : "i is small"
The three parts of the constructs are always evaluated first, thus you couldsee it work as:
(a) ? (b) : (c)
The ":if" commands executes the following statements, until the matching":endif", only when a condition is met. The generic form is:
:if{condition}{statements}:endif
Only when the expression{condition} evaluates to true (non-zero) will the{statements} be executed. These must still be valid commands. If theycontain garbage, Vim won't be able to find the ":endif". You can also use ":else". The generic form for this is:
:if{condition}{statements}:else{statements}:endif
The second{statements} is only executed if the first one isn't. Finally, there is ":elseif":
:if{condition}{statements}:elseif{condition}{statements}:endif
This works just like using ":else" and then "if", but without the need for anextra ":endif". A useful example for your vimrc file is checking the
'term' option anddoing something depending upon its value:
:if &term == "xterm": " Do stuff for xterm:elseif &term == "vt100": " Do stuff for a vt100 terminal:else: " Do something for other terminals:endif
LOGIC OPERATIONS
We already used some of them in the examples. These are the most often usedones:
a == bequal toa != bnot equal toa > bgreater thana >= bgreater than or equal toa < bless thana <= bless than or equal to
The result is one if the condition is met and zero otherwise. An example:
:if v:version >= 700: echo "congratulations":else: echo "you are using an old version, upgrade!":endif
Here "v:version" is a variable defined by Vim, which has the value of the Vimversion. 600 is for version 6.0. Version 6.1 has the value 601. This isvery useful to write a script that works with multiple versions of Vim.
v:versionThe logic operators work both for numbers and strings. When comparing twostrings, the mathematical difference is used. This compares byte values,which may not be right for some languages. When comparing a string with a number, the string is first converted to anumber. This is a bit tricky, because when a string doesn't look like anumber, the number zero is used. Example:
:if 0 == "one": echo "yes":endif
This will echo "yes", because "one" doesn't look like a number, thus it isconverted to the number zero.
For strings there are two more items:
a =~ bmatches witha !~ bdoes not match with
The left item "a" is used as a string. The right item "b" is used as apattern, like what's used for searching. Example:
:if str =~ " ": echo "str contains a space":endif:if str !~ '\.$': echo "str does not end in a full stop":endif
Notice the use of a single-quote string for the pattern. This is useful,because backslashes would need to be doubled in a double-quote string andpatterns tend to contain many backslashes.
The
'ignorecase' option is used when comparing strings. When you don't wantthat, append "#" to match case and "?" to ignore case. Thus "==?" comparestwo strings to be equal while ignoring case. And "!~#" checks if a patterndoesn't match, also checking the case of letters. For the full table see
expr-==.
MORE LOOPING
The ":while" command was already mentioned. Two more statements can be usedin between the ":while" and the ":endwhile":
:continueJump back to the start of the while loop; theloop continues.:breakJump forward to the ":endwhile"; the loop isdiscontinued.
Example:
:while counter < 40: call do_something(): if skip_flag: continue: endif: if finished_flag: break: endif: sleep 50m:endwhile
The ":sleep" command makes Vim take a nap. The "50m" specifies fiftymilliseconds. Another example is ":sleep 4", which sleeps for four seconds.
Even more looping can be done with the ":for" command, see below in
41.8.
41.5 Executing an expression
So far the commands in the script were executed by Vim directly. The":execute" command allows executing the result of an expression. This is avery powerful way to build commands and execute them. An example is to jump to a tag, which is contained in a variable:
:execute "tag " .. tag_name
The ".." is used to concatenate the string "tag " with the value of variable"tag_name". Suppose "tag_name" has the value "get_cmd", then the command thatwill be executed is:
:tag get_cmd
The ":execute" command can only execute colon commands. The ":normal" commandexecutes Normal mode commands. However, its argument is not an expression butthe literal command characters. Example:
:normal gg=G
This jumps to the first line and formats all lines with the "=" operator. To make ":normal" work with an expression, combine ":execute" with it.Example:
:execute "normal " .. normal_commands
The variable "normal_commands" must contain the Normal mode commands. Make sure that the argument for ":normal" is a complete command. OtherwiseVim will run into the end of the argument and abort the command. For example,if you start Insert mode, you must leave Insert mode as well. This works:
:execute "normal Inew text \<Esc>"
This inserts "new text " in the current line. Notice the use of the specialkey "\<Esc>". This avoids having to enter a real
<Esc> character in yourscript.
If you don't want to execute a string but evaluate it to get its expressionvalue, you can use the eval() function:
:let optname = "path":let optval = eval('&' .. optname)A "&" character is prepended to "path", thus the argument to eval() is"&path". The result will then be the value of the
'path' option. The same thing can be done with:
:exe 'let optval = &' .. optname
41.6 Using functions
Vim defines many functions and provides a large amount of functionality thatway. A few examples will be given in this section. You can find the wholelist below:
function-list.
A function is called with the ":call" command. The parameters are passed inbetween parentheses separated by commas. Example:
:call search("Date: ", "W")This calls the search() function, with arguments "Date: " and "W". Thesearch() function uses its first argument as a search pattern and the secondone as flags. The "W" flag means the search doesn't wrap around the end ofthe file.
A function can be called in an expression. Example:
:let line = getline("."):let repl = substitute(line, '\a', "*", "g"):call setline(".", repl)The getline() function obtains a line from the current buffer. Its argumentis a specification of the line number. In this case "." is used, which meansthe line where the cursor is. The substitute() function does something similar to the ":substitute"command. The first argument is the string on which to perform thesubstitution. The second argument is the pattern, the third the replacementstring. Finally, the last arguments are the flags. The setline() function sets the line, specified by the first argument, to anew string, the second argument. In this example the line under the cursor isreplaced with the result of the substitute(). Thus the effect of the threestatements is equal to:
:substitute/\a/*/g
Using the functions becomes interesting when you do more work before andafter the substitute() call.
There are many functions. We will mention them here, grouped by what they areused for. You can find an alphabetical list here:
vimscript-functions.Use
CTRL-] on the function name to jump to detailed help on it.
String manipulation:
string-functionsnr2char()get a character by its number valuelist2str()get a character string from a list of numberschar2nr()get number value of a characterstr2list()get list of numbers from a stringstr2nr()convert a string to a Numberstr2float()convert a string to a Floatprintf()format a string according to "%" itemsescape()escape characters in a string with a '\'shellescape()escape a string for use with a shell commandfnameescape()escape a file name for use with a Vim commandtr()translate characters from one set to anotherstrtrans()translate a string to make it printablekeytrans()translate internal keycodes to a form thatcan be used by
:maptolower()turn a string to lowercasetoupper()turn a string to uppercasecharclass()class of a charactermatch()position where a pattern matches in a stringmatchbufline()all the matches of a pattern in a buffermatchend()position where a pattern match ends in astringmatchfuzzy()fuzzy matches a string in a list of stringsmatchfuzzypos()fuzzy matches a string in a list of stringsmatchstr()match of a pattern in a stringmatchstrlist()all the matches of a pattern in a List ofstringsmatchstrpos()match and positions of a pattern in a stringmatchlist()like matchstr() and also return submatchesstridx()first index of a short string in a long stringstrridx()last index of a short string in a long stringstrlen()length of a string in bytesstrcharlen()length of a string in charactersstrchars()number of characters in a stringstrutf16len()number of UTF-16 code units in a stringstrwidth()size of string when displayedstrdisplaywidth()size of string when displayed, deals with tabssetcellwidths()set character cell width overridesgetcellwidths()get character cell width overridesreverse()reverse the order of characters in a stringsubstitute()substitute a pattern match with a stringsubmatch()get a specific match in ":s" and substitute()strpart()get part of a string using byte indexstrcharpart()get part of a string using char indexslice()take a slice of a string, using char index inVim9 scriptstrgetchar()get character from a string using char indexexpand()expand special keywordsexpandcmd()expand a command like done for
:editiconv()convert text from one encoding to anotherbyteidx()byte index of a character in a stringbyteidxcomp()like byteidx() but count composing characterscharidx()character index of a byte in a stringutf16idx()UTF-16 index of a byte in a stringrepeat()repeat a string multiple timeseval()evaluate a string expressionexecute()execute an Ex command and get the outputwin_execute()like execute() but in a specified windowtrim()trim characters from a stringgettext()lookup message translationitems()get List of String index-character pairs
List manipulation:
list-functionsget()get an item without error for wrong indexlen()number of items in a Listempty()check if List is emptyinsert()insert an item somewhere in a Listadd()append an item to a Listextend()append a List to a Listextendnew()make a new List and append itemsremove()remove one or more items from a Listcopy()make a shallow copy of a Listdeepcopy()make a full copy of a Listfilter()remove selected items from a Listmap()change each List itemmapnew()make a new List with changed itemsforeach()apply function to List itemsreduce()reduce a List to a valueslice()take a slice of a Listsort()sort a Listreverse()reverse the order of items in a Listuniq()remove copies of repeated adjacent itemssplit()split a String into a Listjoin()join List items into a Stringrange()return a List with a sequence of numbersstring()String representation of a Listcall()call a function with List as argumentsindex()index of a value in a Listindexof()index in a List where an expression is truemax()maximum value in a Listmin()minimum value in a Listcount()count number of times a value appears in aListrepeat()repeat a List multiple timesflatten()flatten a Listflattennew()flatten a copy of a Listitems()get List of List index-value pairs
Dictionary manipulation:
dict-functionsget()get an entry without an error for a wrong keylen()number of entries in a Dictionaryhas_key()check whether a key appears in a Dictionaryempty()check if Dictionary is emptyremove()remove an entry from a Dictionaryextend()add entries from one Dictionary to anotherextendnew()make a new Dictionary and append itemsfilter()remove selected entries from a Dictionarymap()change each Dictionary entrymapnew()make a new Dictionary with changed itemsforeach()apply function to Dictionary itemskeys()get List of Dictionary keysvalues()get List of Dictionary valuesitems()get List of Dictionary key-value pairscopy()make a shallow copy of a Dictionarydeepcopy()make a full copy of a Dictionarystring()String representation of a Dictionarymax()maximum value in a Dictionarymin()minimum value in a Dictionarycount()count number of times a value appears
Floating point computation:
float-functionsfloat2nr()convert Float to Numberabs()absolute value (also works for Number)round()round offceil()round upfloor()round downtrunc()remove value after decimal pointfmod()remainder of divisionexp()exponentiallog()natural logarithm (logarithm to base e)log10()logarithm to base 10pow()value of x to the exponent ysqrt()square rootsin()sinecos()cosinetan()tangentasin()arc sineacos()arc cosineatan()arc tangentatan2()arc tangentsinh()hyperbolic sinecosh()hyperbolic cosinetanh()hyperbolic tangentisinf()check for infinityisnan()check for not a number
Blob manipulation:
blob-functionsblob2list()get a list of numbers from a bloblist2blob()get a blob from a list of numbersreverse()reverse the order of numbers in a blobindex()index of a value in a Blobindexof()index in a Blob where an expression is true
Other computation:
bitwise-functionand()bitwise ANDinvert()bitwise invertor()bitwise ORxor()bitwise XORsha256()SHA-256 hashrand()get a pseudo-random numbersrand()initialize seed used by rand()
Variables:
var-functionstype()type of a variableislocked()check if a variable is lockedfuncref()get a Funcref for a function referencefunction()get a Funcref for a function namegetbufvar()get a variable value from a specific buffersetbufvar()set a variable in a specific buffergetwinvar()get a variable from specific windowgettabvar()get a variable from specific tab pagegettabwinvar()get a variable from specific window & tab pagesetwinvar()set a variable in a specific windowsettabvar()set a variable in a specific tab pagesettabwinvar()set a variable in a specific window & tab pagegarbagecollect()possibly free memory
Cursor and mark position:
cursor-functionsmark-functionscol()column number of the cursor or a markvirtcol()screen column of the cursor or a markline()line number of the cursor or markwincol()window column number of the cursorwinline()window line number of the cursorcursor()position the cursor at a line/columnscreencol()get screen column of the cursorscreenrow()get screen row of the cursorscreenpos()screen row and col of a text charactervirtcol2col()byte index of a text character on screengetcurpos()get position of the cursorgetpos()get position of cursor, mark, etc.setpos()set position of cursor, mark, etc.getmarklist()list of global/local marksbyte2line()get line number at a specific byte countline2byte()byte count at a specific linediff_filler()get the number of filler lines above a linescreenattr()get attribute at a screen line/rowscreenchar()get character code at a screen line/rowscreenchars()get character codes at a screen line/rowscreenstring()get string of characters at a screen line/rowcharcol()character number of the cursor or a markgetcharpos()get character position of cursor, mark, etc.setcharpos()set character position of cursor, mark, etc.getcursorcharpos()get character position of the cursorsetcursorcharpos()set character position of the cursor
Working with text in the current buffer:
text-functionsgetline()get a line or list of lines from the buffergetregion()get a region of text from the buffergetregionpos()get a list of positions for a regionsetline()replace a line in the bufferappend()append line or list of lines in the bufferindent()indent of a specific linecindent()indent according to C indentinglispindent()indent according to Lisp indentingnextnonblank()find next non-blank lineprevnonblank()find previous non-blank linesearch()find a match for a patternsearchpos()find a match for a patternsearchcount()get number of matches before/after the cursorsearchpair()find the other end of a start/skip/endsearchpairpos()find the other end of a start/skip/endsearchdecl()search for the declaration of a namegetcharsearch()return character search informationsetcharsearch()set character search information
Working with text in another buffer:getbufline()get a list of lines from the specified buffergetbufoneline()get a one line from the specified buffersetbufline()replace a line in the specified bufferappendbufline()append a list of lines in the specified bufferdeletebufline()delete lines from a specified buffer
system-functionsfile-functionsSystem functions and manipulation of files:glob()expand wildcardsglobpath()expand wildcards in a number of directoriesglob2regpat()convert a glob pattern into a search patternfindfile()find a file in a list of directoriesfinddir()find a directory in a list of directoriesresolve()find out where a shortcut points tofnamemodify()modify a file namepathshorten()shorten directory names in a pathsimplify()simplify a path without changing its meaningexecutable()check if an executable program existsexepath()full path of an executable programfilereadable()check if a file can be readfilewritable()check if a file can be written togetfperm()get the permissions of a filesetfperm()set the permissions of a filegetftype()get the kind of a fileisabsolutepath()check if a path is absoluteisdirectory()check if a directory existsgetfsize()get the size of a filegetcwd()get the current working directoryhaslocaldir()check if current window used
:lcd or
:tcdtempname()get the name of a temporary filemkdir()create a new directorychdir()change current working directorydelete()delete a filerename()rename a filesystem()get the result of a shell command as a stringsystemlist()get the result of a shell command as a listenviron()get all environment variablesgetenv()get one environment variablesetenv()set an environment variablehostname()name of the systemreadfile()read a file into a List of linesreadblob()read a file into a Blobreaddir()get a List of file names in a directorywritefile()write a List of lines or Blob into a filefilecopy()copy a file
{from} to
{to} Date and Time:
date-functionstime-functionsgetftime()get last modification time of a filelocaltime()get current time in secondsstrftime()convert time to a stringstrptime()convert a date/time string to timereltime()get the current or elapsed time accuratelyreltimestr()convert reltime() result to a stringreltimefloat()convert reltime() result to a Float
buffer-functionswindow-functionsarg-functionsBuffers, windows and the argument list:argc()number of entries in the argument listargidx()current position in the argument listarglistid()get id of the argument listargv()get one entry from the argument listbufadd()add a file to the list of buffersbufexists()check if a buffer existsbuflisted()check if a buffer exists and is listedbufload()ensure a buffer is loadedbufloaded()check if a buffer exists and is loadedbufname()get the name of a specific bufferbufnr()get the buffer number of a specific buffertabpagebuflist()return List of buffers in a tab pagetabpagenr()get the number of a tab pagetabpagewinnr()like winnr() for a specified tab pagewinnr()get the window number for the current windowbufwinid()get the window ID of a specific bufferbufwinnr()get the window number of a specific bufferwinbufnr()get the buffer number of a specific windowwin_findbuf()find windows containing a bufferwin_getid()get window ID of a windowwin_gettype()get type of windowwin_gotoid()go to window with IDwin_id2tabwin()get tab and window nr from window IDwin_id2win()get window nr from window IDwin_move_separator()move window vertical separatorwin_move_statusline()move window status linewin_splitmove()move window to a split of another windowgetbufinfo()get a list with buffer informationgettabinfo()get a list with tab page informationgetwininfo()get a list with window informationgetchangelist()get a list of change list entriesgetjumplist()get a list of jump list entriesswapfilelist()list of existing swap files in
'directory'swapinfo()information about a swap fileswapname()get the swap file path of a buffer
Command line:
command-line-functionsgetcmdcomplpat()get completion pattern of the current commandlinegetcmdcompltype()get the type of the current command linecompletiongetcmdline()get the current command line inputgetcmdprompt()get the current command line promptgetcmdpos()get position of the cursor in the command linegetcmdscreenpos()get screen position of the cursor in thecommand linesetcmdline()set the current command linesetcmdpos()set position of the cursor in the command linegetcmdtype()return the current command-line typegetcmdwintype()return the current command-line window typegetcompletion()list of command-line completion matchesgetcompletiontype()get the type of the command-line completionfor specified stringfullcommand()get full command namecmdcomplete_info()get command-line completion information
Quickfix and location lists:
quickfix-functionsgetqflist()list of quickfix errorssetqflist()modify a quickfix listgetloclist()list of location list itemssetloclist()modify a location list
Insert mode completion:
completion-functionscomplete()set found matchescomplete_add()add to found matchescomplete_check()check if completion should be abortedcomplete_info()get current completion informationpreinserted()check if text is inserted after cursorpumvisible()check if the popup menu is displayedpum_getpos()position and size of popup menu if visible
Folding:
folding-functionsfoldclosed()check for a closed fold at a specific linefoldclosedend()like foldclosed() but return the last linefoldlevel()check for the fold level at a specific linefoldtext()generate the line displayed for a closed foldfoldtextresult()get the text displayed for a closed fold
Syntax and highlighting:
syntax-functionshighlighting-functionsclearmatches()clear all matches defined by
matchadd() andthe
:match commandsgetmatches()get all matches defined by
matchadd() andthe
:match commandshlexists()check if a highlight group existshlID()get ID of a highlight groupsynID()get syntax ID at a specific positionsynIDattr()get a specific attribute of a syntax IDsynIDtrans()get translated syntax IDsynstack()get list of syntax IDs at a specific positionsynconcealed()get info about (syntax) concealingdiff_hlID()get highlight ID for diff mode at a positionmatchadd()define a pattern to highlight (a "match")matchaddpos()define a list of positions to highlightmatcharg()get info about
:match argumentsmatchdelete()delete a match defined by
matchadd() or a
:match commandsetmatches()restore a list of matches saved by
getmatches()Spelling:
spell-functionsspellbadword()locate badly spelled word at or after cursorspellsuggest()return suggested spelling correctionssoundfold()return the sound-a-like equivalent of a word
History:
history-functionshistadd()add an item to a historyhistdel()delete an item from a historyhistget()get an item from a historyhistnr()get highest index of a history list
Interactive:
interactive-functionsbrowse()put up a file requesterbrowsedir()put up a directory requesterconfirm()let the user make a choicegetchar()get a character from the usergetcharmod()get modifiers for the last typed charactergetmousepos()get last known mouse positionfeedkeys()put characters in the typeahead queueinput()get a line from the userinputlist()let the user pick an entry from a listinputsecret()get a line from the user without showing itinputdialog()get a line from the user in a dialoginputsave()save and clear typeaheadinputrestore()restore typeahead
GUI:
gui-functionsgetfontname()get name of current font being usedgetwinpos()position of the Vim windowgetwinposx()X position of the Vim windowgetwinposy()Y position of the Vim windowballoon_show()set the balloon contentballoon_split()split a message for a balloonballoon_gettext()get the text in the balloon
Vim server:
server-functionsserverlist()return the list of server namesremote_startserver()run a serverremote_send()send command characters to a Vim serverremote_expr()evaluate an expression in a Vim serverserver2client()send a reply to a client of a Vim serverremote_peek()check if there is a reply from a Vim serverremote_read()read a reply from a Vim serverforeground()move the Vim window to the foregroundremote_foreground()move the Vim server window to the foreground
Window size and position:
window-size-functionswinheight()get height of a specific windowwinwidth()get width of a specific windowwin_screenpos()get screen position of a windowwinlayout()get layout of windows in a tab pagewinrestcmd()return command to restore window sizeswinsaveview()get view of current windowwinrestview()restore saved view of current window
Mappings and Menus:
mapping-functionsdigraph_get()get
digraphdigraph_getlist()get all
digraphsdigraph_set()register
digraphdigraph_setlist()register multiple
digraphshasmapto()check if a mapping existsmapcheck()check if a matching mapping existsmaparg()get rhs of a mappingmaplist()get list of all mappingsmapset()restore a mappingmenu_info()get information about a menu itemwildmenumode()check if the wildmode is activewildtrigger()start wildcard expansion
Signs:
sign-functionssign_define()define or update a signsign_getdefined()get a list of defined signssign_getplaced()get a list of placed signssign_jump()jump to a signsign_place()place a signsign_placelist()place a list of signssign_undefine()undefine a signsign_unplace()unplace a signsign_unplacelist()unplace a list of signs
Testing:
test-functionsassert_equal()assert that two expressions values are equalassert_equalfile()assert that two file contents are equalassert_notequal()assert that two expressions values are notequalassert_inrange()assert that an expression is inside a rangeassert_match()assert that a pattern matches the valueassert_notmatch()assert that a pattern does not match the valueassert_false()assert that an expression is falseassert_true()assert that an expression is trueassert_exception()assert that a command throws an exceptionassert_beeps()assert that a command beepsassert_nobeep()assert that a command does not cause a beepassert_fails()assert that a command failsassert_report()report a test failure
Timers:
timer-functionstimer_start()create a timertimer_pause()pause or unpause a timertimer_stop()stop a timertimer_stopall()stop all timerstimer_info()get information about timerswait()wait for a condition
Tags:
tag-functionstaglist()get list of matching tagstagfiles()get a list of tags filesgettagstack()get the tag stack of a windowsettagstack()modify the tag stack of a window
Prompt Buffer:
promptbuffer-functionsprompt_getprompt()get the effective prompt text for a bufferprompt_setcallback()set prompt callback for a bufferprompt_setinterrupt()set interrupt callback for a bufferprompt_setprompt()set the prompt text for a buffer
Registers:
register-functionsgetreg()get contents of a registergetreginfo()get information about a registergetregtype()get type of a registersetreg()set contents and type of a registerreg_executing()return the name of the register being executedreg_recording()return the name of the register being recorded
Context Stack:
ctx-functionsctxget()return context at given index from topctxpop()pop and restore top contextctxpush()push given contextctxset()set context at given index from topctxsize()return context stack size
Various:
various-functionsmode()get current editing modevisualmode()last visual mode usedexists()check if a variable, function, etc. existshas()check if a feature is supported in Vimchangenr()return number of most recent changedid_filetype()check if a FileType autocommand was usedeventhandler()check if invoked by an event handlergetpid()get process ID of Vimgetscriptinfo()get list of sourced Vim scriptsgetstacktrace()get current stack trace of Vim scripts
libcall()call a function in an external librarylibcallnr()idem, returning a number
undofile()get the name of the undo fileundotree()return the state of the undo tree for a buffer
wordcount()get byte/word/char count of buffer
luaeval()evaluate
Lua expressionpy3eval()evaluate
Python expressionpyeval()evaluate
Python expressionpyxeval()evaluate
python_x expressionrubyeval()evaluate
Ruby expression
debugbreak()interrupt a program being debugged
Vim enables you to define your own functions. The basic function declarationbegins as follows:
:function {name}({var1}, {var2}, ...): {body}:endfunctionNote:Function names must begin with a capital letter.
Let's define a short function to return the smaller of two numbers. It startswith this line:
:function Min(num1, num2)
This tells Vim that the function is named "Min" and it takes two arguments:"num1" and "num2". The first thing you need to do is to check to see which number is smaller:
: if a:num1 < a:num2
The special prefix "a:" tells Vim that the variable is a function argument.Let's assign the variable "smaller" the value of the smallest number:
: if a:num1 < a:num2: let smaller = a:num1: else: let smaller = a:num2: endif
The variable "smaller" is a local variable. Variables used inside a functionare local unless prefixed by something like "g:", "a:", or "s:".
Note:To access a global variable from inside a function you must prepend"g:" to it. Thus "g:today" inside a function is used for the globalvariable "today", and "today" is another variable, local to thefunction.
You now use the ":return" statement to return the smallest number to the user.Finally, you end the function:
: return smaller:endfunction
The complete function definition is as follows:
:function Min(num1, num2): if a:num1 < a:num2: let smaller = a:num1: else: let smaller = a:num2: endif: return smaller:endfunction
For people who like short functions, this does the same thing:
:function Min(num1, num2): if a:num1 < a:num2: return a:num1: endif: return a:num2:endfunction
A user defined function is called in exactly the same way as a built-infunction. Only the name is different. The Min function can be used likethis:
:echo Min(5, 8)
Only now will the function be executed and the lines be interpreted by Vim.If there are mistakes, like using an undefined variable or function, you willnow get an error message. When defining the function these errors are notdetected.
When a function reaches ":endfunction" or ":return" is used without anargument, the function returns zero.
To redefine a function that already exists, use the ! for the ":function"command:
:function! Min(num1, num2, num3)
USING A RANGE
The ":call" command can be given a line range. This can have one of twomeanings. When a function has been defined with the "range" keyword, it willtake care of the line range itself. The function will be passed the variables "a:firstline" and "a:lastline".These will have the line numbers from the range the function was called with.Example:
:function Count_words() range: let lnum = a:firstline: let n = 0: while lnum <= a:lastline: let n = n + len(split(getline(lnum))): let lnum = lnum + 1: endwhile: echo "found " .. n .. " words":endfunction
You can call this function with:
:10,30call Count_words()
It will be executed once and echo the number of words. The other way to use a line range is by defining a function without the"range" keyword. The function will be called once for every line in therange, with the cursor in that line. Example:
:function Number(): echo "line " .. line(".") .. " contains: " .. getline("."):endfunctionIf you call this function with:
:10,15call Number()
The function will be called six times.
VARIABLE NUMBER OF ARGUMENTS
Vim enables you to define functions that have a variable number of arguments.The following command, for instance, defines a function that must have 1argument (start) and can have up to 20 additional arguments:
:function Show(start, ...)
The variable "a:1" contains the first optional argument, "a:2" the second, andso on. The variable "a:0" contains the number of extra arguments. For example:
:function Show(start, ...): echohl Title: echo "start is " .. a:start: echohl None: let index = 1: while index <= a:0: echo " Arg " .. index .. " is " .. a:{index}: let index = index + 1: endwhile: echo "":endfunctionThis uses the ":echohl" command to specify the highlighting used for thefollowing ":echo" command. ":echohl None" stops it again. The ":echon"command works like ":echo", but doesn't output a line break.
You can also use the a:000 variable, it is a List of all the "..." arguments.See
a:000.
LISTING FUNCTIONS
The ":function" command lists the names and arguments of all user-definedfunctions:
:function
function Show(start, ...)
function GetVimIndent()
function SetSyn(name)
To see what a function does, use its name as an argument for ":function":
:function SetSyn
1 if &syntax == ''
2 let &syntax = a:name
3 endif
endfunction
DEBUGGING
The line number is useful for when you get an error message or when debugging.See
debug-scripts about debugging mode. You can also set the
'verbose' option to 12 or higher to see all functioncalls. Set it to 15 or higher to see every executed line.
DELETING A FUNCTION
To delete the Show() function:
:delfunction Show
You get an error when the function doesn't exist.
FUNCTION REFERENCES
Sometimes it can be useful to have a variable point to one function oranother. You can do it with the function() function. It turns the name of afunction into a reference:
:let result = 0" or 1:function! Right(): return 'Right!':endfunc:function! Wrong(): return 'Wrong!':endfunc::if result == 1: let Afunc = function('Right'):else: let Afunc = function('Wrong'):endif:echo call(Afunc, [])Note that the name of a variable that holds a function reference must startwith a capital. Otherwise it could be confused with the name of a builtinfunction. The way to invoke a function that a variable refers to is with the call()function. Its first argument is the function reference, the second argumentis a List with arguments.
Function references are most useful in combination with a Dictionary, as isexplained in the next section.
More information about defining your own functions here:
user-function.
41.8 Lists and Dictionaries
So far we have used the basic types String and Number. Vim also supports twocomposite types: List and Dictionary.
A List is an ordered sequence of things. The things can be any kind of value,thus you can make a List of numbers, a List of Lists and even a List of mixeditems. To create a List with three strings:
:let alist = ['aap', 'mies', 'noot']
The List items are enclosed in square brackets and separated by commas. Tocreate an empty List:
:let alist = []
You can add items to a List with the add() function:
:let alist = []:call add(alist, 'foo'):call add(alist, 'bar'):echo alist
List concatenation is done with +:
:echo alist + ['foo', 'bar']
['foo', 'bar', 'foo', 'bar']
Or, if you want to extend a List directly:
:let alist = ['one']:call extend(alist, ['two', 'three']):echo alist
Notice that using add() will have a different effect:
:let alist = ['one']:call add(alist, ['two', 'three']):echo alist
['one', ['two', 'three']]
The second argument of add() is added as a single item.
FOR LOOP
One of the nice things you can do with a List is iterate over it:
:let alist = ['one', 'two', 'three']:for n in alist: echo n:endfor
This will loop over each element in List "alist", assigning the value tovariable "n". The generic form of a for loop is:
:for {varname} in {listexpression}: {commands}:endforTo loop a certain number of times you need a List of a specific length. Therange() function creates one for you:
:for a in range(3): echo a:endfor
Notice that the first item of the List that range() produces is zero, thus thelast item is one less than the length of the list. You can also specify the maximum value, the stride and even go backwards:
:for a in range(8, 4, -2): echo a:endfor
A more useful example, looping over lines in the buffer:
:for line in getline(1, 20): if line =~ "Date: ": echo matchstr(line, 'Date: \zs.*'): endif:endfor
This looks into lines 1 to 20 (inclusive) and echoes any date found in there.
DICTIONARIES
A Dictionary stores key-value pairs. You can quickly lookup a value if youknow the key. A Dictionary is created with curly braces:
:let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}Now you can lookup words by putting the key in square brackets:
:echo uk2nl['two']
The generic form for defining a Dictionary is:
{<key> : <value>, ...}An empty Dictionary is one without any keys:
{}The possibilities with Dictionaries are numerous. There are various functionsfor them as well. For example, you can obtain a list of the keys and loopover them:
:for key in keys(uk2nl): echo key:endfor
You will notice the keys are not ordered. You can sort the list to get aspecific order:
:for key in sort(keys(uk2nl)): echo key:endfor
But you can never get back the order in which items are defined. For that youneed to use a List, it stores items in an ordered sequence.
DICTIONARY FUNCTIONS
The items in a Dictionary can normally be obtained with an index in squarebrackets:
:echo uk2nl['one']
A method that does the same, but without so many punctuation characters:
:echo uk2nl.one
This only works for a key that is made of ASCII letters, digits and theunderscore. You can also assign a new value this way:
:let uk2nl.four = 'vier':echo uk2nl
{'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'}
And now for something special: you can directly define a function and store areference to it in the dictionary:
:function uk2nl.translate(line) dict: return join(map(split(a:line), 'get(self, v:val, "???")')):endfunction
Let's first try it out:
:echo uk2nl.translate('three two five one')The first special thing you notice is the "dict" at the end of the ":function"line. This marks the function as being used from a Dictionary. The "self"local variable will then refer to that Dictionary. Now let's break up the complicated return command:
split(a:line)
The split() function takes a string, chops it into whitespace separated wordsand returns a list with these words. Thus in the example it returns:
:echo split('three two five one')['three', 'two', 'five', 'one']
This list is the first argument to the map() function. This will go throughthe list, evaluating its second argument with "v:val" set to the value of eachitem. This is a shortcut to using a for loop. This command:
:let alist = map(split(a:line), 'get(self, v:val, "???")')
Is equivalent to:
:let alist = split(a:line):for idx in range(len(alist)): let alist[idx] = get(self, alist[idx], "???"):endfor
The get() function checks if a key is present in a Dictionary. If it is, thenthe value is retrieved. If it isn't, then the default value is returned, inthe example it's '???'. This is a convenient way to handle situations where akey may not be present and you don't want an error message.
The join() function does the opposite of split(): it joins together a list ofwords, putting a space in between. This combination of split(), map() and join() is a nice way to filter a lineof words in a very compact way.
OBJECT ORIENTED PROGRAMMING
Now that you can put both values and functions in a Dictionary, you canactually use a Dictionary like an object. Above we used a Dictionary for translating Dutch to English. We might wantto do the same for other languages. Let's first make an object (akaDictionary) that has the translate function, but no words to translate:
:let transdict = {}:function transdict.translate(line) dict: return join(map(split(a:line), 'get(self.words, v:val, "???")')):endfunctionIt's slightly different from the function above, using 'self.words' to lookupword translations. But we don't have a self.words. Thus you could call thisan abstract class.
Now we can instantiate a Dutch translation object:
:let uk2nl = copy(transdict):let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'}:echo uk2nl.translate('three one')And a German translator:
:let uk2de = copy(transdict):let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}:echo uk2de.translate('three one')You see that the copy() function is used to make a copy of the "transdict"Dictionary and then the copy is changed to add the words. The originalremains the same, of course.
Now you can go one step further, and use your preferred translator:
:if $LANG =~ "de": let trans = uk2de:else: let trans = uk2nl:endif:echo trans.translate('one two three')Here "trans" refers to one of the two objects (Dictionaries). No copy ismade. More about List and Dictionary identity can be found at
list-identityand
dict-identity.
Now you might use a language that isn't supported. You can overrule thetranslate() function to do nothing:
:let uk2uk = copy(transdict):function! uk2uk.translate(line): return a:line:endfunction:echo uk2uk.translate('three one wladiwostok')Notice that a ! was used to overwrite the existing function reference. Nowuse "uk2uk" when no recognized language is found:
:if $LANG =~ "de": let trans = uk2de:elseif $LANG =~ "nl": let trans = uk2nl:else: let trans = uk2uk:endif:echo trans.translate('one two three')Let's start with an example:
:try: read ~/templates/pascal.tmpl:catch /E484:/: echo "Sorry, the Pascal template file cannot be found.":endtry
The ":read" command will fail if the file does not exist. Instead ofgenerating an error message, this code catches the error and gives the user anice message.
For the commands in between ":try" and ":endtry" errors are turned intoexceptions. An exception is a string. In the case of an error the stringcontains the error message. And every error message has a number. In thiscase, the error we catch contains "E484:". This number is guaranteed to staythe same (the text may change, e.g., it may be translated).
When the ":read" command causes another error, the pattern "E484:" will notmatch in it. Thus this exception will not be caught and result in the usualerror message and execution is aborted.
You might be tempted to do this:
:try: read ~/templates/pascal.tmpl:catch: echo "Sorry, the Pascal template file cannot be found.":endtry
This means all errors are caught. But then you will not see errors that areuseful, such as "E21: Cannot make changes,
'modifiable' is off".
Another useful mechanism is the ":finally" command:
:let tmp = tempname():try: exe ".,$write " .. tmp: exe "!filter " .. tmp: .,$delete: exe "$read " .. tmp:finally: call delete(tmp):endtry
This filters the lines from the cursor until the end of the file through the"filter" command, which takes a file name argument. No matter if thefiltering works, something goes wrong in between ":try" and ":finally" or theuser cancels the filtering by pressing
CTRL-C, the "call delete(tmp)" isalways executed. This makes sure you don't leave the temporary file behind.
More information about exception handling can be found in the referencemanual:
exception-handling.
Here is a summary of items that apply to Vim scripts. They are also mentionedelsewhere, but form a nice checklist.
The end-of-line character depends on the system. For Vim scripts it isrecommended to always use the Unix fileformat. Lines are then separated withthe Newline character. This also works on any other system. That way you cancopy your Vim scripts from MS-Windows to Unix and they still work. See
:source_crnl. To be sure it is set right, do this before writing the file:
:setlocal fileformat=unix
When using "dos" fileformat, lines are separated with CR-NL, two characters.The CR character causes various problems, better avoid this.
WHITE SPACE
Blank lines are allowed in a script and ignored.
Leading whitespace characters (blanks and TABs) are ignored, except when using
:let-heredoc without "trim".
Trailing whitespace is often ignored, but not always. One command thatincludes it ismap. You have to watch out for that, it can cause hard tounderstand mistakes. A generic solution is to never use trailing white space,unless you really need it.
To include a whitespace character in the value of an option, it must beescaped by a "\" (backslash) as in the following example:
:set tags=my\ nice\ file
The same example written as:
:set tags=my nice file
will issue an error, because it is interpreted as:
:set tags=my:set nice:set file
COMMENTS
The character " (the double quote mark) starts a comment. Everything afterand including this character until the end-of-line is considered a comment andis ignored, except for commands that don't consider comments, as shown inexamples below. A comment can start on any character position on the line.
There is a little "catch" with comments for some commands. Examples:
:abbrev dev development" shorthand:map <F3> o#include" insert include:execute cmd" do it:!ls *.c" list C files
The abbreviation "dev" will be expanded to 'development " shorthand'. Themapping of
<F3> will actually be the whole line after the 'o# ....' includingthe '" insert include'. The "execute" command will give an error. The "!"command will send everything after it to the shell, causing an error for anunmatched '"' character. There can be no comment after ":map", ":abbreviate", ":execute" and "!"commands (there are a few more commands with this restriction). For the":map", ":abbreviate" and ":execute" commands there is a trick:
:abbrev dev development|" shorthand:map <F3> o#include|" insert include:execute cmd|" do it
With the '|' character the command is separated from the next one. And thatnext command is only a comment. For the last command you need to do twothings:
:execute and use '|':
:exe '!ls *.c'|" list C files
Notice that there is no white space before the '|' in the abbreviation andmapping. For these commands, any character until the end-of-line or '|' isincluded. As a consequence of this behavior, you don't always see thattrailing whitespace is included:
:map <F4> o#include
To spot these problems, you can set the
'list' option when editing vimrcfiles.
For Unix there is one special way to comment a line, that allows making a Vimscript executable:
#!/usr/bin/env vim -Secho "this is a Vim script"quit
The "#" command by itself lists a line with the line number. Adding anexclamation mark changes it into doing nothing, so that you can add the shellcommand to execute the rest of the file.
:#!-SPITFALLS
Even bigger problem arises in the following example:
:map ,ab o#include:unmap ,ab
Here the unmap command will not work, because it tries to unmap ",ab ". Thisdoes not exist as a mapped sequence. An error will be issued, which is veryhard to identify, because the ending whitespace character in ":unmap ,ab " isnot visible.
And this is the same as what happens when one uses a comment after an "unmap"command:
:unmap ,ab " comment
Here the comment part will be ignored. However, Vim will try to unmap',ab ', which does not exist. Rewrite it as:
:unmap ,ab| " comment
RESTORING THE VIEW
Sometimes you want to make a change and go back to where the cursor was.Restoring the relative position would also be nice, so that the same lineappears at the top of the window. This example yanks the current line, puts it above the first line in thefile and then restores the view:
map ,p ma"aYHmbgg"aP`bzt`a
What this does:
ma"aYHmbgg"aP`bzt`a
maset mark a at cursor position "aYyank current line into register a Hmbgo to top line in window and set mark b theregggo to first line in file "aPput the yanked line above itbgo back to top line in display ztposition the text in the window as beforeago back to saved cursor position
PACKAGING
To avoid your function names to interfere with functions that you get fromothers, use this scheme:
Prepend a unique string before each function name. I often use an abbreviation. For example, "OW_" is used for the option window functions.
Put the definition of your functions together in a file. Set a global variable to indicate that the functions have been loaded. When sourcing the file again, first unload the functions.Example:
" This is the XXX packageif exists("XXX_loaded") delfun XXX_one delfun XXX_twoendiffunction XXX_one(a) ... body of function ...endfunfunction XXX_two(b) ... body of function ...endfunlet XXX_loaded = 1==============================================================================
41.11 Writing a plugin
write-pluginYou can write a Vim script in such a way that many people can use it. This iscalled a plugin. Vim users can drop your script in their plugin directory anduse its features right away
add-plugin.
There are actually two types of plugins:
global plugins: For all types of files.filetype plugins: Only for files of a specific type.
In this section the first type is explained. Most items are also relevant forwriting filetype plugins. The specifics for filetype plugins are in the nextsection
write-filetype-plugin.
NAME
First of all you must choose a name for your plugin. The features providedby the plugin should be clear from its name. And it should be unlikely thatsomeone else writes a plugin with the same name but which does somethingdifferent. And please limit the name to 8 characters, to avoid problems onold MS-Windows systems.
A script that corrects typing mistakes could be called "typecorr.vim". Wewill use it here as an example.
For the plugin to work for everybody, it should follow a few guidelines. Thiswill be explained step-by-step. The complete example plugin is at the end.
BODY
Let's start with the body of the plugin, the lines that do the actual work:
14iabbrev teh the15iabbrev otehr other16iabbrev wnat want17iabbrev synchronisation18\ synchronization19let s:count = 4
The actual list should be much longer, of course.
The line numbers have only been added to explain a few things, don't put themin your plugin file!
HEADER
You will probably add new corrections to the plugin and soon have severalversions lying around. And when distributing this file, people will want toknow who wrote this wonderful plugin and where they can send remarks.Therefore, put a header at the top of your plugin:
1" Vim global plugin for correcting typing mistakes2" Last Change:2000 Oct 153" Maintainer:Bram Moolenaar <[email protected]>
About copyright and licensing: Since plugins are very useful and it's hardlyworth restricting their distribution, please consider making your plugineither public domain or use the Vim
license. A short note about this nearthe top of the plugin should be sufficient. Example:
4" License:This file is placed in the public domain.
LINE CONTINUATION, AVOIDING SIDE EFFECTS
use-cpo-saveIn line 18 above, the line-continuation mechanism is used
line-continuation.Users with
'compatible' set will run into trouble here, they will get an errormessage. We can't just reset
'compatible', because that has a lot of sideeffects. To avoid this, we will set the
'cpoptions' option to its Vim defaultvalue and restore it later. That will allow the use of line-continuation andmake the script work for most people. It is done like this:
11let s:save_cpo = &cpo12set cpo&vim..42let &cpo = s:save_cpo43unlet s:save_cpo
We first store the old value of
'cpoptions' in the s:save_cpo variable. Atthe end of the plugin this value is restored.
Notice that a script-local variable is used
s:var. A global variable couldalready be in use for something else. Always use script-local variables forthings that are only used in the script.
NOT LOADING
It's possible that a user doesn't always want to load this plugin. Or thesystem administrator has dropped it in the system-wide plugin directory, but auser has their own plugin they want to use. Then the user must have a chance todisable loading this specific plugin. This will make it possible:
6if exists("g:loaded_typecorr")7 finish8endif9let g:loaded_typecorr = 1This also avoids that when the script is loaded twice it would cause errormessages for redefining functions and cause trouble for autocommands that areadded twice.
The name is recommended to start with "loaded_" and then the file name of theplugin, literally. The "g:" is prepended just to avoid mistakes when usingthe variable in a function (without "g:" it would be a variable local to thefunction).
Using "finish" stops Vim from reading the rest of the file, it's much quickerthan using if-endif around the whole file.
MAPPING
Now let's make the plugin more interesting: We will add a mapping that adds acorrection for the word under the cursor. We could just pick a key sequencefor this mapping, but the user might already use it for something else. Toallow the user to define which keys a mapping in a plugin uses, the
<Leader>item can be used:
22 map <unique> <Leader>a <Plug>TypecorrAdd;
The "<Plug>TypecorrAdd;" thing will do the work, more about that further on.
The user can set the "mapleader" variable to the key sequence that they wantthis mapping to start with. Thus if the user has done:
let mapleader = "_"
the mapping will define "_a". If the user didn't do this, the default valuewill be used, which is a backslash. Then a map for "\a" will be defined.
Note that
<unique> is used, this will cause an error message if the mappingalready happened to exist.
:map-<unique>But what if the user wants to define their own key sequence? We can allow thatwith this mechanism:
21if !hasmapto('<Plug>TypecorrAdd;')22 map <unique> <Leader>a <Plug>TypecorrAdd;23endifThis checks if a mapping to "<Plug>TypecorrAdd;" already exists, and onlydefines the mapping from "<Leader>a" if it doesn't. The user then has achance of putting this in their vimrc file:
map ,c <Plug>TypecorrAdd;
Then the mapped key sequence will be ",c" instead of "_a" or "\a".
PIECES
If a script gets longer, you often want to break up the work in pieces. Youcan use functions or mappings for this. But you don't want these functionsand mappings to interfere with the ones from other scripts. For example, youcould define a function Add(), but another script could try to define the samefunction. To avoid this, we define the function local to the script byprepending it with "s:".
We will define a function that adds a new typing correction:
30function s:Add(from, correct)31 let to = input("type the correction for " .. a:from .. ": ")32 exe ":iabbrev " .. a:from .. " " .. to..36endfunctionNow we can call the function s:Add() from within this script. If anotherscript also defines s:Add(), it will be local to that script and can onlybe called from the script it was defined in. There can also be a global Add()function (without the "s:"), which is again another function.
<SID> can be used with mappings. It generates a script ID, which identifiesthe current script. In our typing correction plugin we use it like this:
24noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add..28noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>Thus when a user types "\a", this sequence is invoked:
\a -> <Plug>TypecorrAdd; -> <SID>Add -> :call <SID>Add()
If another script also maps
<SID>Add, it will get another script ID andthus define another mapping.
Note that instead of s:Add() we use<SID>Add() here. That is because themapping is typed by the user, thus outside of the script. The<SID> istranslated to the script ID, so that Vim knows in which script to look forthe Add() function.
This is a bit complicated, but it's required for the plugin to work togetherwith other plugins. The basic rule is that you use<SID>Add() in mappings ands:Add() in other places (the script itself, autocommands, user commands).
We can also add a menu entry to do the same as the mapping:
26noremenu <script> Plugin.Add\ Correction <SID>Add
The "Plugin" menu is recommended for adding menu items for plugins. In thiscase only one item is used. When adding more items, creating a submenu isrecommended. For example, "Plugin.CVS" could be used for a plugin that offersCVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
Note that in line 28 ":noremap" is used to avoid that any other mappings causetrouble. Someone may have remapped ":call", for example. In line 24 we alsouse ":noremap", but we do want "<SID>Add" to be remapped. This is why"<script>" is used here. This only allows mappings which are local to thescript.
:map-<script> The same is done in line 26 for ":noremenu".
:menu-<script>Both<SID> and<Plug> are used to avoid that mappings of typed keys interferewith mappings that are only to be used from other mappings. Note thedifference between using<SID> and<Plug>:
<Plug>is visible outside of the script. It is used for mappings which theuser might want to map a key sequence to.<Plug> is a special codethat a typed key will never produce.To make it very unlikely that other plugins use the same sequence ofcharacters, use this structure:<Plug> scriptname mapnameIn our example the scriptname is "Typecorr" and the mapname is "Add".We add a semicolon as the terminator. This results in"<Plug>TypecorrAdd;". Only the first character of scriptname andmapname is uppercase, so that we can see where mapname starts.
<SID>is the script ID, a unique identifier for a script.Internally Vim translates<SID> to "<SNR>123_", where "123" can be anynumber. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"in one script, and "<SNR>22_Add()" in another. You can see this ifyou use the ":function" command to get a list of functions. Thetranslation of<SID> in mappings is exactly the same, that's how youcan call a script-local function from a mapping.
USER COMMAND
Now let's add a user command to add a correction:
38if !exists(":Correct")39 command -nargs=1 Correct :call s:Add(<q-args>, 0)40endifThe user command is defined only if no command with the same name alreadyexists. Otherwise we would get an error here. Overriding the existing usercommand with ":command!" is not a good idea, this would probably make the userwonder why the command they defined themself doesn't work.
:commandSCRIPT VARIABLES
When a variable starts with "s:" it is a script variable. It can only be usedinside a script. Outside the script it's not visible. This avoids troublewith using the same variable name in different scripts. The variables will bekept as long as Vim is running. And the same variables are used when sourcingthe same script again.
s:varThe fun is that these variables can also be used in functions, autocommandsand user commands that are defined in the script. In our example we can adda few lines to count the number of corrections:
19let s:count = 4..30function s:Add(from, correct)..34 let s:count = s:count + 135 echo s:count .. " corrections now"36endfunction
First s:count is initialized to 4 in the script itself. When later thes:Add() function is called, it increments s:count. It doesn't matter fromwhere the function was called, since it has been defined in the script, itwill use the local variables from this script.
THE RESULT
Here is the resulting complete example:
1" Vim global plugin for correcting typing mistakes 2" Last Change:2000 Oct 15 3" Maintainer:Bram Moolenaar <[email protected]> 4" License:This file is placed in the public domain. 5 6if exists("g:loaded_typecorr") 7 finish 8endif 9let g:loaded_typecorr = 11011let s:save_cpo = &cpo12set cpo&vim1314iabbrev teh the15iabbrev otehr other16iabbrev wnat want17iabbrev synchronisation18\ synchronization19let s:count = 42021if !hasmapto('<Plug>TypecorrAdd;')22 map <unique> <Leader>a <Plug>TypecorrAdd;23endif24noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add2526noremenu <script> Plugin.Add\ Correction <SID>Add2728noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>2930function s:Add(from, correct)31 let to = input("type the correction for " .. a:from .. ": ")32 exe ":iabbrev " .. a:from .. " " .. to33 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif34 let s:count = s:count + 135 echo s:count .. " corrections now"36endfunction3738if !exists(":Correct")39 command -nargs=1 Correct :call s:Add(<q-args>, 0)40endif4142let &cpo = s:save_cpo43unlet s:save_cpoLine 33 wasn't explained yet. It applies the new correction to the word underthe cursor. The
:normal command is used to use the new abbreviation. Notethat mappings and abbreviations are expanded here, even though the functionwas called from a mapping defined with ":noremap".
Using "unix" for the
'fileformat' option is recommended. The Vim scripts willthen work everywhere. Scripts with
'fileformat' set to "dos" do not work onUnix. Also see
:source_crnl. To be sure it is set right, do this beforewriting the file:
:set fileformat=unix
It's a good idea to also write some documentation for your plugin. Especiallywhen its behavior can be changed by the user. See
add-local-help for howthey are installed.
Here is a simple example for a plugin help file, called "typecorr.txt":
1*typecorr.txt*Plugin for correcting typing mistakes 2 3If you make typing mistakes, this plugin will have them corrected 4automatically. 5 6There are currently only a few corrections. Add your own if you like. 7 8Mappings: 9<Leader>a or <Plug>TypecorrAdd;10Add a correction for the word under the cursor.1112Commands:13:Correct {word}14Add a correction for {word}.1516*typecorr-settings*17This plugin doesn't have any settings.The first line is actually the only one for which the format matters. It willbe extracted from the help file to be put in the "LOCAL ADDITIONS:" section offirst line. After adding your help file do ":help" and check that the entriesline up nicely.
You can add more tags inside ** in your help file. But be careful not to useexisting help tags. You would probably use the name of your plugin in most ofthem, like "typecorr-settings" in the example.
Using references to other parts of the help in || is recommended. This makesit easy for the user to find associated help.
If your filetype is not already detected by Vim, you should create a filetypedetection snippet in a separate file. It is usually in the form of anautocommand that sets the filetype when the file name matches a pattern.Example:
au BufNewFile,BufRead *.fooset filetype=foofoo
Write this single-line file as "ftdetect/foofoo.vim" in the first directorythat appears in
'runtimepath'. For Unix that would be"~/.config/nvim/ftdetect/foofoo.vim". The convention is to use the name ofthe filetype for the script name.
You can make more complicated checks if you like, for example to inspect thecontents of the file to recognize the language. Also see
new-filetype.
Summary of special things to use in a plugin:
s:nameVariables local to the script.
<SID>Script-ID, used for mappings and functions local tothe script.
hasmapto()Function to test if the user already defined a mappingfor functionality the script offers.
<Leader>Value of "mapleader", which the user defines as thekeys that plugin mappings start with.
:map<unique>Give a warning if a mapping already exists.
:noremap<script>Use only mappings local to the script, not globalmappings.
exists(":Cmd")Check if a user command already exists.
A filetype plugin is like a global plugin, except that it sets options anddefines mappings for the current buffer only. See
add-filetype-plugin forhow this type of plugin is used.
First read the section on global plugins above
41.11. All that is said therealso applies to filetype plugins. There are a few extras, which are explainedhere. The essential thing is that a filetype plugin should only have aneffect on the current buffer.
DISABLING
If you are writing a filetype plugin to be used by many people, they need achance to disable loading it. Put this at the top of the plugin:
" Only do this when not done yet for this bufferif exists("b:did_ftplugin") finishendiflet b:did_ftplugin = 1This also needs to be used to avoid that the same plugin is executed twice forthe same buffer (happens when using an ":edit" command without arguments).
Now users can disable loading the default plugin completely by making afiletype plugin with only this line:
let b:did_ftplugin = 1
This does require that the filetype plugin directory comes before $VIMRUNTIMEin
'runtimepath'!
If you do want to use the default plugin, but overrule one of the settings,you can write the different setting in a script:
setlocal textwidth=70
Now write this in the "after" directory, so that it gets sourced after thedistributed "vim.vim" ftplugin
after-directory. For Unix this would be"~/.config/nvim/after/ftplugin/vim.vim". Note that the default plugin willhave set "b:did_ftplugin", but it is ignored here.
OPTIONS
To make sure the filetype plugin only affects the current buffer use the
:setlocal
command to set options. And only set options which are local to a buffer (seethe help for the option to check that). When using
:setlocal for globaloptions or options local to a window, the value will change for many buffers,and that is not what a filetype plugin should do.
When an option has a value that is a list of flags or items, consider using"+=" and "-=" to keep the existing value. Be aware that the user may havechanged an option value already. First resetting to the default value andthen changing it is often a good idea. Example:
:setlocal formatoptions& formatoptions+=ro
MAPPINGS
To make sure mappings will only work in the current buffer use the
:map <buffer>
command. This needs to be combined with the two-step mapping explained above.An example of how to define functionality in a filetype plugin:
if !hasmapto('<Plug>JavaImport;') map <buffer> <unique> <LocalLeader>i <Plug>JavaImport;endifnoremap <buffer> <unique> <Plug>JavaImport; oimport ""<Left><Esc>hasmapto() is used to check if the user has already defined a map to
<Plug>JavaImport;. If not, then the filetype plugin defines the defaultmapping. This starts with
<LocalLeader>, which allows the user to selectthe key(s) they want filetype plugin mappings to start with. The default is abackslash."<unique>" is used to give an error message if the mapping already exists oroverlaps with an existing mapping.
:noremap is used to avoid that any other mappings that the user has definedinterferes. You might want to use ":noremap
<script>" to allow remappingmappings defined in this script that start with
<SID>.
The user must have a chance to disable the mappings in a filetype plugin,without disabling everything. Here is an example of how this is done for aplugin for the mail filetype:
" Add mappings, unless the user didn't want this.if !exists("no_plugin_maps") && !exists("no_mail_maps") " Quote text by inserting "> " if !hasmapto('<Plug>MailQuote;') vmap <buffer> <LocalLeader>q <Plug>MailQuote; nmap <buffer> <LocalLeader>q <Plug>MailQuote; endif vnoremap <buffer> <Plug>MailQuote; :s/^/> /<CR> nnoremap <buffer> <Plug>MailQuote; :.,$s/^/> /<CR>endifTwo global variables are used:
no_plugin_maps disables mappings for all filetype plugins
no_mail_maps disables mappings for the "mail" filetype
USER COMMANDS
To add a user command for a specific file type, so that it can only be used inone buffer, use the "-buffer" argument to
:command. Example:
:command -buffer Make make %:r.s
VARIABLES
A filetype plugin will be sourced for each buffer of the type it's for. Localscript variables
s:var will be shared between all invocations. Use localbuffer variables
b:var if you want a variable specifically for one buffer.
FUNCTIONS
When defining a function, this only needs to be done once. But the filetypeplugin will be sourced every time a file with this filetype will be opened.This construct makes sure the function is only defined once:
:if !exists("*s:Func"): function s:Func(arg): ...: endfunction:endifWhen the user does ":setfiletype xyz" the effect of the previous filetypeshould be undone. Set the b:undo_ftplugin variable to the commands that willundo the settings in your filetype plugin. Example:
let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<" \ .. "| unlet b:match_ignorecase b:match_words b:match_skip"
Using ":setlocal" with "<" after the option name resets the option to itsglobal value. That is mostly the best way to reset the option value.
For undoing the effect of an indent script, the b:undo_indent variable shouldbe set accordingly.
FILE NAME
The filetype must be included in the file name
ftplugin-name. Use one ofthese three forms:
.../ftplugin/stuff.vim.../ftplugin/stuff_foo.vim.../ftplugin/stuff/bar.vim
"stuff" is the filetype, "foo" and "bar" are arbitrary names.
Summary of special things to use in a filetype plugin:
<LocalLeader>Value of "maplocalleader", which the user defines asthe keys that filetype plugin mappings start with.
:map<buffer>Define a mapping local to the buffer.
:noremap<script>Only remap mappings defined in this script that startwith<SID>.
:setlocalSet an option for the current buffer only.
:command -bufferDefine a user command local to the buffer.
exists("*s:Func")Check if a function was already defined.
A compiler plugin sets options for use with a specific compiler. The user canload it with the
:compiler command. The main use is to set the
'errorformat' and
'makeprg' options.
Easiest is to have a look at examples. This command will edit all the defaultcompiler plugins:
:next $VIMRUNTIME/compiler/*.vim
Use
:next to go to the next plugin file.
There are two special items about these files. First is a mechanism to allowa user to overrule or add to the default file. The default files start with:
:if exists("current_compiler"): finish:endif:let current_compiler = "mine"When you write a compiler file and put it in your personal runtime directory(e.g., ~/.config/nvim/compiler for Unix), you set the "current_compiler"variable to make the default file skip the settings.
:CompilerSetThe second mechanism is to use ":set" for ":compiler!" and ":setlocal" for":compiler". Vim defines the ":CompilerSet" user command for this. This isan example:
CompilerSet errorformat&" use the default 'errorformat'CompilerSet makeprg=nmake
When you write a compiler plugin for the Vim distribution or for a system-wideruntime directory, use the mechanism mentioned above. When"current_compiler" was already set by a user plugin nothing will be done.
When you write a compiler plugin to overrule settings from a default plugin,don't check "current_compiler". This plugin is supposed to be loadedlast, thus it should be in a directory at the end of
'runtimepath'. For Unixthat could be ~/.config/nvim/after/compiler.
A plugin may grow and become quite long. The startup delay may becomenoticeable, while you hardly ever use the plugin. Then it's time for aquickload plugin.
The basic idea is that the plugin is loaded twice. The first time usercommands and mappings are defined that offer the functionality. The secondtime the functions that implement the functionality are defined.
It may sound surprising that quickload means loading a script twice. What wemean is that it loads quickly the first time, postponing the bulk of thescript to the second time, which only happens when you actually use it. Whenyou always use the functionality it actually gets slower!
Note that since Vim 7 there is an alternative: use the
autoloadfunctionality
41.15.
The following example shows how it's done:
" Vim global plugin for demonstrating quick loading" Last Change:2005 Feb 25" Maintainer:Bram Moolenaar <[email protected]>" License:This file is placed in the public domain.if !exists("s:did_load") command -nargs=* BNRead call BufNetRead(<f-args>) map <F19> :call BufNetWrite('something')<CR> let s:did_load = 1 exe 'au FuncUndefined BufNet* source ' .. expand('<script>') finishendiffunction BufNetRead(...) echo 'BufNetRead(' .. string(a:000) .. ')' " read functionality hereendfunctionfunction BufNetWrite(...) echo 'BufNetWrite(' .. string(a:000) .. ')' " write functionality hereendfunctionWhen the script is first loaded "s:did_load" is not set. The commands betweenthe "if" and "endif" will be executed. This ends in a
:finish command, thusthe rest of the script is not executed.
The second time the script is loaded "s:did_load" exists and the commandsafter the "endif" are executed. This defines the (possible long)BufNetRead() and BufNetWrite() functions.
If you drop this script in your plugin directory Vim will execute it onstartup. This is the sequence of events that happens:
1. The "BNRead" command is defined and the
<F19> key is mapped when the script is sourced at startup. A
FuncUndefined autocommand is defined. The ":finish" command causes the script to terminate early.
2. The user types the BNRead command or presses the<F19> key. The BufNetRead() or BufNetWrite() function will be called.
3. Vim can't find the function and triggers the
FuncUndefined autocommand event. Since the pattern "BufNet*" matches the invoked function, the command "source fname" will be executed. "fname" will be equal to the name of the script, no matter where it is located, because it comes from expanding "<script>" (see
expand()).
4. The script is sourced again, the "s:did_load" variable exists and the functions are defined.
Notice that the functions that are loaded afterwards match the pattern in the
FuncUndefined autocommand. You must make sure that no other plugin definesfunctions that match this pattern.
Some functionality will be required in several places. When this becomes morethan a few lines you will want to put it in one script and use it from manyscripts. We will call that one script a library script.
Manually loading a library script is possible, so long as you avoid loading itwhen it's already done. You can do this with the
exists() function.Example:
if !exists('*MyLibFunction') runtime library/mylibscript.vimendifcall MyLibFunction(arg)Here you need to know that MyLibFunction() is defined in a script"library/mylibscript.vim" in one of the directories in
'runtimepath'.
To make this a bit simpler Vim offers the autoload mechanism. Then theexample looks like this:
call mylib#myfunction(arg)
That's a lot simpler, isn't it? Vim will recognize the function name and whenit's not defined search for the script "autoload/mylib.vim" in
'runtimepath'.That script must define the "mylib#myfunction()" function.
You can put many other functions in the mylib.vim script, you are free toorganize your functions in library scripts. But you must use function nameswhere the part before the '#' matches the script name. Otherwise Vim wouldnot know what script to load.
If you get really enthusiastic and write lots of library scripts, you maywant to use subdirectories. Example:
call netlib#ftp#read('somefile')For Unix the library script used for this could be:
~/.config/nvim/autoload/netlib/ftp.vim
Where the function is defined like this:
function netlib#ftp#read(fname) " Read the file fname through ftpendfunction
Notice that the name the function is defined with is exactly the same as thename used for calling the function. And the part before the last '#'exactly matches the subdirectory and script name.
You can use the same mechanism for variables:
let weekdays = dutch#weekdays
This will load the script "autoload/dutch.vim", which should contain somethinglike:
let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag', \ 'donderdag', 'vrijdag', 'zaterdag']
Further reading:
autoload.
Vim users will look for scripts on the Vim website:
https://www.vim.org.If you made something that is useful for others, share it!
Vim scripts can be used on any system. There might not be a tar or gzipcommand. If you want to pack files together and/or compress them the "zip"utility is recommended.