Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
Number
Integer
Number A 32 or 64 bit signed number. expr-number
The number of bits is available in v:numbersize.
Examples: -123 0x10 0177 0o177 0b1011Float
Examples: 123.456 1.15e-6 -1.1e3{"blue": "#0000ff", "red": "#ff0000"} #{blue: "#0000ff", red: "#ff0000"}Blob Binary Large Object. Stores any sequence of bytes. See Blob for details. Example: 0zFF00ED015DAF 0z is an empty Blob.
octal
Conversion from a String to a Number is done by converting the first digits to
a number. Hexadecimal "0xf9", Octal "017" or "0o17", and Binary "0b10"
numbers are recognized. If the String doesn't start with digits, the result
is zero. Examples:
:echo "0100" + 0
TRUE
FALSE
Boolean
For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
You can also use v:false and v:true.
When TRUE is returned from a function it is the Number one, FALSE is the
number zero.:if "foo" :" NOT executed"foo" is converted to 0, which means FALSE. If the string starts with a non-zero number it means TRUE:
:if "8foo" :" executedTo test for a non-empty string, use empty():
:if !empty("foo")
falsy
truthy
An expression can be used as a condition, ignoring the type and only using
whether the value is "sort of true" or "sort of false". Falsy is:
the number zero
empty string, blob, list or dictionary
Other values are truthy. Examples:
0 falsy
1 truthy
-1 truthy
0.0 falsy
0.1 truthy
'' falsy
'x' truthy
[] falsy
[0] truthy
{} falsy
#{x: 1} truthy
0z falsy
0z00 truthynon-zero-arg
Function arguments often behave slightly different from TRUE: If the
argument is present and it evaluates to a non-zero Number, v:true or a
non-empty String, then the value is considered to be TRUE.
Note that " " and "0" are also non-empty strings, thus considered to be TRUE.
A List, Dictionary or Float is not a Number or String, thus evaluate to FALSE.E745
E728
E703
E729
E730
E731
E974
E975
E976
List, Dictionary, Funcref, and Blob types are not automatically
converted.E805
E806
E808
When mixing Number and Float the Number is converted to Float. Otherwise
there is no automatic conversion of Float. You can use str2float() for String
to Float, printf() for Float to String and float2nr() for Float to Number.no-type-checking
You will not get an error if you try to change the type of a variable.Funcref
E695
E718
E1192
A Funcref variable is obtained with the function() function, the funcref()
function or created with the lambda expression expr-lambda. It can be used
in an expression in the place of a function name, before the parenthesis
around the arguments, to invoke the function it refers to. Example::let Fn = function("MyFunc") :echo Fn()
E704
E705
E707
A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You
can use "g:" but the following name must still start with a capital. You
cannot have both a Funcref variable and a function with the same name.:function dict.init() dict : let self.val = 0 :endfunctionThe key of the Dictionary can start with a lower case letter. The actual function name is not used here. Also see numbered-function.
:call Fn() :call dict.init()The name of the referenced function can be obtained with string().
:let func = string(Fn)You can use call() to invoke a Funcref and use a list variable for the arguments:
:let r = call(Fn, mylist)
Partial
A Funcref optionally binds a Dictionary and/or arguments. This is also called
a Partial. This is created by passing the Dictionary and/or arguments to
function() or funcref(). When calling the function the Dictionary and/or
arguments will be passed to the function. Example:let Cb = function('Callback', ['foo'], myDict) call Cb('bar')This will invoke the function as if using:
call myDict.Callback('foo', 'bar')Note that binding a function to a Dictionary also happens when the function is a member of the Dictionary:
let myDict.myFunction = MyFunction call myDict.myFunction()Here MyFunction() will get myDict passed as "self". This happens when the "myFunction" member is accessed. When assigning "myFunction" to otherDict and calling it, it will be bound to otherDict:
let otherDict.myFunction = myDict.myFunction call otherDict.myFunction()Now "self" will be "otherDict". But when the dictionary was bound explicitly this won't happen:
let myDict.myFunction = function(MyFunction, myDict) let otherDict.myFunction = myDict.myFunction call otherDict.myFunction()Here "self" will be "myDict", because it was bound explicitly.
list
List
Lists
E686
A List is an ordered sequence of items. An item can be of any type. Items
can be accessed by their index number. Items can be added and removed at any
position in the sequence.E696
E697
A List is created with a comma-separated list of items in square brackets.
Examples::let mylist = [1, two, 3, "four"] :let emptylist = []An item can be any expression. Using a List for an item creates a List of Lists:
:let nestlist = [[11, 12], [21, 22], [31, 32]]An extra comma after the last item is ignored.
list-index
E684
An item in the List can be accessed by putting the index in square brackets
after the List. Indexes are zero-based, thus the first item has index zero.:let item = mylist[0] " get the first item: 1 :let item = mylist[2] " get the third item: 3When the resulting item is a list this can be repeated:
:let item = nestlist[0][1] " get the first list, second item: 12
:let last = mylist[-1] " get the last item: "four"To avoid an error for an invalid index use the get() function. When an item is not available it returns zero or the default value you specify:
:echo get(mylist, idx) :echo get(mylist, idx, "NONE")
list-concatenation
Two lists can be concatenated with the "+" operator::let longlist = mylist + [5, 6] :let mylist += [7, 8]To prepend or append an item, turn the item into a list by putting [] around it. To change a list in-place, refer to list-modification below.
sublist
A part of the List can be obtained by specifying the first and last index,
separated by a colon in square brackets::let shortlist = mylist[2:-1] " get List [3, "four"]Omitting the first index is similar to zero. Omitting the last index is similar to -1.
:let endlist = mylist[2:] " from item 2 to the end: [3, "four"] :let shortlist = mylist[2:2] " List with one item: [3] :let otherlist = mylist[:] " make a copy of the ListNotice that the last index is inclusive. If you prefer using an exclusive index use the slice() method.
:let mylist = [0, 1, 2, 3] :echo mylist[2:8] " result: [2, 3]NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for using a single letter variable before the ":". Insert a space when needed: mylist[s : e].
list-identity
When variable "aa" is a list and you assign it to another variable "bb", both
variables refer to the same list. Thus changing the list "aa" will also
change "bb"::let aa = [1, 2, 3] :let bb = aa :call add(aa, 4) :echo bb
:let aa = [[1, 'a'], 2, 3] :let bb = copy(aa) :call add(aa, 4) :let aa[0][1] = 'aaa' :echo aa
:echo bb
:let alist = [1, 2, 3] :let blist = [1, 2, 3] :echo alist is blist
:echo alist == blist
echo 4 == "4"
echo [4] == ["4"]
:let a = 5 :let b = "5" :echo a == b
:echo [a] == [b]
:let [var1, var2] = mylistWhen the number of variables does not match the number of items in the list this produces an error. To handle any extra items from the list append ";" and a variable name:
:let [var1, var2; rest] = mylistThis works like:
:let var1 = mylist[0] :let var2 = mylist[1] :let rest = mylist[2:]Except that there is no error if there are only two items. "rest" will be an empty list then.
list-modification
To change a specific item of a list use :let this way::let list[4] = "four" :let listlist[0][3] = itemTo change part of a list you can specify the first and last item to be modified. The value must at least have the number of items in the range:
:let list[3:5] = [3, 4, 5]Adding and removing items from a list is done with functions. Here are a few examples:
:call insert(list, 'a') " prepend item 'a' :call insert(list, 'a', 3) " insert item 'a' before list[3] :call add(list, "new") " append String item :call add(list, [1, 2]) " append a List as one new item :call extend(list, [1, 2]) " extend the list with two more items :let i = remove(list, 3) " remove item 3 :unlet list[3] " idem :let l = remove(list, 3, -1) " remove items 3 to last item :unlet list[3 : ] " idem :call filter(list, 'v:val !~ "x"') " remove items with an 'x'Changing the order of items in a list:
:call sort(list) " sort a list alphabetically :call reverse(list) " reverse the order of items :call uniq(sort(list)) " sort and remove duplicates
:for item in mylist : call Doit(item) :endforThis works like:
:let index = 0 :while index < len(mylist) : let item = mylist[index] : :call Doit(item) : let index = index + 1 :endwhileIf all you want to do is modify each item in the list then the map() function will be a simpler method than a for loop.
:for [lnum, col] in [[1, 3], [2, 8], [3, 0]] : call Doit(lnum, col) :endforThis works like a :let command is done for each list item. Again, the types must remain the same to avoid an error.
:for [i, j; rest] in listlist : call Doit(i, j) : if !empty(rest) : echo "remainder: " .. string(rest) : endif :endforFor a Blob one byte at a time is used.
for c in text echo 'This character is ' .. c endfor
E714
Functions that are useful with a List::let r = call(funcname, list) " call a function with an argument list :if empty(list) " check if list is empty :let l = len(list) " number of items in list :let big = max(list) " maximum value in list :let small = min(list) " minimum value in list :let xs = count(list, 'x') " count nr of times 'x' appears in list :let i = index(list, 'x') " index of first 'x' in list :let lines = getline(1, 10) " get ten text lines from buffer :call append('$', lines) " append text lines in buffer :let list = split("a b c") " create list from items in a string :let string = join(list, ', ') " create string from list items :let s = string(list) " String representation of list :call map(list, '">> " .. v:val') " prepend ">> " to each itemDon't forget that a combination of features can make things simple. For example, to add up all the numbers in a list:
:exe 'let sum = ' .. join(nrlist, '+')
Dict
dict
Dictionaries
Dictionary
A Dictionary is an associative array: Each entry has a key and a value. The
entry can be located with the key. The entries are stored without a specific
ordering.E720
E721
E722
E723
A Dictionary is created with a comma-separated list of entries in curly
braces. Each entry has a key and a value, separated by a colon. Each key can
only appear once. Examples::let mydict = {1: 'one', 2: 'two', 3: 'three'} :let emptydict = {}
E713
E716
E717
A key is always a String. You can use a Number, it will be converted to a
String automatically. Thus the String '4' and the number 4 will find the same
entry. Note that the String '04' and the Number 04 are different, since the
Number will be converted to the String '4', leading zeros are dropped. The
empty string can also be used as a key.
literal-Dict
#{}
To avoid having to put quotes around every key the #{} form can be used. This
does require the key to consist only of ASCII letters, digits, '-' and '_'.
Example::let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3}Note that 333 here is the string "333". Empty keys are not possible with #{}.
:let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}An extra comma after the last entry is ignored.
:let val = mydict["one"] :let mydict["four"] = 4You can add new entries to an existing Dictionary this way, unlike Lists.
:let val = mydict.one :let mydict.four = 4Since an entry can be any type, also a List and a Dictionary, the indexing and key lookup can be repeated:
:echo dict.key[idx].key
:for key in keys(mydict) : echo key .. ': ' .. mydict[key] :endforThe List of keys is unsorted. You may want to sort them first:
:for key in sort(keys(mydict))To loop over the values use the values() function:
:for v in values(mydict) : echo "value: " .. v :endforIf you want both the key and the value use the items() function. It returns a List in which each item is a List with two items, the key and the value:
:for [key, value] in items(mydict) : echo key .. ': ' .. value :endfor
dict-identity
Just like Lists you need to use copy() and deepcopy() to make a copy of a
Dictionary. Otherwise, assignment results in referring to the same
Dictionary::let onedict = {'a': 1, 'b': 2} :let adict = onedict :let adict['a'] = 11 :echo onedict['a'] 11Two Dictionaries compare equal if all the key-value pairs compare equal. For more info see list-identity.
dict-modification
To change an already existing entry of a Dictionary, or to add a new entry,
use :let this way::let dict[4] = "four" :let dict['one'] = itemRemoving an entry from a Dictionary is done with remove() or :unlet. Three ways to remove the entry with key "aaa" from dict:
:let i = remove(dict, 'aaa') :unlet dict.aaa :unlet dict['aaa']Merging a Dictionary with another is done with extend():
:call extend(adict, bdict)This extends adict with all entries from bdict. Duplicate keys cause entries in adict to be overwritten. An optional third argument can change this. Note that the order of entries in a Dictionary is irrelevant, thus don't expect ":echo adict" to show the items from bdict after the older entries in adict.
:call filter(dict, 'v:val =~ "x"')This removes all entries from "dict" with a value not matching 'x'. This can also be used to remove all entries:
call filter(dict, 0)
Dictionary-function
self
E725
E862
When a function is defined with the "dict" attribute it can be used in a
special way with a dictionary. Example::function Mylen() dict : return len(self.data) :endfunction :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")} :echo mydict.len()This is like a method in object oriented programming. The entry in the Dictionary is a Funcref. The local variable "self" refers to the dictionary the function was invoked from.
numbered-function
anonymous-function
To avoid the extra name for the function it can be defined and directly
assigned to a Dictionary in this way::let mydict = {'data': [0, 1, 2, 3]} :function mydict.len() : return len(self.data) :endfunction :echo mydict.len()The function will then get a number and the value of dict.len is a Funcref that references this function. The function can only be used through a Funcref. It will automatically be deleted when there is no Funcref remaining that refers to it.
:function g:42
E715
Functions that can be used with a Dictionary::if has_key(dict, 'foo') " TRUE if dict has entry with key "foo" :if empty(dict) " TRUE if dict is empty :let l = len(dict) " number of items in dict :let big = max(dict) " maximum value in dict :let small = min(dict) " minimum value in dict :let xs = count(dict, 'x') " count nr of times 'x' appears in dict :let s = string(dict) " String representation of dict :call map(dict, '">> " .. v:val') " prepend ">> " to each item
blob
Blob
Blobs
E978
A Blob is a binary object. It can be used to read an image from a file and
send it over a channel, for example.:let b = 0zFF00ED015DAFDots can be inserted between bytes (pair of hex characters) for readability, they don't change the value:
:let b = 0zFF00.ED01.5DAFA blob can be read from a file with readfile() passing the
{type}
argument
set to "B", for example::let b = readfile('image.png', 'B')
blob-index
E979
A byte in the Blob can be accessed by putting the index in square brackets
after the Blob. Indexes are zero-based, thus the first byte has index zero.:let myblob = 0z00112233 :let byte = myblob[0] " get the first byte: 0x00 :let byte = myblob[2] " get the third byte: 0x22A negative index is counted from the end. Index -1 refers to the last byte in the Blob, -2 to the last but one byte, etc.
:let last = myblob[-1] " get the last byte: 0x33To avoid an error for an invalid index use the get() function. When an item is not available it returns -1 or the default value you specify:
:echo get(myblob, idx) :echo get(myblob, idx, 999)
:for byte in 0z112233 : call Doit(byte) :endforThis calls Doit() with 0x11, 0x22 and 0x33.
:let longblob = myblob + 0z4455 :let myblob += 0z6677To change a blob in-place see blob-modification below.
:let myblob = 0z00112233 :let shortblob = myblob[1:2] " get 0z1122 :let shortblob = myblob[2:-1] " get 0z2233Omitting the first index is similar to zero. Omitting the last index is similar to -1.
:let endblob = myblob[2:] " from item 2 to the end: 0z2233 :let shortblob = myblob[2:2] " Blob with one byte: 0z22 :let otherblob = myblob[:] " make a copy of the BlobIf the first index is beyond the last byte of the Blob or the second index is before the first index, the result is an empty Blob. There is no error message.
:echo myblob[2:8] " result: 0z2233
blob-modification
To change a specific byte of a blob use :let this way::let blob[4] = 0x44When the index is just one beyond the end of the Blob, it is appended. Any higher index is an error.
let blob[1:3] = 0z445566The length of the replaced bytes must be exactly the same as the value provided.
E972
:let blob[3:5] = 0z334455You can also use the functions add(), remove() and insert().
if blob == 0z001122And for equal identity:
if blob is otherblob
blob-identity
E977
When variable "aa" is a Blob and you assign it to another variable "bb", both
variables refer to the same Blob. Then the "is" operator returns true.:let blob = 0z112233 :let blob2 = blob :echo blob == blob2
:echo blob is blob2
:let blob3 = blob[:] :echo blob == blob3
:echo blob is blob3
more-variables
If you need to know the type of a variable or expression, use the type()
function.'string'
string constant, ' is doubled
[expr1, ...] List
{expr1: expr1, ...}
Dictionary
#{key: expr1, ...} Dictionary
&option option value
(expr1) nested expression
variable internal variable
va{ria}ble internal variable with curly braces
$VAR environment variable
@r contents of register "r"
function(expr1, ...) function call
func{ti}on(expr1, ...) function call with curly braces
{args -> expr1}
lambda expression&nu || &list && &shell == "csh"All expressions within one level are parsed from left to right.
:echo lnum == 1 ? "top" : lnumSince the first expression is an "expr2", it cannot contain another ?:. The other two expressions can, thus allow for recursive use of ?:. Example:
:echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnumTo keep this readable, using line-continuation is suggested:
:echo lnum == 1 :\ ? "top" :\ : lnum == 1000 :\ ? "last" :\ : lnumYou should always put a space before the ':', otherwise it can be mistaken for use in a variable such as "a:1".
echo theList ?? 'list is empty' echo GetName() ?? 'unknown'These are similar, but not equal:
expr2 ?? expr1 expr2 ? expr2 : expr1In the second line "expr2" is evaluated twice.
expr-barbar
expr4 && expr4 .. logical AND expr-&&
&nu || &list && &shell == "csh"Note that "&&" takes precedence over "||", so this has the meaning of:
&nu || (&list && &shell == "csh")Once the result is known, the expression "short-circuits", that is, further arguments are not evaluated. This is like what happens in C. For example:
let a = 1 echo a || bThis is valid even if there is no variable called "b" because "a" is TRUE, so the result must be TRUE. Similarly below:
echo exists("b") && b == "yes"This is valid whether "b" has been defined or not. The second clause will only be evaluated if "b" has been defined.
{cmp}
expr5expr-==
expr-!=
expr->
expr->=
expr-<
expr-<=
expr-=~
expr-!~
expr-==#
expr-!=#
expr->#
expr->=#
expr-<#
expr-<=#
expr-=~#
expr-!~#
expr-==?
expr-!=?
expr->?
expr->=?
expr-<?
expr-<=?
expr-=~?
expr-!~?
expr-is
expr-isnot
expr-is#
expr-isnot#
expr-is?
expr-isnot?
E691
E692
A List can only be compared with a List and only "equal", "not equal",
"is" and "isnot" can be used. This compares the values of the list,
recursively. Ignoring case means case is ignored when comparing item values.E735
E736
A Dictionary can only be compared with a Dictionary and only "equal", "not
equal", "is" and "isnot" can be used. This compares the key/values of the
Dictionary recursively. Ignoring case means case is ignored when comparing
item values.E694
A Funcref can only be compared with a Funcref and only "equal", "not
equal", "is" and "isnot" can be used. Case is never ignored. Whether
arguments or a Dictionary are bound (with a partial) matters. The
Dictionaries must also be equal (or the same, in case of "is") and the
arguments must be equal (or the same).if get(Part1, 'name') == get(Part2, 'name') " Part1 and Part2 refer to the same functionUsing "is" or "isnot" with a List, Dictionary or Blob checks whether the expressions are referring to the same List, Dictionary or Blob instance. A copy of a List is different from the original List. When using "is" without a List, Dictionary or Blob, it is equivalent to using "equal", using "isnot" is equivalent to using "not equal". Except that a different type means the values are different:
echo 4 == '4' 1 echo 4 is '4' 0 echo 0 is [] 0"is#"/"isnot#" and "is?"/"isnot?" can be used to match and ignore case.
echo 0 == 'x' 1because 'x' converted to a Number is zero. However:
echo [0] == ['x'] 0Inside a List or Dictionary this conversion is not used.
expr-+
expr6 - expr6 Number subtraction expr--
expr6 . expr6 String concatenation expr-.
expr6 .. expr6 String concatenation expr-..
expr-star
expr7 / expr7 Number division expr-/
expr7 % expr7 Number modulo expr-%
1 . 90 + 90.0As:
(1 . 90) + 90.0That works, since the String "190" is automatically converted to the Number 190, which can be added to the Float 90.0. However:
1 . 90 * 90.0Should be read as:
1 . (90 * 90.0)Since '.' has lower precedence than "*". This does NOT work, since this attempts to concatenate a Float and a String.
E804
expr-!
expr-unary--
+ expr7 unary plus expr-unary-+
expr-[]
E111
subscript
In legacy Vim script:
If expr8 is a Number or String this results in a String that contains the
expr1'th single byte from expr8. expr8 is used as a String (a number is
automatically converted to a String), expr1 as a Number. This doesn't
recognize multibyte encodings, see byteidx()
for an alternative, or use
split()
to turn the string into a list of characters. Example, to get the
byte under the cursor::let c = getline(".")[col(".") - 1]Index zero gives the first byte. This is like it works in C. Careful: text column numbers start with one! Example, to get the byte under the cursor:
:let c = getline(".")[col(".") - 1]Index zero gives the first byte. Careful: text column numbers start with one!
:let item = mylist[-1] " get last itemGenerally, if a List index is equal to or higher than the length of the List, or more negative than the length of the List, this results in an error.
:let c = name[-1:] " last byte of a string :let c = name[0:-1] " the whole string :let c = name[-2:-2] " last but one byte of a string :let s = line(".")[4:] " from the fifth byte to the end :let s = s[:-3] " remove last two bytes
slice
If expr8 is a List this results in a new List with the items indicated by
the indexes expr1a and expr1b. This works like with a String, as explained
just above. Also see sublist below. Examples::let l = mylist[:3] " first four items :let l = mylist[4:4] " List with one item :let l = mylist[:] " shallow copy of a ListIf expr8 is a Blob this results in a new Blob with the bytes in the indexes expr1a and expr1b, inclusive. Examples:
:let b = 0zDEADBEEF :let bs = b[1:2] " 0zADBE :let bs = b[] " copy of 0zDEADBEEFUsing expr8[expr1] or expr8[expr1a : expr1b] on a Funcref results in an error.
mylist[n:] " uses variable n mylist[s:] " uses namespace s:, error!expr8.name entry in a Dictionary
expr-entry
:let dict = {"one": 1, 2: "two"} :echo dict.one " shows "1" :echo dict.2 " shows "two" :echo dict .2 " error because of space before the dotNote that the dot is also used for String concatenation. To avoid confusion always put spaces around the dot for String concatenation.
E260
E276
For methods that are also available as global functions this is the same as:name(expr8 [, args])There can also be methods specifically for the type of "expr8".
mylist->filter(filterexpr)->map(mapexpr)->sort()->join()
GetPercentage()->{x -> x * 100}()->printf('%d%%')
-1.234->string()Is equivalent to:
(-1.234)->string()And NOT:
-(1.234->string())
E274
"->name(" must not contain white space. There can be white space before the
"->" and after the "(", thus you can split the lines like this:mylist \ ->filter(filterexpr) \ ->map(mapexpr) \ ->sort() \ ->join()When using the lambda form there must be no white space between the } and the
expr9
expr-number
0x
hex-number
0o
octal-number
binary-number
Decimal, Hexadecimal (starting with 0x or 0X), Binary (starting with 0b or 0B)
and Octal (starting with 0, 0o or 0O).floating-point-format
Floating point numbers can be written in two forms:{N}
and {M}
are numbers. Both {N}
and {M}
must be present and can only
contain digits.
[-+] means there is an optional plus or minus sign.
{exp}
is the exponent, power of 10.
Only a decimal point is accepted, not a comma. No matter what the current
locale is.{M}
1e40 missing .{M}float-pi
float-e
A few useful values to copy&paste::let pi = 3.14159265359 :let e = 2.71828182846Or, if you don't want to write them in as floating-point literals, you can also use functions, like the following:
:let pi = acos(-1.0) :let e = exp(1.0)
floating-point-precision
The precision and range of floating points numbers depends on what "double"
means in the library Vim was compiled with. There is no way to change this at
runtime.:echo printf('%.15e', atan(1))
expr-quote
<BS>
\e escape <Esc>
\f formfeed 0x0C
\n newline <NL>
\r return <CR>
\t tab <Tab>
\\ backslash
\" double quote
\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W
. This is for use
in mappings, the 0x80 byte is escaped.
To use the double quote character it must be escaped: "<M-\">".
Don't use <Char-xxxx>
to get a UTF-8 character, use \uxxxx as
mentioned above.
\<*xxx> Like \<xxx> but prepends a modifier instead of including it in the
character. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is four
bytes: 3 for the CTRL modifier and then character "W".:let b = 0zFF00ED015DAF
expr-'
if a =~ "\\s*" if a =~ '\s*'
expr-$quote
$'string' interpolated literal string constant expr-$'
E1278
To include an opening brace '{' or closing brace '}' in the string content
double it. For double quoted strings using a backslash also works. A single
closing brace '}' will result in an error.let your_name = input("What's your name? ")
echo echo $"Hello, {your_name}!"
echo $"The square root of {{9}} is {sqrt(9)}"
{9}
is 3.0string-offset-encoding
A string consists of multiple characters. UTF-8 uses one byte for ASCII
characters, two bytes for other latin characters and more bytes for other
characters.echo "tabstop is " .. &tabstop if &expandtabAny option name can be used here. See options. When using the local value and there is no buffer-local or window-local value, the global value is used anyway.
expr-nesting
E110
-------
(expr1) nested expressiongetenv()
and setenv()
can also be used and work for
environment variables with non-alphanumeric names.
The function environ()
can be used to get a Dict with all environment
variables.expr-env-expand
Note that there is a difference between using $VAR directly and using
expand("$VAR"). Using it directly will only expand environment variables that
are known inside the current Vim session. Using expand() will first try using
the environment variables known inside the current Vim session. If that
fails, a shell will be used to expand the variable. This can be slow, but it
does expand all variables that the shell knows about. Example::echo $shell :echo expand("$shell")The first one probably doesn't echo anything, the second echoes the $shell variable (if your shell supports it).
{args -> expr1}
lambda expression E451
:let F = {arg1, arg2 -> arg1 - arg2} :echo F(5, 2)
:let F = {-> 'error function'} :echo F('ignored')
closure
Lambda expressions can access outer scope variables and arguments. This is
often called a closure. Example where "i" and "a:arg" are used in a lambda
while they already exist in the function scope. They remain valid even after
the function returns::function Foo(arg) : let i = 3 : return {x -> x + i - a:arg} :endfunction :let Bar = Foo(4) :echo Bar(6)
if has('lambda')Examples for using a lambda expression with sort(), map() and filter():
:echo map([1, 2, 3], {idx, val -> val + 1})
:echo sort([3,7,2,1,4], {a, b -> a - b})
:let timer = timer_start(500, \ {-> execute("echo 'Handler called'", "")}, \ {'repeat': 3})
function Function() let x = 0 let F = {-> x} endfunctionThe closure uses "x" from the function scope, and "F" in that same scope refers to the closure. This cycle results in the memory not being freed. Recommendation: don't do this.
<lambda>
42'. If you get an error
for a lambda expression, you can find what it is with the following command::function <lambda>42See also: numbered-function
variable-scope
There are several name spaces for variables. Which one is to be used is
specified by what is prepended::for k in keys(s:) : unlet s:[k] :endfor
buffer-variable
b:var
b:
A variable name that is preceded with "b:" is local to the current buffer.
Thus you can have several "b:foo" variables, one for each buffer.
This kind of variable is deleted when the buffer is wiped out or deleted with
:bdelete.b:changedtick
changetick
b:changedtick The total number of changes to the current buffer. It is
incremented for each change. An undo command is also a change
in this case. Resetting 'modified' when writing the buffer is
also counted.
This can be used to perform an action only when the buffer has
changed. Example::if my_changedtick != b:changedtick : let my_changedtick = b:changedtick : call My_Update() :endif
window-variable
w:var
w:
A variable name that is preceded with "w:" is local to the current window. It
is deleted when the window is closed.tabpage-variable
t:var
t:
A variable name that is preceded with "t:" is local to the current tab page,
It is deleted when the tab page is closed.global-variable
g:var
g:
Inside functions global variables are accessed with "g:". Omitting this will
access a variable local to a function. But "g:" can also be used in any other
place if you like.local-variable
l:var
l:
Inside functions local variables are accessed without prepending anything.
But you can also prepend "l:" if you like. However, without prepending "l:"
you may run into reserved variable names. For example "count". By itself it
refers to "v:count". Using "l:count" you can have a local variable with the
same name.script-variable
s:var
In a Vim script variables starting with "s:" can be used. They cannot be
accessed from outside of the scripts, thus are local to the script.let s:counter = 0 function MyCounter() let s:counter = s:counter + 1 echo s:counter endfunction command Tick call MyCounter()You can now invoke "Tick" from any script, and the "s:counter" variable in that script will not be changed, only the "s:counter" in the script where "Tick" was defined is used.
let s:counter = 0 command Tick let s:counter = s:counter + 1 | echo s:counterWhen calling a function and invoking a user-defined command, the context for script variables is set to the script where the function or command was defined.
let s:counter = 0 function StartCounting(incr) if a:incr function MyCounter() let s:counter = s:counter + 1 endfunction else function MyCounter() let s:counter = s:counter - 1 endfunction endif endfunctionThis defines the MyCounter() function either for counting up or counting down when calling StartCounting(). It doesn't matter from where StartCounting() is called, the s:counter variable will be accessible in MyCounter().
if !exists("s:counter") let s:counter = 1 echo "script executed for the first time" else let s:counter = s:counter + 1 echo "script executed " .. s:counter .. " times now" endifNote that this means that filetype plugins don't get a different set of script variables for each buffer. Use local buffer variables instead b:var.
E963
Some variables can be set by the user, but the type cannot be changed.v:argv
argv-variable
v:argv The command line arguments Vim was invoked with. This is a
list of strings. The first item is the Vim command.
See v:progpath for the command with full path.v:char
char-variable
v:char Argument for evaluating 'formatexpr' and used for the typed
character when using <expr>
in an abbreviation :map-<expr>.
It is also used by the InsertCharPre and InsertEnter events.v:charconvert_from
charconvert_from-variable
v:charconvert_from
The name of the character encoding of a file to be converted.
Only valid while evaluating the 'charconvert' option.v:charconvert_to
charconvert_to-variable
v:charconvert_to
The name of the character encoding of a file after conversion.
Only valid while evaluating the 'charconvert' option.v:cmdarg
cmdarg-variable
v:cmdarg
The extra arguments ("++p", "++enc=", "++ff=") given to a file
read/write command. This is set before an autocommand event
for a file read/write command is triggered. There is a
leading space to make it possible to append this variable
directly after the read/write command. Note: "+cmd" isn't
included here, because it will be executed anyway.v:collate
collate-variable
v:collate The current locale setting for collation order of the runtime
environment. This allows Vim scripts to be aware of the
current locale encoding. Technical: it's the value of
LC_COLLATE. When not using a locale the value is "C".
This variable can not be set directly, use the :language
command.
See multi-lang.v:cmdbang
cmdbang-variable
v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
was used the value is 1, otherwise it is 0. Note that this
can only be used in autocommands. For user commands <bang>
can be used.v:completed_item
completed_item-variable
v:completed_item
Dictionary containing the most recent complete-items after
CompleteDone. Empty if the completion failed, or after
leaving and re-entering insert mode.
Note: Plugins can modify the value to emulate the builtin
CompleteDone event behavior.v:count
count-variable
v:count The count given for the last Normal mode command. Can be used
to get the count before a mapping. Read-only. Example::map _x :<C-U>echo "the count is " .. v:count<CR>
<C-U>
is required to remove the line range that you
get when typing ':' after a count.
When there are two counts, as in "3d2w", they are multiplied,
just like what happens in the command, "d6w" for the example.
Also used for evaluating the 'formatexpr' option.v:count1
count1-variable
v:count1 Just like "v:count", but defaults to one when no count is
used.v:ctype
ctype-variable
v:ctype The current locale setting for characters of the runtime
environment. This allows Vim scripts to be aware of the
current locale encoding. Technical: it's the value of
LC_CTYPE. When not using a locale the value is "C".
This variable can not be set directly, use the :language
command.
See multi-lang.v:dying
dying-variable
v:dying Normally zero. When a deadly signal is caught it's set to
one. When multiple signals are caught the number increases.
Can be used in an autocommand to check if Vim didn't
terminate normally.
Example::au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
v:exiting
exiting-variable
v:exiting Exit code, or v:null before invoking the VimLeavePre
and VimLeave autocmds. See :q, :x and :cquit.
Example::au VimLeave * echo "Exit value is " .. v:exiting
v:echospace
echospace-variable
v:echospace Number of screen cells that can be used for an :echo
message
in the last screen line before causing the hit-enter-prompt.
Depends on 'showcmd', 'ruler' and 'columns'. You need to
check 'cmdheight' for whether there are full-width lines
available above the last line.v:errmsg
errmsg-variable
v:errmsg Last given error message.
Modifiable (can be set).
Example::let v:errmsg = "" :silent! next :if v:errmsg != "" : ... handle error
v:errors
errors-variable
assert-return
v:errors Errors found by assert functions, such as assert_true().
This is a list of strings.
The assert functions append an item when an assert fails.
The return value indicates this: a one is returned if an item
was added to v:errors, otherwise zero is returned.
To remove old results make it empty::let v:errors = []
v:event
event-variable
v:event Dictionary of event data for the current autocommand. Valid
only during the event lifetime; storing or passing v:event is
invalid! Copy it instead:au TextYankPost * let g:foo = deepcopy(v:event)
v:event.operator
is "y".
regcontents Text stored in the register as a
readfile()-style list of lines.
regname Requested register (e.g "x" for "xyy)
or the empty string for an unnamed
operation.
regtype Type of register as returned by
getregtype().
visual Selection is visual (as opposed to,
e.g., via motion).
completed_item Current selected complete item on
CompleteChanged, Is {}
when no complete
item selected.
height Height of popup menu on CompleteChanged
width width of popup menu on CompleteChanged
row Row count of popup menu on CompleteChanged,
relative to screen.
col Col count of popup menu on CompleteChanged,
relative to screen.
size Total number of completion items on
CompleteChanged.
scrollbar Is v:true if popup menu have scrollbar, or
v:false if not.
changed_window Is v:true if the event fired while
changing window (or tab) on DirChanged.
status Job status or exit code, -1 means "unknown". TermClosev:exception
exception-variable
v:exception The value of the exception most recently caught and not
finished. See also v:throwpoint and throw-variables.
Example::try : throw "oops" :catch /.*/ : echo "caught " .. v:exception :endtry
v:false
false-variable
v:false Special value used to put "false" in JSON and msgpack. See
json_encode(). This value is converted to "v:false" when used
as a String (e.g. in expr5 with string concatenation
operator) and to zero when used as a Number (e.g. in expr5
or expr7 when used with numeric operators). Read-only.v:fcs_reason
fcs_reason-variable
v:fcs_reason The reason why the FileChangedShell event was triggered.
Can be used in an autocommand to decide what to do and/or what
to set v:fcs_choice to. Possible values:
deleted file no longer exists
conflict file contents, mode or timestamp was
changed and buffer is modified
changed file contents has changed
mode mode of file changed
time only file timestamp changedv:fcs_choice
fcs_choice-variable
v:fcs_choice What should happen after a FileChangedShell event was
triggered. Can be used in an autocommand to tell Vim what to
do with the affected buffer:
reload Reload the buffer (does not work if
the file was deleted).
edit Reload the buffer and detect the
values for options such as
'fileformat', 'fileencoding', 'binary'
(does not work if the file was
deleted).
ask Ask the user what to do, as if there
was no autocommand. Except that when
only the timestamp changed nothing
will happen.
<empty>
Nothing, the autocommand should do
everything that needs to be done.
The default is empty. If another (invalid) value is used then
Vim behaves like it is empty, there is no warning message.v:fname
fname-variable
v:fname When evaluating 'includeexpr': the file name that was
detected. Empty otherwise.v:fname_in
fname_in-variable
v:fname_in The name of the input file. Valid while evaluating:
v:fname_out
fname_out-variable
v:fname_out The name of the output file. Only valid while
evaluating:
v:fname_new
fname_new-variable
v:fname_new The name of the new version of the file. Only valid while
evaluating 'diffexpr'.v:fname_diff
fname_diff-variable
v:fname_diff The name of the diff (patch) file. Only valid while
evaluating 'patchexpr'.v:folddashes
folddashes-variable
v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
fold.
Read-only in the sandbox. fold-foldtextv:foldlevel
foldlevel-variable
v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Read-only in the sandbox. fold-foldtextv:foldend
foldend-variable
v:foldend Used for 'foldtext': last line of closed fold.
Read-only in the sandbox. fold-foldtextv:foldstart
foldstart-variable
v:foldstart Used for 'foldtext': first line of closed fold.
Read-only in the sandbox. fold-foldtextv:hlsearch
hlsearch-variable
v:hlsearch Variable that indicates whether search highlighting is on.
Setting it makes sense only if 'hlsearch' is enabled. Setting
this variable to zero acts like the :nohlsearch command,
setting it to one acts likelet &hlsearch = &hlsearch
v:insertmode
insertmode-variable
v:insertmode Used for the InsertEnter and InsertChange autocommand
events. Values:
i Insert mode
r Replace mode
v Virtual Replace modev:key
key-variable
v:key Key of the current item of a Dictionary. Only valid while
evaluating the expression used with map() and filter().
Read-only.v:lang
lang-variable
v:lang The current locale setting for messages of the runtime
environment. This allows Vim scripts to be aware of the
current language. Technical: it's the value of LC_MESSAGES.
The value is system dependent.
This variable can not be set directly, use the :language
command.
It can be different from v:ctype when messages are desired
in a different language than what is used for character
encoding. See multi-lang.v:lc_time
lc_time-variable
v:lc_time The current locale setting for time messages of the runtime
environment. This allows Vim scripts to be aware of the
current language. Technical: it's the value of LC_TIME.
This variable can not be set directly, use the :language
command. See multi-lang.v:lnum
lnum-variable
v:lnum Line number for the 'foldexpr' fold-expr, 'formatexpr',
'indentexpr' and 'statuscolumn' expressions, tab page number
for 'guitablabel' and 'guitabtooltip'. Only valid while one of
these expressions is being evaluated. Read-only when in the
sandbox.v:lua
lua-variable
v:lua Prefix for calling Lua functions from expressions.
See v:lua-call for more information.v:maxcol
maxcol-variable
v:maxcol Maximum line length. Depending on where it is used it can be
screen columns, characters or bytes. The value currently is
2147483647 on all systems.v:mouse_win
mouse_win-variable
v:mouse_win Window number for a mouse click obtained with getchar().
First window has number 1, like with winnr(). The value is
zero when there was no mouse button click.v:mouse_winid
mouse_winid-variable
v:mouse_winid window-ID for a mouse click obtained with getchar().
The value is zero when there was no mouse button click.v:mouse_lnum
mouse_lnum-variable
v:mouse_lnum Line number for a mouse click obtained with getchar().
This is the text line number, not the screen line number. The
value is zero when there was no mouse button click.v:mouse_col
mouse_col-variable
v:mouse_col Column number for a mouse click obtained with getchar().
This is the screen column number, like with virtcol(). The
value is zero when there was no mouse button click.v:msgpack_types
msgpack_types-variable
v:msgpack_types Dictionary containing msgpack types used by msgpackparse()
and msgpackdump(). All types inside dictionary are fixed
(not editable) empty lists. To check whether some list is one
of msgpack types, use is operator.v:null
null-variable
v:null Special value used to put "null" in JSON and NIL in msgpack.
See json_encode(). This value is converted to "v:null" when
used as a String (e.g. in expr5 with string concatenation
operator) and to zero when used as a Number (e.g. in expr5
or expr7 when used with numeric operators). Read-only.
In some places v:null
can be used for a List, Dict, etc.
that is not set. That is slightly different than an empty
List, Dict, etc.v:numbermax
numbermax-variable
v:numbermax Maximum value of a number.v:numbermin
numbermin-variable
v:numbermin Minimum value of a number (negative).v:numbersize
numbersize-variable
v:numbersize Number of bits in a Number. This is normally 64, but on some
systems it may be 32.v:oldfiles
oldfiles-variable
v:oldfiles List of file names that is loaded from the shada file on
startup. These are the files that Vim remembers marks for.
The length of the List is limited by the ' argument of the
'shada' option (default is 100).
When the shada file is not used the List is empty.
Also see :oldfiles and c_#<.
The List can be modified, but this has no effect on what is
stored in the shada file later. If you use values other
than String this will cause trouble.v:option_new
v:option_new New value of the option. Valid while executing an OptionSet
autocommand.
v:option_old
v:option_old Old value of the option. Valid while executing an OptionSet
autocommand. Depending on the command used for setting and the
kind of option this is either the local old value or the
global old value.
v:option_oldlocal
v:option_oldlocal
Old local value of the option. Valid while executing an
OptionSet autocommand.
v:option_oldglobal
v:option_oldglobal
Old global value of the option. Valid while executing an
OptionSet autocommand.
v:option_type
v:option_type Scope of the set command. Valid while executing an
OptionSet autocommand. Can be either "global" or "local"
v:option_command
v:option_command
Command used to set the option. Valid while executing an
OptionSet autocommand.
v:operator
operator-variable
v:operator The last operator given in Normal mode. This is a single
character except for commands starting with <g>
or <z>
,
in which case it is two characters. Best used alongside
v:prevcount and v:register. Useful if you want to cancel
Operator-pending mode and then use the operator, e.g.::omap O <Esc>:call MyMotion(v:operator)<CR>
v:prevcount
prevcount-variable
v:prevcount The count given for the last but one Normal mode command.
This is the v:count value of the previous command. Useful if
you want to cancel Visual or Operator-pending mode and then
use the count, e.g.::vmap % <Esc>:call MyFilter(v:prevcount)<CR>
v:profiling
profiling-variable
v:profiling Normally zero. Set to one after using ":profile start".
See profiling.v:progname
progname-variable
v:progname The name by which Nvim was invoked (with path removed).
Read-only.v:progpath
progpath-variable
v:progpath Absolute path to the current running Nvim.
Read-only.v:register
register-variable
v:register The name of the register in effect for the current normal mode
command (regardless of whether that command actually used a
register). Or for the currently executing normal mode mapping
(use this in custom commands that take a register).
If none is supplied it is the default register '"', unless
'clipboard' contains "unnamed" or "unnamedplus", then it is
"*" or '+'.
Also see getreg() and setreg()v:relnum
relnum-variable
v:relnum Relative line number for the 'statuscolumn' expression.
Read-only.v:scrollstart
scrollstart-variable
v:scrollstart String describing the script or function that caused the
screen to scroll up. It's only set when it is empty, thus the
first reason is remembered. It is set to "Unknown" for a
typed command.
This can be used to find out why your script causes the
hit-enter prompt.v:servername
servername-variable
v:servername Primary listen-address of Nvim, the first item returned by
serverlist(). Usually this is the named pipe created by Nvim
at startup or given by --listen (or the deprecated
$NVIM_LISTEN_ADDRESS env var).$NVIM
$NVIM is set by terminal and jobstart(), and is thus
a hint that the current environment is a subprocess of Nvim.
Example:if $NVIM echo nvim_get_chan_info(v:parent) endif
v:searchforward
searchforward-variable
Search direction: 1 after a forward search, 0 after a
backward search. It is reset to forward when directly setting
the last search pattern, see quote/.
Note that the value is restored when returning from a
function. function-search-undo.
Read-write.v:shell_error
shell_error-variable
v:shell_error Result of the last shell command. When non-zero, the last
shell command had an error. When zero, there was no problem.
This only works when the shell returns the error code to Vim.
The value -1 is often used when the command could not be
executed. Read-only.
Example::!mv foo bar :if v:shell_error : echo 'could not rename "foo" to "bar"!' :endif
v:statusmsg
statusmsg-variable
v:statusmsg Last given status message.
Modifiable (can be set).v:stderr
stderr-variable
v:stderr channel-id corresponding to stderr. The value is always 2;
use this variable to make your code more descriptive.
Unlike stdin and stdout (see stdioopen()), stderr is always
open for writing. Example::call chansend(v:stderr, "error: toaster empty\n")
v:swapname
swapname-variable
v:swapname Name of the swapfile found.
Only valid during SwapExists event.
Read-only.v:swapchoice
swapchoice-variable
v:swapchoice SwapExists autocommands can set this to the selected choice
for handling an existing swapfile:
'o' Open read-only
'e' Edit anyway
'r' Recover
'd' Delete swapfile
'q' Quit
'a' Abort
The value should be a single-character string. An empty value
results in the user being asked, as would happen when there is
no SwapExists autocommand. The default is empty.v:swapcommand
swapcommand-variable
v:swapcommand Normal mode command to be executed after a file has been
opened. Can be used for a SwapExists autocommand to have
another Vim open the file and jump to the right place. For
example, when jumping to a tag the value is ":tag tagname\r".
For ":edit +cmd file" the value is ":cmd\r".v:t_TYPE
v:t_bool
t_bool-variable
v:t_bool Value of Boolean type. Read-only. See: type()
v:t_dict
t_dict-variable
v:t_dict Value of Dictionary type. Read-only. See: type()
v:t_float
t_float-variable
v:t_float Value of Float type. Read-only. See: type()
v:t_func
t_func-variable
v:t_func Value of Funcref type. Read-only. See: type()
v:t_list
t_list-variable
v:t_list Value of List type. Read-only. See: type()
v:t_number
t_number-variable
v:t_number Value of Number type. Read-only. See: type()
v:t_string
t_string-variable
v:t_string Value of String type. Read-only. See: type()
v:t_blob
t_blob-variable
v:t_blob Value of Blob type. Read-only. See: type()v:termresponse
termresponse-variable
v:termresponse The value of the most recent OSC or DCS escape sequence
received by Nvim from the terminal. This can be read in a
TermResponse event handler after querying the terminal using
another escape sequence.v:this_session
this_session-variable
v:this_session Full filename of the last loaded or saved session file.
Empty when no session file has been saved. See :mksession.
Modifiable (can be set).v:throwpoint
throwpoint-variable
v:throwpoint The point where the exception most recently caught and not
finished was thrown. Not set when commands are typed. See
also v:exception and throw-variables.
Example::try : throw "oops" :catch /.*/ : echo "Exception from" v:throwpoint :endtry
v:true
true-variable
v:true Special value used to put "true" in JSON and msgpack. See
json_encode(). This value is converted to "v:true" when used
as a String (e.g. in expr5 with string concatenation
operator) and to one when used as a Number (e.g. in expr5 or
expr7 when used with numeric operators). Read-only.v:val
val-variable
v:val Value of the current item of a List or Dictionary. Only
valid while evaluating the expression used with map() and
filter(). Read-only.v:version
version-variable
v:version Vim version number: major version times 100 plus minor
version. Vim 5.0 is 500, Vim 5.1 is 501.
Read-only.
Use has() to check the Nvim (not Vim) version::if has("nvim-0.2.1")
v:virtnum
virtnum-variable
v:virtnum Virtual line number for the 'statuscolumn' expression.
Negative when drawing the status column for virtual lines, zero
when drawing an actual buffer line, and positive when drawing
the wrapped part of a buffer line.
Read-only.v:vim_did_enter
vim_did_enter-variable
v:vim_did_enter 0 during startup, 1 just before VimEnter.
Read-only.v:warningmsg
warningmsg-variable
v:warningmsg Last given warning message.
Modifiable (can be set).v:windowid
windowid-variable
v:windowid Application-specific window "handle" which may be set by any
attached UI. Defaults to zero.
Note: For Nvim windows use winnr() or win_getid(), see
window-ID.my_{adjective}_variableWhen Vim encounters this, it evaluates the expression inside the braces, puts that in place of the expression, and re-interprets the whole as a variable name. So in the above example, if the variable "adjective" was set to "noisy", then the reference would be to "my_noisy_variable", whereas if "adjective" was set to "quiet", then it would be to "my_quiet_variable".
echo my_{&background}_messagewould output the contents of "my_dark_message" or "my_light_message" depending on the current value of 'background'.
echo my_{adverb}_{adjective}_message..or even nest them:
echo my_{ad{end_of_word}}_messagewhere "end_of_word" is either "verb" or "jective".
:let foo='a + b' :echo c{foo}d.. since the result of expansion is "ca + bd", which is not a variable name.
curly-braces-function-names
You can call and define functions by an evaluated name in a similar way.
Example::let func_end='whizz' :call my_func_{func_end}(parameter)This would call the function "my_func_whizz(parameter)".
:let i = 3 :let @{i} = '' " error :echo @{i} " error
{var-name}
= {expr1}
:let
E18
Set internal variable {var-name}
to the result of the
expression {expr1}
. The variable will get the type
from the {expr}
. If {var-name}
didn't exist yet, it
is created.{var-name}
[{idx}
] = {expr1}
E689
Set a list item to the result of the expression
{expr1}
. {var-name}
must refer to a list and {idx}
must be a valid index in that list. For nested list
the index can be repeated.
This cannot be used to add an item to a List.
This cannot be used to set a byte in a String. You
can do that like this::let var = var[0:2] .. 'X' .. var[4:]
{var-name}
is a Blob then {idx}
can be the
length of the blob, in which case one byte is
appended.E711
E719
:let {var-name}
[{idx1}
:{idx2}] = {expr1}
E708
E709
E710
Set a sequence of items in a List to the result of
the expression {expr1}
, which must be a list with the
correct number of items.
{idx1}
can be omitted, zero is used instead.
{idx2}
can be omitted, meaning the end of the list.
When the selected range of items is partly past the
end of the list, items will be added.:let+=
:let-=
:letstar=
:let/=
:let%=
:let.=
:let..=
E734
:let {var}
+= {expr1}
Like ":let {var}
= {var}
+ {expr1}
".
:let {var}
-= {expr1}
Like ":let {var}
= {var}
- {expr1}
".
:let {var} *= {expr1}
Like ":let {var}
= {var}
* {expr1}
".
:let {var}
/= {expr1}
Like ":let {var}
= {var}
/ {expr1}
".
:let {var}
%= {expr1}
Like ":let {var}
= {var}
% {expr1}
".
:let {var}
.= {expr1}
Like ":let {var}
= {var}
. {expr1}
".
:let {var}
..= {expr1}
Like ":let {var}
= {var}
.. {expr1}
".
These fail if {var}
was not set yet and when the type
of {var}
and {expr1}
don't fit the operator.{expr1}
:let-environment
:let-$
Set environment variable {env-name}
to the result of
the expression {expr1}
. The type is always String.
:let ${env-name} .= {expr1}
Append {expr1}
to the environment variable {env-name}
.
If the environment variable didn't exist yet this
works like "=".{expr1}
:let-register
:let-@
Write the result of the expression {expr1}
in register
{reg-name}
. {reg-name}
must be a single letter, and
must be the name of a writable register (see
registers). "@@" can be used for the unnamed
register, "@/" for the search pattern.
If the result of {expr1}
ends in a <CR>
or <NL>
, the
register will be linewise, otherwise it will be set to
charwise.
This can be used to clear the last search pattern::let @/ = ""
{expr1}
Append {expr1}
to register {reg-name}
. If the
register was empty it's like setting it to {expr1}
.{expr1}
:let-option
:let-&
Set option {option-name}
to the result of the
expression {expr1}
. A String or Number value is
always converted to the type of the option.
For an option local to a window or buffer the effect
is just like using the :set command: both the local
value and the global value are changed.
Example::let &path = &path .. ',/usr/local/include':let &{option-name} .=
{expr1}
For a string option: Append {expr1}
to the value.
Does not insert a comma like :set+=.{expr1}
:let &{option-name} -= {expr1}
For a number or boolean option: Add or subtract
{expr1}
.{expr1}
:let &l:{option-name} .= {expr1}
:let &l:{option-name} += {expr1}
:let &l:{option-name} -= {expr1}
Like above, but only set the local value of an option
(if there is one). Works like :setlocal.{expr1}
:let &g:{option-name} .= {expr1}
:let &g:{option-name} += {expr1}
:let &g:{option-name} -= {expr1}
Like above, but only set the global value of an option
(if there is one). Works like :setglobal.{name1}
, {name2}
, ...] = {expr1}
:let-unpack
E687
E688
{expr1}
must evaluate to a List. The first item in
the list is assigned to {name1}
, the second item to
{name2}
, etc.
The number of names must match the number of items in
the List.
Each name can be one of the items of the ":let"
command as mentioned above.
Example::let [s, item] = GetItem(s)
{expr1}
is evaluated first, then the
assignments are done in sequence. This matters if
{name2}
depends on {name1}
. Example::let x = [0, 1] :let i = 0 :let [i, x[i]] = [1, 2] :echo x
{name1}
, {name2}
, ...] .= {expr1}
:let [{name1}
, {name2}
, ...] += {expr1}
:let [{name1}
, {name2}
, ...] -= {expr1}
Like above, but append/add/subtract the value for each
List item.{name}
, ..., ; {lastname}
] = {expr1}
E452
Like :let-unpack above, but the List may have more
items than there are names. A list of the remaining
items is assigned to {lastname}
. If there are no
remaining items {lastname}
is set to an empty list.
Example::let [a, b; rest] = ["aval", "bval", 3, 4]
{name}
, ..., ; {lastname}
] .= {expr1}
:let [{name}
, ..., ; {lastname}
] += {expr1}
:let [{name}
, ..., ; {lastname}
] -= {expr1}
Like above, but append/add/subtract the value for each
List item.:let=<<
:let-heredoc
E990
E991
E172
E221
E1145
:let {var-name}
=<< [trim] [eval] {endmarker}
text...
text...
{endmarker}
Set internal variable {var-name}
to a List
containing the lines of text bounded by the string
{endmarker}
.{expr}
is evaluated and the result replaces the
expression, like with interpolated-string.
Example where $HOME is expanded:let lines =<< trim eval END some text See the file {$HOME}/.vimrc more text END
{endmarker}
must not contain white space.
{endmarker}
cannot start with a lower case character.
The last line should end only with the {endmarker}
string without any other character. Watch out for
white space after {endmarker}
!{endmarker}
, then indentation is stripped so you can
do:let text =<< trim END if ok echo 'done' endif END
["if ok", " echo 'done'", "endif"]
The marker must line up with "let" and the indentation
of the first line is removed from all the text lines.
Specifically: all the leading indentation exactly
matching the leading indentation of the first
non-empty text line is stripped from the input lines.
All leading indentation exactly matching the leading
indentation before let
is stripped from the line
containing {endmarker}
. Note that the difference
between space and tab matters here.{var-name}
didn't exist yet, it is created.
Cannot be followed by another command, but can be
followed by a comment.set cpo+=C let var =<< END \ leading backslash END set cpo-=C
let var1 =<< END Sample text 1 Sample text 2 Sample text 3 END let data =<< trim DATA 1 2 3 4 5 6 7 8 DATA let code =<< trim eval CODE let v = {10 + 20} let h = "{$HOME}" let s = "{Str1()} abc {Str2()}" let n = {MyFunc(3, 4)} CODE
E121
:let {var-name}
.. List the value of variable {var-name}
. Multiple
variable names may be given. Special names recognized
here: E738
g: global variables
b: local buffer variables
w: local window variables
t: local tab page variables
s: script-local variables
l: local function variables
v: Vim variables.<nothing>
String
# Number
* Funcref{name}
... :unlet
:unl
E108
E795
Remove the internal variable {name}
. Several variable
names can be given, they are all removed. The name
may also be a List or Dictionary item.
With [!] no error message is given for non-existing
variables.
One or more items from a List can be removed::unlet list[3] " remove fourth item :unlet list[3:] " remove fourth item to last
:unlet dict['two'] :unlet dict.two
:unlet-environment
:unlet-$
Remove environment variable {env-name}
.
Can mix {name}
and ${env-name} in one :unlet command.
No error message is given for a non-existing
variable, also without !.
If the system does not support deleting an environment
variable, it is made empty.:cons
:const
:cons[t] {var-name}
= {expr1}
:cons[t] [{name1}
, {name2}
, ...] = {expr1}
:cons[t] [{name}
, ..., ; {lastname}
] = {expr1}
Similar to :let, but additionally lock the variable
after setting the value. This is the same as locking
the variable with :lockvar just after :let, thus::const x = 1
:let x = 1 :lockvar! x
const ll = [1, 2, 3] let ll[1] = 5 " Error!
let lvar = ['a'] const lconst = [0, lvar] let lconst[0] = 2 " Error! let lconst[1][0] = 'b' " OK
E996
Note that environment variables, option values and
register values cannot be used here, since they cannot
be locked.{var-name}
If no argument is given or only {var-name}
is given,
the behavior is the same as :let.{name}
... :lockvar
:lockv
Lock the internal variable {name}
. Locking means that
it can no longer be changed (until it is unlocked).
A locked variable can be deleted::lockvar v :let v = 'asdf' " fails! :unlet v " works
E741
E940
If you try to change a locked variable you get an
error message: "E741: Value is locked: {name}
".
If you try to lock or unlock a built-in variable you
will get an error message "E940: Cannot lock or unlock
variable {name}
".{name}
but not its
value.
1 Lock the List or Dictionary itself,
cannot add or remove items, but can
still change their values.
2 Also lock the values, cannot change
the items. If an item is a List or
Dictionary, cannot add or remove
items, but can still change the
values.
3 Like 2 but for the List /
Dictionary in the List /
Dictionary, one level deeper.
The default [depth] is 2, thus when {name}
is a List
or Dictionary the values cannot be changed.let mylist = [1, 2, 3] lockvar 0 mylist let mylist[0] = 77 " OK call add(mylist, 4) " OK let mylist = [7, 8, 9] " Error!
E743
For unlimited depth use [!] and omit [depth].
However, there is a maximum depth of 100 to catch
loops.:let l = [0, 1, 2, 3] :let cl = l :lockvar l :let cl[1] = 99 " won't work!
{name}
... :unlockvar
:unlo
Unlock the internal variable {name}
. Does the
opposite of :lockvar.{name}
does not exist.{expr1}
:if
:end
:endif
:en
E171
E579
E580
:en[dif] Execute the commands until the next matching :else
or :endif
if {expr1}
evaluates to non-zero.
Although the short forms work, it is recommended to
always use :endif
to avoid confusion and to make
auto-indenting work properly.:if
and :endif
is ignored. These two
commands were just to allow for future expansions in a
backward compatible way. Nesting was allowed. Note
that any :else
or :elseif
was ignored, the else
part was not executed either.:if version >= 500 : version-5-specific-commands :endif
endif
. Sometimes an older Vim has a problem with a
new command. For example, :silent
is recognized as
a :substitute
command. In that case :execute
can
avoid problems::if version >= 600 : execute "silent 1,$delete" :endif
:append
and :insert
commands don't work
properly in between :if
and :endif
.:else
:el
E581
E583
:el[se] Execute the commands until the next matching :else
or :endif
if they previously were not being
executed.:elseif
:elsei
E582
E584
:elsei[f] {expr1}
Short for :else
:if
, with the addition that there
is no extra :endif
.{expr1}
:while
:endwhile
:wh
:endw
E170
E585
E588
E733
:endw[hile] Repeat the commands between :while
and :endwhile
,
as long as {expr1}
evaluates to non-zero.
When an error is detected from a command inside the
loop, execution continues after the endwhile
.
Example::let lnum = 1 :while lnum <= line("$") :call FixLine(lnum) :let lnum = lnum + 1 :endwhile
:append
and :insert
commands don't work
properly inside a :while
and :for
loop.{var}
in {object}
:for
E690
E732
:endfo[r] :endfo
:endfor
Repeat the commands between :for
and :endfor
for
each item in {object}
. {object}
can be a List,
a Blob or a String.{var}
is set to the value of each item.endfor
.
Changing {object}
inside the loop affects what items
are used. Make a copy if this is unwanted::for item in copy(mylist)
{object}
is a List and not making a copy, Vim
stores a reference to the next item in the List
before executing the commands with the current item.
Thus the current item can be removed without effect.
Removing any later item means it will not be found.
Thus the following example works (an inefficient way
to make a List empty):for item in mylist call remove(mylist, 0) endfor
{object}
is a Blob, Vim always makes a copy to
iterate over. Unlike with List, modifying the
Blob does not affect the iteration.{object}
is a String each item is a string with
one character, plus any combining characters.{var1}
, {var2}
, ...] in {listlist}
:endfo[r]
Like :for
above, but each item in {listlist}
must be
a list, of which each item is assigned to {var1}
,
{var2}
, etc. Example::for [lnum, col] in [[1, 3], [2, 5], [3, 8]] :echo getline(lnum)[col] :endfor
:continue
:con
E586
:con[tinue] When used inside a :while
or :for
loop, jumps back
to the start of the loop.:try
inside the loop but
before the matching :finally
(if present), the
commands following the :finally
up to the matching
:endtry
are executed first. This process applies to
all nested :try
s inside the loop. The outermost
:endtry
then jumps back to the start of the loop.:break
:brea
E587
:brea[k] When used inside a :while
or :for
loop, skips to
the command after the matching :endwhile
or
:endfor
.
If it is used after a :try
inside the loop but
before the matching :finally
(if present), the
commands following the :finally
up to the matching
:endtry
are executed first. This process applies to
all nested :try
s inside the loop. The outermost
:endtry
then jumps to the command after the loop.:try
:endt
:endtry
E600
E601
E602
:endt[ry] Change the error handling for the commands between
:try
and :endtry
including everything being
executed across :source
commands, function calls,
or autocommand invocations.:finally
command following, execution continues
after the :finally
. Otherwise, or when the
:endtry
is reached thereafter, the next
(dynamically) surrounding :try
is checked for
a corresponding :finally
etc. Then the script
processing is terminated. Whether a function
definition has an "abort" argument does not matter.
Example:try | call Unknown() | finally | echomsg "cleanup" | endtry echomsg "not reached"
:try
and :endtry
is converted to an exception. It
can be caught as if it were thrown by a :throw
command (see :catch
). In this case, the script
processing is not terminated.{command}
):{errmsg}",
other errors are converted to a value of the form
"Vim:{errmsg}". {command}
is the full command name,
and {errmsg}
is the message that is displayed if the
error exception is not caught, always beginning with
the error number.
Examples:try | sleep 100 | catch /^Vim:Interrupt$/ | endtry try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
:cat
:catch
E603
E604
E605
:cat[ch] /{pattern}/ The following commands until the next :catch
,
:finally
, or :endtry
that belongs to the same
:try
as the :catch
are executed when an exception
matching {pattern}
is being thrown and has not yet
been caught by a previous :catch
. Otherwise, these
commands are skipped.
When {pattern}
is omitted all errors are caught.
Examples::catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C) :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts :catch /^Vim(write):/ " catch all errors in :write :catch /^Vim\%((\a\+)\)\=:E123:/ " catch error E123 :catch /my-exception/ " catch user exception :catch /.*/ " catch everything :catch " same as /.*/
{pattern}
, so long as it does not have a special
meaning (e.g., '|' or '"') and doesn't occur inside
{pattern}
.
Information about the exception is available in
v:exception. Also see throw-variables.
NOTE: It is not reliable to ":catch" the TEXT of
an error message because it may vary in different
locales.:fina
:finally
E606
E607
:fina[lly] The following commands until the matching :endtry
are executed whenever the part between the matching
:try
and the :finally
is left: either by falling
through to the :finally
or by a :continue
,
:break
, :finish
, or :return
, or by an error or
interrupt or exception (see :throw
).:th
:throw
E608
:th[row] {expr1}
The {expr1}
is evaluated and thrown as an exception.
If the :throw
is used after a :try
but before the
first corresponding :catch
, commands are skipped
until the first :catch
matching {expr1}
is reached.
If there is no such :catch
or if the :throw
is
used after a :catch
but before the :finally
, the
commands following the :finally
(if present) up to
the matching :endtry
are executed. If the :throw
is after the :finally
, commands up to the :endtry
are skipped. At the :endtry
, this process applies
again for the next dynamically surrounding :try
(which may be found in a calling function or sourcing
script), until a matching :catch
has been found.
If the exception is not caught, the command processing
is terminated.
Example::try | throw "oops" | catch /^oo/ | echo "caught" | endtry
:ec
:echo
:ec[ho] {expr1}
.. Echoes each {expr1}
, with a space in between. The
first {expr1}
starts on a new line.
Also see :comment.
Use "\n" to start a new line. Use "\r" to move the
cursor to the first column.
Uses the highlighting set by the :echohl
command.
Cannot be followed by a comment.
Example::echo "the value of 'shell' is" &shell
:echo-redraw
A later redraw may make the message disappear again.
And since Vim mostly postpones redrawing until it's
finished with a sequence of commands this happens
quite often. To avoid that a command from before the
:echo
causes a redraw afterwards (redraws are often
postponed until you type something), force a redraw
with the :redraw
command. Example::new | redraw | echo "there is a new window"
:echo-self-refer
When printing nested containers echo prints second
occurrence of the self-referencing container using
"[...@level]" (self-referencing List) or
"{...@level}" (self-referencing Dict)::let l = [] :call add(l, l) :let l2 = [] :call add(l2, [l2]) :echo l l2
:echon
:echon {expr1}
.. Echoes each {expr1}
, without anything added. Also see
:comment.
Uses the highlighting set by the :echohl
command.
Cannot be followed by a comment.
Example::echon "the value of 'shell' is " &shell
:echo
, which is a
Vim command, and :!echo
, which is an external shell
command::!echo % --> filename
:!echo "%" --> filename or "filename"
:echo % --> nothing
:echo "%" --> %
:echo expand("%") --> filename
:echoh
:echohl
:echoh[l] {name}
Use the highlight group {name}
for the following
:echo
, :echon
and :echomsg
commands. Also used
for the input()
prompt. Example::echohl WarningMsg | echo "Don't panic!" | echohl None
:echom
:echomsg
:echom[sg] {expr1}
.. Echo the expression(s) as a true message, saving the
message in the message-history.
Spaces are placed between the arguments as with the
:echo
command. But unprintable characters are
displayed, not interpreted.
The parsing works slightly different from :echo
,
more like :execute
. All the expressions are first
evaluated and concatenated before echoing anything.
If expressions does not evaluate to a Number or
String, string() is used to turn it into a string.
Uses the highlighting set by the :echohl
command.
Example::echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
:echoe
:echoerr
:echoe[rr] {expr1}
.. Echo the expression(s) as an error message, saving the
message in the message-history. When used in a
script or function the line number will be added.
Spaces are placed between the arguments as with the
:echomsg
command. When used inside a try conditional,
the message is raised as an error exception instead
(see try-echoerr).
Example::echoerr "This script just failed!"
:echohl
.
And to get a beep::exe "normal \<Esc>"
:eval
:eval {expr}
Evaluate {expr}
and discard the result. Example::eval Getlist()->Filter()->append('$')
append()
call appends the List with text to the
buffer. This is similar to :call
but works with any
expression.:ev
or :eva
, but
these are hard to recognize and therefore not to be
used.:exe
:execute
:exe[cute] {expr1}
.. Executes the string that results from the evaluation
of {expr1}
as an Ex command.
Multiple arguments are concatenated, with a space in
between. To avoid the extra space use the ".."
operator to concatenate strings into one argument.
{expr1}
is used as the processed command, command line
editing keys are not recognized.
Cannot be followed by a comment.
Examples::execute "buffer" nextbuf :execute "normal" count .. "w"
:execute '!ls' | echo "theend"
:execute "normal ixxx\<Esc>"
<Esc>
character, see expr-string.:execute "e " .. fnameescape(filename) :execute "!ls " .. shellescape(filename, 1)
:if 0 : execute 'while i > 5' : echo "test" : endwhile :endif
:execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
:exe-comment
":execute", ":echo" and ":echon" cannot be followed by
a comment directly, because they see the '"' as the
start of a string. But, you can use '|' followed by a
comment. Example::echo "foo" | "this is a comment
:try : ... : ... TRY BLOCK : ... :catch /{pattern}/ : ... : ... CATCH CLAUSE : ... :catch /{pattern}/ : ... : ... CATCH CLAUSE : ... :finally : ... : ... FINALLY CLAUSE : ... :endtryThe try conditional allows to watch code for exceptions and to take the appropriate actions. Exceptions from the try block may be caught. Exceptions from the try block and also the catch clauses may cause cleanup actions. When no exception is thrown during execution of the try block, the control is transferred to the finally clause, if present. After its execution, the script continues with the line following the ":endtry". When an exception occurs during execution of the try block, the remaining lines in the try block are skipped. The exception is matched against the patterns specified as arguments to the ":catch" commands. The catch clause after the first matching ":catch" is taken, other catch clauses are not executed. The catch clause ends when the next ":catch", ":finally", or ":endtry" command is reached - whatever is first. Then, the finally clause (if present) is executed. When the ":endtry" is reached, the script execution continues in the following line as usual. When an exception that does not match any of the patterns specified by the ":catch" commands is thrown in the try block, the exception is not caught by that try conditional and none of the catch clauses is executed. Only the finally clause, if present, is taken. The exception pends during execution of the finally clause. It is resumed at the ":endtry", so that commands after the ":endtry" are not executed and the exception might be caught elsewhere, see try-nesting. When during execution of a catch clause another exception is thrown, the remaining lines in that catch clause are not executed. The new exception is not matched against the patterns in any of the ":catch" commands of the same try conditional and none of its catch clauses is taken. If there is, however, a finally clause, it is executed, and the exception pends during its execution. The commands following the ":endtry" are not executed. The new exception might, however, be caught elsewhere, see try-nesting. When during execution of the finally clause (if present) an exception is thrown, the remaining lines in the finally clause are skipped. If the finally clause has been taken because of an exception from the try block or one of the catch clauses, the original (pending) exception is discarded. The commands following the ":endtry" are not executed, and the exception from the finally clause is propagated and can be caught elsewhere, see try-nesting.
:throw 4711 :throw "string"
throw-expression
You can also specify an expression argument. The expression is then evaluated
first, and the result is thrown::throw 4705 + strlen("string") :throw strpart("strings", 0, 6)An exception might be thrown during evaluation of the argument of the ":throw" command. Unless it is caught there, the expression evaluation is abandoned. The ":throw" command then does not throw a new exception. Example:
:function! Foo(arg) : try : throw a:arg : catch /foo/ : endtry : return 1 :endfunction : :function! Bar() : echo "in Bar" : return 4710 :endfunction : :throw Foo("arrgh") + Bar()This throws "arrgh", and "in Bar" is not displayed since Bar() is not executed.
:throw Foo("foo") + Bar()however displays "in Bar" and throws 4711.
:if Foo("arrgh") : echo "then" :else : echo "else" :endifHere neither of "then" or "else" is displayed.
catch-order
Exceptions can be caught by a try conditional with one or more :catch
commands, see try-conditionals. The values to be caught by each ":catch"
command can be specified as a pattern argument. The subsequent catch clause
gets executed when a matching exception is caught.
Example::function! Foo(value) : try : throw a:value : catch /^\d\+$/ : echo "Number thrown" : catch /.*/ : echo "String thrown" : endtry :endfunction : :call Foo(0x1267) :call Foo('string')The first call to Foo() displays "Number thrown", the second "String thrown". An exception is matched against the ":catch" commands in the order they are specified. Only the first match counts. So you should place the more specific ":catch" first. The following order does not make sense:
: catch /.*/ : echo "String thrown" : catch /^\d\+$/ : echo "Number thrown"The first ":catch" here matches always, so that the second catch clause is never taken.
throw-variables
If you catch an exception by a general pattern, you may access the exact value
in the variable v:exception:: catch /^\d\+$/ : echo "Number thrown. Value is" v:exceptionYou may also be interested where an exception was thrown. This is stored in v:throwpoint. Note that "v:exception" and "v:throwpoint" are valid for the exception most recently caught as long it is not finished. Example:
:function! Caught() : if v:exception != "" : echo 'Caught "' .. v:exception .. '" in ' .. v:throwpoint : else : echo 'Nothing caught' : endif :endfunction : :function! Foo() : try : try : try : throw 4711 : finally : call Caught() : endtry : catch /.*/ : call Caught() : throw "oops" : endtry : catch /.*/ : call Caught() : finally : call Caught() : endtry :endfunction : :call Foo()This displays
Nothing caught Caught "4711" in function Foo, line 4 Caught "oops" in function Foo, line 10 Nothing caughtA practical example: The following command ":LineNumber" displays the line number in the script or function where it has been used:
:function! LineNumber() : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "") :endfunction :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
try-nested
An exception that is not caught by a try conditional can be caught by
a surrounding try conditional::try : try : throw "foo" : catch /foobar/ : echo "foobar" : finally : echo "inner finally" : endtry :catch /foo/ : echo "foo" :endtryThe inner try conditional does not catch the exception, just its finally clause is executed. The exception is then caught by the outer try conditional. The example displays "inner finally" and then "foo".
throw-from-catch
You can catch an exception and throw a new one to be caught elsewhere from the
catch clause::function! Foo() : throw "foo" :endfunction : :function! Bar() : try : call Foo() : catch /foo/ : echo "Caught foo, throw bar" : throw "bar" : endtry :endfunction : :try : call Bar() :catch /.*/ : echo "Caught" v:exception :endtryThis displays "Caught foo, throw bar" and then "Caught bar".
rethrow
There is no real rethrow in the Vim script language, but you may throw
"v:exception" instead::function! Bar() : try : call Foo() : catch /.*/ : echo "Rethrow" v:exception : throw v:exception : endtry :endfunction
try-echoerr
Note that this method cannot be used to "rethrow" Vim error or interrupt
exceptions, because it is not possible to fake Vim internal exceptions.
Trying so causes an error exception. You should throw your own exception
denoting the situation. If you want to cause a Vim error exception containing
the original error exception value, you can use the :echoerr command::try : try : asdf : catch /.*/ : echoerr v:exception : endtry :catch /.*/ : echo v:exception :endtryThis code displays
CTRL-C
, the settings remain in
an inconsistent state. The same may happen to you in the development phase of
a script when an error occurs or you explicitly throw an exception without
catching it. You can solve these problems by using a try conditional with
a finally clause for restoring the settings. Its execution is guaranteed on
normal control flow, on error, on an explicit ":throw", and on interrupt.
(Note that errors and interrupts from inside the try conditional are converted
to exceptions. When not caught, they terminate the script after the finally
clause has been executed.)
Example::try : let s:saved_ts = &ts : set ts=17 : : " Do the hard work here. : :finally : let &ts = s:saved_ts : unlet s:saved_ts :endtryThis method should be used locally whenever a function or part of a script changes global settings which need to be restored on failure or normal exit of that function or script part.
break-finally
Cleanup code works also when the try block or a catch clause is left by
a ":continue", ":break", ":return", or ":finish".
Example::let first = 1 :while 1 : try : if first : echo "first" : let first = 0 : continue : else : throw "second" : endif : catch /.*/ : echo v:exception : break : finally : echo "cleanup" : endtry : echo "still in while" :endwhile :echo "end"This displays "first", "cleanup", "second", "cleanup", and "end".
:function! Foo() : try : return 4711 : finally : echo "cleanup\n" : endtry : echo "Foo still active" :endfunction : :echo Foo() "returned by Foo"This displays "cleanup" and "4711 returned by Foo". You don't need to add an extra ":return" in the finally clause. (Above all, this would override the return value.)
except-from-finally
Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
a finally clause is possible, but not recommended since it abandons the
cleanup actions for the try conditional. But, of course, interrupt and error
exceptions might get raised from a finally clause.
Example where an error in the finally clause stops an interrupt from
working correctly::try : try : echo "Press CTRL-C for interrupt" : while 1 : endwhile : finally : unlet novar : endtry :catch /novar/ :endtry :echo "Script still running" :sleep 1If you need to put commands that could fail into a finally clause, you should think about catching or ignoring the errors in these commands, see catch-errors and ignore-errors.
Vim({cmdname}):{errmsg}or
Vim:{errmsg}
{cmdname}
is the name of the command that failed; the second form is used when
the command name is not known. {errmsg}
is the error message usually produced
when the error occurs outside try conditionals. It always begins with
a capital "E", followed by a two or three-digit error number, a colon, and
a space.:unlet novarnormally produces the error message
E108: No such variable: "novar"which is converted inside try conditionals to an exception
Vim(unlet):E108: No such variable: "novar"The command
:dwimnormally produces the error message
E492: Not an editor command: dwimwhich is converted inside try conditionals to an exception
Vim:E492: Not an editor command: dwimYou can catch all ":unlet" errors by a
:catch /^Vim(unlet):/or all errors for misspelled command names by a
:catch /^Vim:E492:/Some error messages may be produced by different commands:
:function nofuncand
:delfunction nofuncboth produce the error message
E128: Function name must start with a capital: nofuncwhich is converted inside try conditionals to an exception
Vim(function):E128: Function name must start with a capital: nofuncor
Vim(delfunction):E128: Function name must start with a capital: nofuncrespectively. You can catch the error by its number independently on the command that caused it if you use the following pattern:
:catch /^Vim(\a\+):E128:/Some commands like
:let x = novarproduce multiple error messages, here:
E121: Undefined variable: novar E15: Invalid expression: novarOnly the first is used for the exception value, since it is the most specific one (see except-several-errors). So you can catch it by
:catch /^Vim(\a\+):E121:/You can catch all errors related to the name "nofunc" by
:catch /\<nofunc\>/You can catch all Vim errors in the ":write" and ":read" commands by
:catch /^Vim(\(write\|read\)):E\d\+:/You can catch all Vim errors by the pattern
:catch /^Vim\((\a\+)\)\=:E\d\+:/
catch-text
NOTE: You should never catch the error message text itself::catch /No such variable/only works in the English locale, but not when the user has selected a different language by the :language command. It is however helpful to cite the message text in a comment:
:catch /^Vim(\a\+):E108:/ " No such variable
:try : write :catch :endtryBut you are strongly recommended NOT to use this simple form, since it could catch more than you want. With the ":write" command, some autocommands could be executed and cause errors not related to writing, for instance:
:au BufWritePre * unlet novarThere could even be such errors you are not responsible for as a script writer: a user of your script might have defined such autocommands. You would then hide the error from the user. It is much better to use
:try : write :catch /^Vim(write):/ :endtrywhich only catches real write errors. So catch only what you'd like to ignore intentionally.
:silent! nunmap kThis works also when a try conditional is active.
CTRL-C
) is converted to
the exception "Vim:Interrupt". You can catch it like every exception. The
script is not terminated, then.
Example::function! TASK1() : sleep 10 :endfunction :function! TASK2() : sleep 20 :endfunction :while 1 : let command = input("Type a command: ") : try : if command == "" : continue : elseif command == "END" : break : elseif command == "TASK1" : call TASK1() : elseif command == "TASK2" : call TASK2() : else : echo "\nIllegal command:" command : continue : endif : catch /^Vim:Interrupt$/ : echo "\nCommand interrupted" : " Caught the interrupt. Continue with next prompt. : endtry :endwhileYou can interrupt a task here by pressing
CTRL-C
; the script then asks for
a new command. If you press CTRL-C
at the prompt, the script is terminated.CTRL-C
would be pressed on a specific line in
your script, use the debug mode and execute the >quit or >interrupt
command on that line. See debug-scripts.:catch /.*/ :catch // :catchcatch everything, error exceptions, interrupt exceptions and exceptions explicitly thrown by the :throw command. This is useful at the top level of a script in order to catch unexpected things. Example:
:try : : " do the hard work here : :catch /MyException/ : : " handle known problem : :catch /^Vim:Interrupt$/ : echo "Script interrupted" :catch /.*/ : echo "Internal error (" .. v:exception .. ")" : echo " - occurred at " .. v:throwpoint :endtry :" end of scriptNote: Catching all might catch more things than you want. Thus, you are strongly encouraged to catch only for problems that you can really handle by specifying a pattern argument to the ":catch". Example: Catching all could make it nearly impossible to interrupt a script by pressing
CTRL-C
::while 1 : try : sleep 1 : catch : endtry :endwhile
:autocmd User x try :autocmd User x throw "Oops!" :autocmd User x catch :autocmd User x echo v:exception :autocmd User x endtry :autocmd User x throw "Arrgh!" :autocmd User x echo "Should not be displayed" : :try : doautocmd User x :catch : echo v:exception :endtryThis displays "Oops!" and "Arrgh!".
except-autocmd-Pre
For some commands, autocommands get executed before the main action of the
command takes place. If an exception is thrown and not caught in the sequence
of autocommands, the sequence and the command that caused its execution are
abandoned and the exception is propagated to the caller of the command.
Example::autocmd BufWritePre * throw "FAIL" :autocmd BufWritePre * echo "Should not be displayed" : :try : write :catch : echo "Caught:" v:exception "from" v:throwpoint :endtryHere, the ":write" command does not write the file currently being edited (as you can see by checking 'modified'), since the exception from the BufWritePre autocommand abandons the ":write". The exception is then caught and the script displays:
Caught: FAIL from BufWrite Auto commands for "*"
except-autocmd-Post
For some commands, autocommands get executed after the main action of the
command has taken place. If this main action fails and the command is inside
an active try conditional, the autocommands are skipped and an error exception
is thrown that can be caught by the caller of the command.
Example::autocmd BufWritePost * echo "File successfully written!" : :try : write /i/m/p/o/s/s/i/b/l/e :catch : echo v:exception :endtryThis just displays:
Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)If you really need to execute the autocommands even when the main action fails, trigger the event from the catch clause. Example:
:autocmd BufWritePre * set noreadonly :autocmd BufWritePost * set readonly : :try : write /i/m/p/o/s/s/i/b/l/e :catch : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e :endtry
:let x = "ok" :let v:errmsg = "" :autocmd BufWritePost * if v:errmsg != "" :autocmd BufWritePost * let x = "after fail" :autocmd BufWritePost * endif :try : silent! write /i/m/p/o/s/s/i/b/l/e :catch :endtry :echo xThis displays "after fail".
:autocmd BufWritePost * throw ":-(" :autocmd BufWritePost * echo "Should not be displayed" : :try : write :catch : echo v:exception :endtry
except-autocmd-Cmd
For some commands, the normal action can be replaced by a sequence of
autocommands. Exceptions from that sequence will be catchable by the caller
of the command.
Example: For the ":write" command, the caller cannot know whether the file
had actually been written when the exception occurred. You need to tell it in
some way.:if !exists("cnt") : let cnt = 0 : : autocmd BufWriteCmd * if &modified : autocmd BufWriteCmd * let cnt = cnt + 1 : autocmd BufWriteCmd * if cnt % 3 == 2 : autocmd BufWriteCmd * throw "BufWriteCmdError" : autocmd BufWriteCmd * endif : autocmd BufWriteCmd * write | set nomodified : autocmd BufWriteCmd * if cnt % 3 == 0 : autocmd BufWriteCmd * throw "BufWriteCmdError" : autocmd BufWriteCmd * endif : autocmd BufWriteCmd * echo "File successfully written!" : autocmd BufWriteCmd * endif :endif : :try : write :catch /^BufWriteCmdError$/ : if &modified : echo "Error on writing (file contents not changed)" : else : echo "Error after writing" : endif :catch /^Vim(write):/ : echo "Error on writing" :endtryWhen this script is sourced several times after making changes, it displays first
File successfully written!then
Error on writing (file contents not changed)then
Error after writingetc.
except-autocmd-ill
You cannot spread a try conditional over autocommands for different events.
The following code is ill-formed::autocmd BufWritePre * try : :autocmd BufWritePost * catch :autocmd BufWritePost * echo v:exception :autocmd BufWritePost * endtry : :write
:function! CheckRange(a, func) : if a:a < 0 : throw "EXCEPT:MATHERR:RANGE(" .. a:func .. ")" : endif :endfunction : :function! Add(a, b) : call CheckRange(a:a, "Add") : call CheckRange(a:b, "Add") : let c = a:a + a:b : if c < 0 : throw "EXCEPT:MATHERR:OVERFLOW" : endif : return c :endfunction : :function! Div(a, b) : call CheckRange(a:a, "Div") : call CheckRange(a:b, "Div") : if (a:b == 0) : throw "EXCEPT:MATHERR:ZERODIV" : endif : return a:a / a:b :endfunction : :function! Write(file) : try : execute "write" fnameescape(a:file) : catch /^Vim(write):/ : throw "EXCEPT:IO(" .. getcwd() .. ", " .. a:file .. "):WRITEERR" : endtry :endfunction : :try : : " something with arithmetic and I/O : :catch /^EXCEPT:MATHERR:RANGE/ : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "") : echo "Range error in" function : :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV : echo "Math error" : :catch /^EXCEPT:IO/ : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "") : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "") : if file !~ '^/' : let file = dir .. "/" .. file : endif : echo 'I/O error for "' .. file .. '"' : :catch /^EXCEPT/ : echo "Unspecified error" : :endtryThe exceptions raised by Vim itself (on error or when pressing
CTRL-C
) use
a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
exceptions with the "Vim" prefix; they are reserved for Vim.
Vim error exceptions are parameterized with the name of the command that
failed, if known. See catch-errors.except-compat
The exception handling concept requires that the command sequence causing the
exception is aborted immediately and control is transferred to finally clauses
and/or a catch clause.except-syntax-err
Syntax errors in the exception handling commands are never caught by any of
the ":catch" commands of the try conditional they belong to. Its finally
clauses, however, is executed.
Example::try : try : throw 4711 : catch /\(/ : echo "in catch with syntax error" : catch : echo "inner catch-all" : finally : echo "inner finally" : endtry :catch : echo 'outer catch-all caught "' .. v:exception .. '"' : finally : echo "outer finally" :endtryThis displays:
inner finally outer catch-all caught "Vim(catch):E54: Unmatched \(" outer finallyThe original exception is discarded and an error exception is raised, instead.
except-single-line
The ":try", ":catch", ":finally", and ":endtry" commands can be put on
a single line, but then syntax errors may make it difficult to recognize the
"catch" line, thus you better avoid this.
Example::try | unlet! foo # | catch | endtryraises an error exception for the trailing characters after the ":unlet!" argument, but does not see the ":catch" and ":endtry" commands, so that the error exception is discarded and the "E488: Trailing characters" message gets displayed.
except-several-errors
When several errors appear in a single command, the first error message is
usually the most specific one and therefore converted to the error exception.
Example:echo novarcauses
E121: Undefined variable: novar E15: Invalid expression: novarThe value of the error exception inside try conditionals is:
Vim(echo):E121: Undefined variable: novar
except-syntax-error
But when a syntax error is detected after a normal error in the same command,
the syntax error is used for the exception being thrown.
Example:unlet novar #causes
E108: No such variable: "novar" E488: Trailing charactersThe value of the error exception inside try conditionals is:
Vim(unlet):E488: Trailing charactersThis is done because the syntax error might change the execution path in a way not intended by the user. Example:
try try | unlet novar # | catch | echo v:exception | endtry catch /.*/ echo "outer catch:" v:exception endtryThis displays "outer catch: Vim(unlet):E488: Trailing characters", and then a "E600: Missing :endtry" error message is given, see except-single-line.
:" The function Nr2Bin() returns the binary string representation of a number. :func Nr2Bin(nr) : let n = a:nr : let r = "" : while n : let r = '01'[n % 2] .. r : let n = n / 2 : endwhile : return r :endfunc :" The function String2Bin() converts each character in a string to a :" binary string, separated with dashes. :func String2Bin(str) : let out = '' : for ix in range(strlen(a:str)) : let out = out .. '-' .. Nr2Bin(char2nr(a:str[ix])) : endfor : return out[1:] :endfuncExample of its use:
:echo Nr2Bin(32)result: "100000"
:echo String2Bin("32")result: "110011-110010"
:func SortBuffer() : let lines = getline(1, '$') : call sort(lines, function("Strcmp")) : call setline(1, lines) :endfunctionAs a one-liner:
:call setline(1, sort(getline(1, '$'), function("Strcmp")))
sscanf
There is no sscanf() function in Vim. If you need to extract parts from a
line, you can use matchstr() and substitute() to do it. This example shows
how to get the file name, line number and column number out of a line like
"foobar.txt, 123, 45".:" Set up the match bit :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)' :"get the part matching the whole expression :let l = matchstr(line, mx) :"get each item out of the match :let file = substitute(l, mx, '\1', '') :let lnum = substitute(l, mx, '\2', '') :let col = substitute(l, mx, '\3', '')The input is in the variable "line", the results in the variables "file", "lnum" and "col". (idea from Michael Geddes)
scriptnames-dictionary
The :scriptnames
command can be used to get a list of all script files that
have been sourced. There is also the getscriptinfo()
function, but the
information returned is not exactly the same. In case you need to manipulate
the output of scriptnames
this code can be used:" Get the output of ":scriptnames" in the scriptnames_output variable. let scriptnames_output = '' redir => scriptnames_output silent scriptnames redir END " Split the output into lines and parse each line. Add an entry to the " "scripts" dictionary. let scripts = {} for line in split(scriptnames_output, "\n") " Only do non-blank lines. if line =~ '\S' " Get the first number in the line. let nr = matchstr(line, '\d\+') " Get the file name, remove the script number " 123: ". let name = substitute(line, '.\+:\s*', '', '') " Add an item to the Dictionary let scripts[nr] = name endif endfor unlet scriptnames_output
CTRL-R
= in the command line.
The sandbox is also used for the :sandbox command.E48
These items are not allowed in the sandbox:
:san
:sandbox
:san[dbox] {cmd}
Execute {cmd}
in the sandbox. Useful to evaluate an
option that may have been set from a modeline, e.g.
'foldexpr'.sandbox-option
A few options contain an expression. When this expression is evaluated it may
have to be done in the sandbox to avoid a security risk. But the sandbox is
restrictive, thus this only happens when the option was set from an insecure
location. Insecure in this context are:
dist#vim
The functions make use of the autoloaded prefix "dist#vim".hl-NvimInvalid
Besides the "Nvim"-prefixed highlight groups described below, there are
"NvimInvalid"-prefixed highlight groups which have the same meaning but
indicate that the token contains an error or that an error occurred just
before it. They have mostly the same hierarchy, except that (by default) in
place of any non-Nvim-prefixed group NvimInvalid linking to Error
is used
and some other intermediate groups are present.hl-NvimInternalError
None, red/red Parser bughl-NvimAssignment
Operator Generic assignment
hl-NvimPlainAssignment
NvimAssignment =
in :let
hl-NvimAugmentedAssignment
NvimAssignment Generic, +=
/`-=`/`.=`
hl-NvimAssignmentWithAddition
NvimAugmentedAssignment +=
in :let+=
hl-NvimAssignmentWithSubtraction
NvimAugmentedAssignment -=
in :let-=
hl-NvimAssignmentWithConcatenation
NvimAugmentedAssignment .=
in :let.=hl-NvimOperator
Operator Generic operatorhl-NvimUnaryOperator
NvimOperator Generic unary op
hl-NvimUnaryPlus
NvimUnaryOperator expr-unary-+
hl-NvimUnaryMinus
NvimUnaryOperator expr-unary--
hl-NvimNot
NvimUnaryOperator expr-!hl-NvimBinaryOperator
NvimOperator Generic binary op
hl-NvimComparison
NvimBinaryOperator Any expr4 operator
hl-NvimComparisonModifier
NvimComparison #
/`?` near expr4 op
hl-NvimBinaryPlus
NvimBinaryOperator expr-+
hl-NvimBinaryMinus
NvimBinaryOperator expr--
hl-NvimConcat
NvimBinaryOperator expr-.
hl-NvimConcatOrSubscript
NvimConcat expr-. or expr-entry
hl-NvimOr
NvimBinaryOperator expr-barbar
hl-NvimAnd
NvimBinaryOperator expr-&&
hl-NvimMultiplication
NvimBinaryOperator expr-star
hl-NvimDivision
NvimBinaryOperator expr-/
hl-NvimMod
NvimBinaryOperator expr-%hl-NvimParenthesis
Delimiter Generic bracket
hl-NvimLambda
NvimParenthesis {
/`}` in lambda
hl-NvimNestingParenthesis
NvimParenthesis (
/`)` in expr-nesting
hl-NvimCallingParenthesis
NvimParenthesis (
/`)` in expr-functionhl-NvimSubscript
NvimParenthesis Generic subscript
hl-NvimSubscriptBracket
NvimSubscript [
/`]` in expr-[]
hl-NvimSubscriptColon
NvimSubscript :
in expr-[:]
hl-NvimCurly
NvimSubscript {
/`}` in
curly-braces-nameshl-NvimContainer
NvimParenthesis Generic container
hl-NvimDict
NvimContainer {
/`}` in dict literal
hl-NvimList
NvimContainer [
/`]` in list literalhl-NvimIdentifier
Identifier Generic identifier
hl-NvimIdentifierScope
NvimIdentifier Namespace: letter
before :
in
internal-variables
hl-NvimIdentifierScopeDelimiter
NvimIdentifier :
after namespace
letter
hl-NvimIdentifierName
NvimIdentifier Rest of the ident
hl-NvimIdentifierKey
NvimIdentifier Identifier after
expr-entryhl-NvimColon
Delimiter :
in dict literal
hl-NvimComma
Delimiter ,
in dict or list
literal or
expr-function
hl-NvimArrow
Delimiter ->
in lambdahl-NvimRegister
SpecialChar expr-register
hl-NvimNumber
Number Non-prefix digits
in integer
expr-number
hl-NvimNumberPrefix
Type 0
for octal-number
0x
for hex-number
0b
for binary-number
hl-NvimFloat
NvimNumber Floating-point
numberhl-NvimOptionSigil
Type &
in expr-option
hl-NvimOptionScope
NvimIdentifierScope Option scope if any
hl-NvimOptionScopeDelimiter
NvimIdentifierScopeDelimiter
:
after option scope
hl-NvimOptionName
NvimIdentifier Option namehl-NvimEnvironmentSigil
NvimOptionSigil $
in expr-env
hl-NvimEnvironmentName
NvimIdentifier Env variable namehl-NvimString
String Generic string
hl-NvimStringBody
NvimString Generic string
literal body
hl-NvimStringQuote
NvimString Generic string quote
hl-NvimStringSpecial
SpecialChar Generic string
non-literal bodyhl-NvimSingleQuote
NvimStringQuote '
in expr-'
hl-NvimSingleQuotedBody
NvimStringBody Literal part of
expr-' string body
hl-NvimSingleQuotedQuote
NvimStringSpecial ''
inside expr-'
string bodyhl-NvimDoubleQuote
NvimStringQuote "
in expr-quote
hl-NvimDoubleQuotedBody
NvimStringBody Literal part of
expr-quote body
hl-NvimDoubleQuotedEscape
NvimStringSpecial Valid expr-quote
escape sequence
hl-NvimDoubleQuotedUnknownEscape
NvimInvalidValue Unrecognized
expr-quote escape
sequence