Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
:let i = 1 :while i < 5 : echo "count is" i : let i += 1 :endwhile
: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 the condition is true. The condition used here is the expression "i < 5". This is true when the variable i is smaller than five. Note: If you happen to write a while loop that keeps on running, you can interrupt it by pressing
CTRL-C
(CTRL-Break
on MS-Windows).:for i in range(1, 4) : echo "count is" i :endforWe won't explain how :for and range() work until later. Follow the links if you are impatient.
:echo 0x7f 0o36
:echo 0x7f -0o36
:echo 0x7f - 0o36
41.2
Variables:letYou can use global variables everywhere. This also means that when the variable "count" is used in one script file, it might also be used in another file. This leads to confusion at least, and real problems at worst. To avoid this, you can use a variable local to a script file by prepending "s:". For example, one script contains this code:
:let s:count = 1 :while s:count < 5 : source other.vim : let s:count += 1 :endwhileSince "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. More about script-local variables here: script-variable.
:unlet s:countThis deletes the script-local variable "s:count" to free up the memory it uses. If you are not sure if the variable exists, and don't want an error message when it doesn't, append !:
:unlet! s:countWhen a script has been processed to the end, the local variables declared there will not be deleted. Functions defined in the script can use them. Example:
:if !exists(s:call_count)Then the value of s:call_count will be used as the name of the variable that exists() checks. That's not what you want. The exclamation mark ! negates a value. When the value was true, it becomes 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 for a number. When using a string that doesn't start with a digit the resulting number is zero. Thus look out for this:
:if "true"
:let name = "peter" :echo name
:let name = "\"peter\"" :echo name
:let name = '"peter"' :echo name
<Tab>
\n <NL>
, line break
\r <CR>
, <Enter>
\e <Esc>
\b <BS>
, backspace
\" "
\\ \, backslash
\<Esc> <Esc>
\<C-W> CTRL-W
41.3
Expressions:echo "The value of 'tabstop' is" &ts :echo "Your home directory is" $HOME :if @a > 5The &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_icThis makes sure the "The Start" pattern is used with the 'ignorecase' option off. Still, it keeps the value that the user had set. (Another way to do this would be to add "\C" to the pattern, see /\C.)
:echo 10 + 5 * 2
:echo (10 + 5) * 2
:echo "foo" .. "bar"
:let i = 4 :echo i > 5 ? "i is big" : "i is small"
41.4
Conditionals{condition}
{statements}
:endif{condition}
evaluates to true (non-zero) will the
{statements}
be executed. These must still be valid commands. If they
contain garbage, Vim won't be able to find the ":endif".
You can also use ":else". The generic form for this is:{condition}
{statements}
:else
{statements}
:endif{statements}
is only executed if the first one isn't.
Finally, there is ":elseif":{condition}
{statements}
:elseif {condition}
{statements}
:endif:if &term == "xterm" : " Do stuff for xterm :elseif &term == "vt100" : " Do stuff for a vt100 terminal :else : " Do something for other terminals :endif
:if v:version >= 700 : echo "congratulations" :else : echo "you are using an old version, upgrade!" :endifHere "v:version" is a variable defined by Vim, which has the value of the Vim version. 600 is for version 6.0. Version 6.1 has the value 601. This is very useful to write a script that works with multiple versions of Vim. v:version
:if 0 == "one" : echo "yes" :endifThis will echo "yes", because "one" doesn't look like a number, thus it is converted to the number zero.
:if str =~ " " : echo "str contains a space" :endif :if str !~ '\.$' : echo "str does not end in a full stop" :endifNotice 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 and patterns tend to contain many backslashes.
:while counter < 40 : call do_something() : if skip_flag : continue : endif : if finished_flag : break : endif : sleep 50m :endwhileThe ":sleep" command makes Vim take a nap. The "50m" specifies fifty milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
41.5
Executing an expression:execute "tag " .. tag_nameThe ".." 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 that will be executed is:
:tag get_cmdThe ":execute" command can only execute colon commands. The ":normal" command executes Normal mode commands. However, its argument is not an expression but the literal command characters. Example:
:normal gg=GThis 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_commandsThe variable "normal_commands" must contain the Normal mode commands. Make sure that the argument for ":normal" is a complete command. Otherwise Vim 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 special key "\<Esc>". This avoids having to enter a real
<Esc>
character in your
script.: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:call search("Date: ", "W")This calls the search() function, with arguments "Date: " and "W". The search() function uses its first argument as a search pattern and the second one as flags. The "W" flag means the search doesn't wrap around the end of the file.
:let line = getline(".") :let repl = substitute(line, '\a', "*", "g") :call setline(".", repl)The getline() function obtains a line from the current buffer. Its argument is a specification of the line number. In this case "." is used, which means the 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 the substitution. The second argument is the pattern, the third the replacement string. Finally, the last arguments are the flags. The setline() function sets the line, specified by the first argument, to a new string, the second argument. In this example the line under the cursor is replaced with the result of the substitute(). Thus the effect of the three statements is equal to:
:substitute/\a/*/gUsing the functions becomes interesting when you do more work before and after the substitute() call.
CTRL-]
on the function name to jump to detailed help on it.string-functions
nr2char() get a character by its number value
list2str() get a character string from a list of numbers
char2nr() get number value of a character
str2list() get list of numbers from a string
str2nr() convert a string to a Number
str2float() convert a string to a Float
printf() format a string according to % items
escape() escape characters in a string with a '\'
shellescape() escape a string for use with a shell command
fnameescape() escape a file name for use with a Vim command
tr() translate characters from one set to another
strtrans() translate a string to make it printable
keytrans() translate internal keycodes to a form that
can be used by :map
tolower() turn a string to lowercase
toupper() turn a string to uppercase
charclass() class of a character
match() position where a pattern matches in a string
matchbufline() all the matches of a pattern in a buffer
matchend() position where a pattern match ends in a string
matchfuzzy() fuzzy matches a string in a list of strings
matchfuzzypos() fuzzy matches a string in a list of strings
matchstr() match of a pattern in a string
matchstrlist() all the matches of a pattern in a List of
strings
matchstrpos() match and positions of a pattern in a string
matchlist() like matchstr() and also return submatches
stridx() first index of a short string in a long string
strridx() last index of a short string in a long string
strlen() length of a string in bytes
strcharlen() length of a string in characters
strchars() number of characters in a string
strutf16len() number of UTF-16 code units in a string
strwidth() size of string when displayed
strdisplaywidth() size of string when displayed, deals with tabs
setcellwidths() set character cell width overrides
getcellwidths() get character cell width overrides
reverse() reverse the order of characters in a string
substitute() substitute a pattern match with a string
submatch() get a specific match in ":s" and substitute()
strpart() get part of a string using byte index
strcharpart() get part of a string using char index
slice() take a slice of a string, using char index in
Vim9 script
strgetchar() get character from a string using char index
expand() expand special keywords
expandcmd() expand a command like done for :edit
iconv() convert text from one encoding to another
byteidx() byte index of a character in a string
byteidxcomp() like byteidx() but count composing characters
charidx() character index of a byte in a string
utf16idx() UTF-16 index of a byte in a string
repeat() repeat a string multiple times
eval() evaluate a string expression
execute() execute an Ex command and get the output
win_execute() like execute() but in a specified window
trim() trim characters from a string
gettext() lookup message translationlist-functions
get() get an item without error for wrong index
len() number of items in a List
empty() check if List is empty
insert() insert an item somewhere in a List
add() append an item to a List
extend() append a List to a List
extendnew() make a new List and append items
remove() remove one or more items from a List
copy() make a shallow copy of a List
deepcopy() make a full copy of a List
filter() remove selected items from a List
map() change each List item
mapnew() make a new List with changed items
foreach() apply function to List items
reduce() reduce a List to a value
slice() take a slice of a List
sort() sort a List
reverse() reverse the order of items in a List
uniq() remove copies of repeated adjacent items
split() split a String into a List
join() join List items into a String
range() return a List with a sequence of numbers
string() String representation of a List
call() call a function with List as arguments
index() index of a value in a List or Blob
indexof() index in a List or Blob where an expression
evaluates to true
max() maximum value in a List
min() minimum value in a List
count() count number of times a value appears in a List
repeat() repeat a List multiple times
flatten() flatten a List
flattennew() flatten a copy of a Listdict-functions
get() get an entry without an error for a wrong key
len() number of entries in a Dictionary
has_key() check whether a key appears in a Dictionary
empty() check if Dictionary is empty
remove() remove an entry from a Dictionary
extend() add entries from one Dictionary to another
extendnew() make a new Dictionary and append items
filter() remove selected entries from a Dictionary
map() change each Dictionary entry
mapnew() make a new Dictionary with changed items
foreach() apply function to Dictionary items
keys() get List of Dictionary keys
values() get List of Dictionary values
items() get List of Dictionary key-value pairs
copy() make a shallow copy of a Dictionary
deepcopy() make a full copy of a Dictionary
string() String representation of a Dictionary
max() maximum value in a Dictionary
min() minimum value in a Dictionary
count() count number of times a value appearsfloat-functions
float2nr() convert Float to Number
abs() absolute value (also works for Number)
round() round off
ceil() round up
floor() round down
trunc() remove value after decimal point
fmod() remainder of division
exp() exponential
log() natural logarithm (logarithm to base e)
log10() logarithm to base 10
pow() value of x to the exponent y
sqrt() square root
sin() sine
cos() cosine
tan() tangent
asin() arc sine
acos() arc cosine
atan() arc tangent
atan2() arc tangent
sinh() hyperbolic sine
cosh() hyperbolic cosine
tanh() hyperbolic tangent
isinf() check for infinity
isnan() check for not a numberblob-functions
blob2list() get a list of numbers from a blob
list2blob() get a blob from a list of numbers
reverse() reverse the order of numbers in a blobbitwise-function
and() bitwise AND
invert() bitwise invert
or() bitwise OR
xor() bitwise XOR
sha256() SHA-256 hash
rand() get a pseudo-random number
srand() initialize seed used by rand()var-functions
type() type of a variable
islocked() check if a variable is locked
funcref() get a Funcref for a function reference
function() get a Funcref for a function name
getbufvar() get a variable value from a specific buffer
setbufvar() set a variable in a specific buffer
getwinvar() get a variable from specific window
gettabvar() get a variable from specific tab page
gettabwinvar() get a variable from specific window & tab page
setwinvar() set a variable in a specific window
settabvar() set a variable in a specific tab page
settabwinvar() set a variable in a specific window & tab page
garbagecollect() possibly free memorycursor-functions
mark-functions
col() column number of the cursor or a mark
virtcol() screen column of the cursor or a mark
line() line number of the cursor or mark
wincol() window column number of the cursor
winline() window line number of the cursor
cursor() position the cursor at a line/column
screencol() get screen column of the cursor
screenrow() get screen row of the cursor
screenpos() screen row and col of a text character
virtcol2col() byte index of a text character on screen
getcurpos() get position of the cursor
getpos() get position of cursor, mark, etc.
setpos() set position of cursor, mark, etc.
getmarklist() list of global/local marks
byte2line() get line number at a specific byte count
line2byte() byte count at a specific line
diff_filler() get the number of filler lines above a line
screenattr() get attribute at a screen line/row
screenchar() get character code at a screen line/row
screenchars() get character codes at a screen line/row
screenstring() get string of characters at a screen line/row
charcol() character number of the cursor or a mark
getcharpos() get character position of cursor, mark, etc.
setcharpos() set character position of cursor, mark, etc.
getcursorcharpos() get character position of the cursor
setcursorcharpos() set character position of the cursortext-functions
getline() get a line or list of lines from the buffer
getregion() get a region of text from the buffer
getregionpos() get a list of positions for a region
setline() replace a line in the buffer
append() append line or list of lines in the buffer
indent() indent of a specific line
cindent() indent according to C indenting
lispindent() indent according to Lisp indenting
nextnonblank() find next non-blank line
prevnonblank() find previous non-blank line
search() find a match for a pattern
searchpos() find a match for a pattern
searchcount() get number of matches before/after the cursor
searchpair() find the other end of a start/skip/end
searchpairpos() find the other end of a start/skip/end
searchdecl() search for the declaration of a name
getcharsearch() return character search information
setcharsearch() set character search informationsystem-functions
file-functions
System functions and manipulation of files:
glob() expand wildcards
globpath() expand wildcards in a number of directories
glob2regpat() convert a glob pattern into a search pattern
findfile() find a file in a list of directories
finddir() find a directory in a list of directories
resolve() find out where a shortcut points to
fnamemodify() modify a file name
pathshorten() shorten directory names in a path
simplify() simplify a path without changing its meaning
executable() check if an executable program exists
exepath() full path of an executable program
filereadable() check if a file can be read
filewritable() check if a file can be written to
getfperm() get the permissions of a file
setfperm() set the permissions of a file
getftype() get the kind of a file
isabsolutepath() check if a path is absolute
isdirectory() check if a directory exists
getfsize() get the size of a file
getcwd() get the current working directory
haslocaldir() check if current window used :lcd or :tcd
tempname() get the name of a temporary file
mkdir() create a new directory
chdir() change current working directory
delete() delete a file
rename() rename a file
system() get the result of a shell command as a string
systemlist() get the result of a shell command as a list
environ() get all environment variables
getenv() get one environment variable
setenv() set an environment variable
hostname() name of the system
readfile() read a file into a List of lines
readblob() read a file into a Blob
readdir() get a List of file names in a directory
writefile() write a List of lines or Blob into a file
filecopy() copy a file {from}
to {to}
date-functions
time-functions
getftime() get last modification time of a file
localtime() get current time in seconds
strftime() convert time to a string
strptime() convert a date/time string to time
reltime() get the current or elapsed time accurately
reltimestr() convert reltime() result to a string
reltimefloat() convert reltime() result to a Floatbuffer-functions
window-functions
arg-functions
Buffers, windows and the argument list:
argc() number of entries in the argument list
argidx() current position in the argument list
arglistid() get id of the argument list
argv() get one entry from the argument list
bufadd() add a file to the list of buffers
bufexists() check if a buffer exists
buflisted() check if a buffer exists and is listed
bufload() ensure a buffer is loaded
bufloaded() check if a buffer exists and is loaded
bufname() get the name of a specific buffer
bufnr() get the buffer number of a specific buffer
tabpagebuflist() return List of buffers in a tab page
tabpagenr() get the number of a tab page
tabpagewinnr() like winnr() for a specified tab page
winnr() get the window number for the current window
bufwinid() get the window ID of a specific buffer
bufwinnr() get the window number of a specific buffer
winbufnr() get the buffer number of a specific window
win_findbuf() find windows containing a buffer
win_getid() get window ID of a window
win_gettype() get type of window
win_gotoid() go to window with ID
win_id2tabwin() get tab and window nr from window ID
win_id2win() get window nr from window ID
win_move_separator() move window vertical separator
win_move_statusline() move window status line
win_splitmove() move window to a split of another window
getbufinfo() get a list with buffer information
gettabinfo() get a list with tab page information
getwininfo() get a list with window information
getchangelist() get a list of change list entries
getjumplist() get a list of jump list entries
swapfilelist() list of existing swap files in 'directory'
swapinfo() information about a swap file
swapname() get the swap file path of a buffercommand-line-functions
getcmdcompltype() get the type of the current command line
completion
getcmdline() get the current command line
getcmdpos() get position of the cursor in the command line
getcmdscreenpos() get screen position of the cursor in the
command line
setcmdline() set the current command line
setcmdpos() set position of the cursor in the command line
getcmdtype() return the current command-line type
getcmdwintype() return the current command-line window type
getcompletion() list of command-line completion matches
fullcommand() get full command namequickfix-functions
getqflist() list of quickfix errors
setqflist() modify a quickfix list
getloclist() list of location list items
setloclist() modify a location listcompletion-functions
complete() set found matches
complete_add() add to found matches
complete_check() check if completion should be aborted
complete_info() get current completion information
pumvisible() check if the popup menu is displayed
pum_getpos() position and size of popup menu if visiblefolding-functions
foldclosed() check for a closed fold at a specific line
foldclosedend() like foldclosed() but return the last line
foldlevel() check for the fold level at a specific line
foldtext() generate the line displayed for a closed fold
foldtextresult() get the text displayed for a closed foldsyntax-functions
highlighting-functions
clearmatches() clear all matches defined by matchadd() and
the :match commands
getmatches() get all matches defined by matchadd() and
the :match commands
hlexists() check if a highlight group exists
hlID() get ID of a highlight group
synID() get syntax ID at a specific position
synIDattr() get a specific attribute of a syntax ID
synIDtrans() get translated syntax ID
synstack() get list of syntax IDs at a specific position
synconcealed() get info about (syntax) concealing
diff_hlID() get highlight ID for diff mode at a position
matchadd() define a pattern to highlight (a "match")
matchaddpos() define a list of positions to highlight
matcharg() get info about :match arguments
matchdelete() delete a match defined by matchadd() or a
:match command
setmatches() restore a list of matches saved by
getmatches()spell-functions
spellbadword() locate badly spelled word at or after cursor
spellsuggest() return suggested spelling corrections
soundfold() return the sound-a-like equivalent of a wordhistory-functions
histadd() add an item to a history
histdel() delete an item from a history
histget() get an item from a history
histnr() get highest index of a history listinteractive-functions
browse() put up a file requester
browsedir() put up a directory requester
confirm() let the user make a choice
getchar() get a character from the user
getcharmod() get modifiers for the last typed character
getmousepos() get last known mouse position
feedkeys() put characters in the typeahead queue
input() get a line from the user
inputlist() let the user pick an entry from a list
inputsecret() get a line from the user without showing it
inputdialog() get a line from the user in a dialog
inputsave() save and clear typeahead
inputrestore() restore typeaheadgui-functions
getfontname() get name of current font being used
getwinpos() position of the Vim window
getwinposx() X position of the Vim window
getwinposy() Y position of the Vim window
balloon_show() set the balloon content
balloon_split() split a message for a balloon
balloon_gettext() get the text in the balloonserver-functions
serverlist() return the list of server names
remote_startserver() run a server
remote_send() send command characters to a Vim server
remote_expr() evaluate an expression in a Vim server
server2client() send a reply to a client of a Vim server
remote_peek() check if there is a reply from a Vim server
remote_read() read a reply from a Vim server
foreground() move the Vim window to the foreground
remote_foreground() move the Vim server window to the foregroundwindow-size-functions
winheight() get height of a specific window
winwidth() get width of a specific window
win_screenpos() get screen position of a window
winlayout() get layout of windows in a tab page
winrestcmd() return command to restore window sizes
winsaveview() get view of current window
winrestview() restore saved view of current windowmapping-functions
digraph_get() get digraph
digraph_getlist() get all digraphs
digraph_set() register digraph
digraph_setlist() register multiple digraphs
hasmapto() check if a mapping exists
mapcheck() check if a matching mapping exists
maparg() get rhs of a mapping
maplist() get list of all mappings
mapset() restore a mapping
menu_info() get information about a menu item
wildmenumode() check if the wildmode is activesign-functions
sign_define() define or update a sign
sign_getdefined() get a list of defined signs
sign_getplaced() get a list of placed signs
sign_jump() jump to a sign
sign_place() place a sign
sign_placelist() place a list of signs
sign_undefine() undefine a sign
sign_unplace() unplace a sign
sign_unplacelist() unplace a list of signstest-functions
assert_equal() assert that two expressions values are equal
assert_equalfile() assert that two file contents are equal
assert_notequal() assert that two expressions values are not equal
assert_inrange() assert that an expression is inside a range
assert_match() assert that a pattern matches the value
assert_notmatch() assert that a pattern does not match the value
assert_false() assert that an expression is false
assert_true() assert that an expression is true
assert_exception() assert that a command throws an exception
assert_beeps() assert that a command beeps
assert_nobeep() assert that a command does not cause a beep
assert_fails() assert that a command fails
assert_report() report a test failuretimer-functions
timer_start() create a timer
timer_pause() pause or unpause a timer
timer_stop() stop a timer
timer_stopall() stop all timers
timer_info() get information about timers
wait() wait for a conditiontag-functions
taglist() get list of matching tags
tagfiles() get a list of tags files
gettagstack() get the tag stack of a window
settagstack() modify the tag stack of a windowpromptbuffer-functions
prompt_getprompt() get the effective prompt text for a buffer
prompt_setcallback() set prompt callback for a buffer
prompt_setinterrupt() set interrupt callback for a buffer
prompt_setprompt() set the prompt text for a bufferregister-functions
getreg() get contents of a register
getreginfo() get information about a register
getregtype() get type of a register
setreg() set contents and type of a register
reg_executing() return the name of the register being executed
reg_recording() return the name of the register being recordedctx-functions
ctxget() return context at given index from top
ctxpop() pop and restore top context
ctxpush() push given context
ctxset() set context at given index from top
ctxsize() return context stack sizevarious-functions
mode() get current editing mode
visualmode() last visual mode used
exists() check if a variable, function, etc. exists
has() check if a feature is supported in Vim
changenr() return number of most recent change
did_filetype() check if a FileType autocommand was used
eventhandler() check if invoked by an event handler
getpid() get process ID of Vim
getscriptinfo() get list of sourced vim scripts41.7
Defining a function:function {name}({var1}, {var2}, ...) : {body} :endfunction
: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:num2The 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 : endifThe variable "smaller" is a local variable. Variables used inside a function are local unless prefixed by something like "g:", "a:", or "s:".
: return smaller :endfunctionThe 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 :endfunctionFor 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 :endfunctionA user defined function is called in exactly the same way as a built-in function. Only the name is different. The Min function can be used like this:
: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 will now get an error message. When defining the function these errors are not detected.
:function! Min(num1, num2, num3)USING A RANGE
: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" :endfunctionYou 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 the range, 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.
:function Show(start, ...)The variable "a:1" contains the first optional argument, "a:2" the second, and so 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 the following ":echo" command. ":echohl None" stops it again. The ":echon" command works like ":echo", but doesn't output a line break.
:function
:function SetSyn
:delfunction ShowYou get an error when the function doesn't exist.
: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, [])
41.8
Lists and Dictionaries:let alist = ['aap', 'mies', 'noot']The List items are enclosed in square brackets and separated by commas. To create 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
:echo alist + ['foo', 'bar']
:let alist = ['one'] :call extend(alist, ['two', 'three']) :echo alist
:let alist = ['one'] :call add(alist, ['two', 'three']) :echo alist
:let alist = ['one', 'two', 'three'] :for n in alist : echo n :endfor
:for {varname} in {listexpression} : {commands} :endforTo loop a certain number of times you need a List of a specific length. The range() function creates one for you:
:for a in range(3) : echo a :endfor
:for a in range(8, 4, -2) : echo a :endfor
:for line in getline(1, 20) : if line =~ "Date: " : echo matchstr(line, 'Date: \zs.*') : endif :endforThis looks into lines 1 to 20 (inclusive) and echoes any date found in there.
:let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}Now you can lookup words by putting the key in square brackets:
:echo uk2nl['two']
{<key> : <value>, ...}An empty Dictionary is one without any keys:
{}The possibilities with Dictionaries are numerous. There are various functions for them as well. For example, you can obtain a list of the keys and loop over them:
:for key in keys(uk2nl) : echo key :endfor
:for key in sort(keys(uk2nl)) : echo key :endfor
:echo uk2nl['one']
:echo uk2nl.one
:let uk2nl.four = 'vier' :echo uk2nl
:function uk2nl.translate(line) dict : return join(map(split(a:line), 'get(self, v:val, "???")')) :endfunctionLet's first try it out:
:echo uk2nl.translate('three two five one')
split(a:line)The split() function takes a string, chops it into whitespace separated words and returns a list with these words. Thus in the example it returns:
:echo split('three two five one')
: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], "???") :endforThe get() function checks if a key is present in a Dictionary. If it is, then the value is retrieved. If it isn't, then the default value is returned, in the example it's '???'. This is a convenient way to handle situations where a key may not be present and you don't want an error message.
: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 lookup word translations. But we don't have a self.words. Thus you could call this an abstract class.
:let uk2nl = copy(transdict) :let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'} :echo uk2nl.translate('three one')
:let uk2de = copy(transdict) :let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'} :echo uk2de.translate('three one')
:if $LANG =~ "de" : let trans = uk2de :else : let trans = uk2nl :endif :echo trans.translate('one two three')
:let uk2uk = copy(transdict) :function! uk2uk.translate(line) : return a:line :endfunction :echo uk2uk.translate('three one wladiwostok')
:if $LANG =~ "de" : let trans = uk2de :elseif $LANG =~ "nl" : let trans = uk2nl :else : let trans = uk2uk :endif :echo trans.translate('one two three')
41.9
Exceptions:try : read ~/templates/pascal.tmpl :catch /E484:/ : echo "Sorry, the Pascal template file cannot be found." :endtryThe ":read" command will fail if the file does not exist. Instead of generating an error message, this code catches the error and gives the user a nice message.
:try : read ~/templates/pascal.tmpl :catch : echo "Sorry, the Pascal template file cannot be found." :endtryThis means all errors are caught. But then you will not see errors that are useful, such as "E21: Cannot make changes, 'modifiable' is off".
:let tmp = tempname() :try : exe ".,$write " .. tmp : exe "!filter " .. tmp : .,$delete : exe "$read " .. tmp :finally : call delete(tmp) :endtryThis 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 the filtering works, something goes wrong in between ":try" and ":finally" or the user cancels the filtering by pressing
CTRL-C
, the "call delete(tmp)" is
always executed. This makes sure you don't leave the temporary file behind.41.10
Various remarks:setlocal fileformat=unixWhen using "dos" fileformat, lines are separated with CR-NL, two characters. The CR character causes various problems, better avoid this.
map
. You have to watch out for that, it can cause hard to
understand mistakes. A generic solution is to never use trailing white space,
unless you really need it.:set tags=my\ nice\ fileThe same example written as:
:set tags=my nice filewill issue an error, because it is interpreted as:
:set tags=my :set nice :set file
:abbrev dev development " shorthand :map <F3> o#include " insert include :execute cmd " do it :!ls *.c " list C filesThe abbreviation "dev" will be expanded todevelopment " shorthand'. The mapping of
<F3>
will actually be the whole line after the 'o# ....' including
the '" insert include'. The "execute" command will give an error. The "!"
command will send everything after it to the shell, causing an error for an
unmatched '"' 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 itWith the '|' character the command is separated from the next one. And that next command is only a comment. For the last command you need to do two things: :execute and use '|':
:exe '!ls *.c' |" list C filesNotice that there is no white space before the '|' in the abbreviation and mapping. For these commands, any character until the end-of-line or '|' is included. As a consequence of this behavior, you don't always see that trailing whitespace is included:
:map <F4> o#includeTo spot these problems, you can set the 'list' option when editing vimrc files.
#!/usr/bin/env vim -S echo "this is a Vim script" quitThe "#" command by itself lists a line with the line number. Adding an exclamation mark changes it into doing nothing, so that you can add the shell command to execute the rest of the file. :#! -S
:map ,ab o#include :unmap ,abHere the unmap command will not work, because it tries to unmap ",ab ". This does not exist as a mapped sequence. An error will be issued, which is very hard to identify, because the ending whitespace character in ":unmap ,ab " is not visible.
:unmap ,ab " commentHere the comment part will be ignored. However, Vim will try to unmap ',ab ', which does not exist. Rewrite it as:
:unmap ,ab| " comment
map ,p ma"aYHmbgg"aP`bzt`aWhat this does:
ma"aYHmbgg"aP`bzt`a
" This is the XXX package if exists("XXX_loaded") delfun XXX_one delfun XXX_two endif function XXX_one(a) ... body of function ... endfun function XXX_two(b) ... body of function ... endfun let XXX_loaded = 1==============================================================================
41.11
Writing a plugin write-plugin
14 iabbrev teh the 15 iabbrev otehr other 16 iabbrev wnat want 17 iabbrev synchronisation 18 \ synchronization 19 let s:count = 4The actual list should be much longer, of course.
1 " Vim global plugin for correcting typing mistakes 2 " Last Change: 2000 Oct 15 3 " Maintainer: Bram Moolenaar <[email protected]>About copyright and licensing: Since plugins are very useful and it's hardly worth restricting their distribution, please consider making your plugin either public domain or use the Vim license. A short note about this near the 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-save
11 let s:save_cpo = &cpo 12 set cpo&vim .. 42 let &cpo = s:save_cpo 43 unlet s:save_cpoWe first store the old value of 'cpoptions' in the s:save_cpo variable. At the end of the plugin this value is restored.
6 if exists("g:loaded_typecorr") 7 finish 8 endif 9 let g:loaded_typecorr = 1This also avoids that when the script is loaded twice it would cause error messages for redefining functions and cause trouble for autocommands that are added twice.
<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.
let mapleader = "_"the mapping will define "_a". If the user didn't do this, the default value will be used, which is a backslash. Then a map for "\a" will be defined.
<unique>
is used, this will cause an error message if the mapping
already happened to exist. :map-<unique>21 if !hasmapto('<Plug>TypecorrAdd;') 22 map <unique> <Leader>a <Plug>TypecorrAdd; 23 endifThis checks if a mapping to "<Plug>TypecorrAdd;" already exists, and only defines the mapping from "<Leader>a" if it doesn't. The user then has a chance of putting this in their vimrc file:
map ,c <Plug>TypecorrAdd;Then the mapped key sequence will be ",c" instead of "_a" or "\a".
30 function s:Add(from, correct) 31 let to = input("type the correction for " .. a:from .. ": ") 32 exe ":iabbrev " .. a:from .. " " .. to .. 36 endfunctionNow we can call the function s:Add() from within this script. If another script also defines s:Add(), it will be local to that script and can only be 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 identifies
the current script. In our typing correction plugin we use it like this:24 noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add .. 28 noremap <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 and
thus define another mapping.<SID>
Add() here. That is because the
mapping is typed by the user, thus outside of the script. The <SID>
is
translated to the script ID, so that Vim knows in which script to look for
the Add() function.<SID>
Add() in mappings and
s:Add() in other places (the script itself, autocommands, user commands).26 noremenu <script> Plugin.Add\ Correction <SID>AddThe "Plugin" menu is recommended for adding menu items for plugins. In this case only one item is used. When adding more items, creating a submenu is recommended. For example, "Plugin.CVS" could be used for a plugin that offers CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
<SID>
and <Plug>
are used to avoid that mappings of typed keys interfere
with mappings that are only to be used from other mappings. Note the
difference between using <SID>
and <Plug>
:<Plug>
is visible outside of the script. It is used for mappings which the
user might want to map a key sequence to. <Plug>
is a special code
that a typed key will never produce.
To make it very unlikely that other plugins use the same sequence of
characters, use this structure: <Plug>
scriptname mapname
In 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 and
mapname 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 any
number. 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 if
you use the ":function" command to get a list of functions. The
translation of <SID>
in mappings is exactly the same, that's how you
can call a script-local function from a mapping.38 if !exists(":Correct") 39 command -nargs=1 Correct :call s:Add(<q-args>, 0) 40 endifThe user command is defined only if no command with the same name already exists. Otherwise we would get an error here. Overriding the existing user command with ":command!" is not a good idea, this would probably make the user wonder why the command they defined themself doesn't work. :command
19 let s:count = 4 .. 30 function s:Add(from, correct) .. 34 let s:count = s:count + 1 35 echo s:count .. " corrections now" 36 endfunctionFirst s:count is initialized to 4 in the script itself. When later the s:Add() function is called, it increments s:count. It doesn't matter from where the function was called, since it has been defined in the script, it will use the local variables from this script.
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 6 if exists("g:loaded_typecorr") 7 finish 8 endif 9 let g:loaded_typecorr = 1 10 11 let s:save_cpo = &cpo 12 set cpo&vim 13 14 iabbrev teh the 15 iabbrev otehr other 16 iabbrev wnat want 17 iabbrev synchronisation 18 \ synchronization 19 let s:count = 4 20 21 if !hasmapto('<Plug>TypecorrAdd;') 22 map <unique> <Leader>a <Plug>TypecorrAdd; 23 endif 24 noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add 25 26 noremenu <script> Plugin.Add\ Correction <SID>Add 27 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR> 29 30 function s:Add(from, correct) 31 let to = input("type the correction for " .. a:from .. ": ") 32 exe ":iabbrev " .. a:from .. " " .. to 33 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif 34 let s:count = s:count + 1 35 echo s:count .. " corrections now" 36 endfunction 37 38 if !exists(":Correct") 39 command -nargs=1 Correct :call s:Add(<q-args>, 0) 40 endif 41 42 let &cpo = s:save_cpo 43 unlet s:save_cpoLine 33 wasn't explained yet. It applies the new correction to the word under the cursor. The :normal command is used to use the new abbreviation. Note that mappings and abbreviations are expanded here, even though the function was called from a mapping defined with ":noremap".
:set fileformat=unix
1 *typecorr.txt* Plugin for correcting typing mistakes 2 3 If you make typing mistakes, this plugin will have them corrected 4 automatically. 5 6 There are currently only a few corrections. Add your own if you like. 7 8 Mappings: 9 <Leader>a or <Plug>TypecorrAdd; 10 Add a correction for the word under the cursor. 11 12 Commands: 13 :Correct {word} 14 Add a correction for {word}. 15 16 *typecorr-settings* 17 This plugin doesn't have any settings.The first line is actually the only one for which the format matters. It will be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of first line. After adding your help file do ":help" and check that the entries line up nicely.
au BufNewFile,BufRead *.foo set filetype=foofooWrite this single-line file as "ftdetect/foofoo.vim" in the first directory that appears in 'runtimepath'. For Unix that would be "~/.config/nvim/ftdetect/foofoo.vim". The convention is to use the name of the filetype for the script name.
<SID>
Script-ID, used for mappings and functions local to
the script.<Leader>
Value of "mapleader", which the user defines as the
keys that plugin mappings start with.<unique>
Give a warning if a mapping already exists.<script>
Use only mappings local to the script, not global
mappings.41.12
Writing a filetype plugin" Only do this when not done yet for this buffer if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1This also needs to be used to avoid that the same plugin is executed twice for the same buffer (happens when using an ":edit" command without arguments).
let b:did_ftplugin = 1This does require that the filetype plugin directory comes before $VIMRUNTIME in 'runtimepath'!
setlocal textwidth=70Now write this in the "after" directory, so that it gets sourced after the distributed "vim.vim" ftplugin after-directory. For Unix this would be "~/.config/nvim/after/ftplugin/vim.vim". Note that the default plugin will have set "b:did_ftplugin", but it is ignored here.
:setlocalcommand to set options. And only set options which are local to a buffer (see the help for the option to check that). When using :setlocal for global options or options local to a window, the value will change for many buffers, and that is not what a filetype plugin should do.
:setlocal formatoptions& formatoptions+=ro
: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; endif noremap <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 default
mapping. This starts with <LocalLeader>, which allows the user to select
the key(s) they want filetype plugin mappings to start with. The default is a
backslash.
"<unique>" is used to give an error message if the mapping already exists or
overlaps with an existing mapping.
:noremap is used to avoid that any other mappings that the user has defined
interferes. You might want to use ":noremap <script>
" to allow remapping
mappings defined in this script that start with <SID>
." 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
:command -buffer Make make %:r.s
:if !exists("*s:Func") : function s:Func(arg) : ... : endfunction :endif
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 its global value. That is mostly the best way to reset the option value.
<LocalLeader>
Value of "maplocalleader", which the user defines as
the keys that filetype plugin mappings start with.<buffer>
Define a mapping local to the buffer.<script>
Only remap mappings defined in this script that start
with <SID>
.41.13
Writing a compiler plugin:next $VIMRUNTIME/compiler/*.vimUse :next to go to the next plugin file.
: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.
:CompilerSet
The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
":compiler". Vim defines the ":CompilerSet" user command for this. This is
an example:CompilerSet errorformat& " use the default 'errorformat' CompilerSet makeprg=nmakeWhen you write a compiler plugin for the Vim distribution or for a system-wide runtime directory, use the mechanism mentioned above. When "current_compiler" was already set by a user plugin nothing will be done.
41.14
Writing a plugin that loads quickly" 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('<sfile>') finish endif function BufNetRead(...) echo 'BufNetRead(' .. string(a:000) .. ')' " read functionality here endfunction function BufNetWrite(...) echo 'BufNetWrite(' .. string(a:000) .. ')' " write functionality here endfunctionWhen the script is first loaded "s:did_load" is not set. The commands between the "if" and "endif" will be executed. This ends in a :finish command, thus the rest of the script is not executed.
<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.<F19>
key. The
BufNetRead() or BufNetWrite() function will be called.41.15
Writing library scriptsif !exists('*MyLibFunction') runtime library/mylibscript.vim endif call MyLibFunction(arg)Here you need to know that MyLibFunction() is defined in a script "library/mylibscript.vim" in one of the directories in 'runtimepath'.
call mylib#myfunction(arg)That's a lot simpler, isn't it? Vim will recognize the function name and when it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'. That script must define the "mylib#myfunction()" function.
call netlib#ftp#read('somefile')For Unix the library script used for this could be:
function netlib#ftp#read(fname) " Read the file fname through ftp endfunctionNotice that the name the function is defined with is exactly the same as the name used for calling the function. And the part before the last '#' exactly matches the subdirectory and script name.
let weekdays = dutch#weekdaysThis will load the script "autoload/dutch.vim", which should contain something like:
let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag', \ 'donderdag', 'vrijdag', 'zaterdag']Further reading: autoload.
41.16
Distributing Vim scripts