Nvim:help
pages,generated fromsource using thetree-sitter-vimdoc parser.
{"blue": "#0000ff", "red": "#ff0000"}#{blue: "#0000ff", red: "#ff0000"}BlobBinary Large Object. Stores any sequence of bytes. SeeBlobfor details.Example: 0zFF00ED015DAF0z is an empty Blob.
:echo "0100" + 0
:if "foo":" NOT executed"foo" is converted to 0, which means FALSE. If the string starts with anon-zero number it means TRUE:
:if "8foo":" executedTo test for a non-empty string, use empty():
:if !empty("foo")
:let Fn = function("MyFunc"):echo Fn()
:function dict.init() dict: let self.val = 0:endfunctionThe key of the Dictionary can start with a lower case letter. The actualfunction name is not used here. Also seenumbered-function.
:call Fn():call dict.init()The name of the referenced function can be obtained withstring().
:let func = string(Fn)You can usecall() to invoke a Funcref and use a list variable for thearguments:
:let r = call(Fn, mylist)
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 isa member of the Dictionary:
let myDict.myFunction = MyFunctioncall myDict.myFunction()Here MyFunction() will get myDict passed as "self". This happens when the"myFunction" member is accessed. When assigning "myFunction" to otherDictand calling it, it will be bound to otherDict:
let otherDict.myFunction = myDict.myFunctioncall otherDict.myFunction()Now "self" will be "otherDict". But when the dictionary was bound explicitlythis won't happen:
let myDict.myFunction = function(MyFunction, myDict)let otherDict.myFunction = myDict.myFunctioncall otherDict.myFunction()Here "self" will be "myDict", because it was bound explicitly.
:let mylist = [1, two, 3, "four"]:let emptylist = []An item can be any expression. Using a List for an item creates aList of Lists:
:let nestlist = [[11, 12], [21, 22], [31, 32]]An extra comma after the last item is ignored.
: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 theget() function. When an itemis not available it returns zero or the default value you specify:
:echo get(mylist, idx):echo get(mylist, idx, "NONE")
:let longlist = mylist + [5, 6]:let longlist = [5, 6] + mylistTo prepend or append an item, turn it into a list by putting [] around it.
:let mylist += [7, 8]:call extend(mylist, [7, 8])
:let shortlist = mylist[2:-1]" get List [3, "four"]Omitting the first index is similar to zero. Omitting the last index issimilar 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 exclusiveindex use theslice() 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 forusing a single letter variable before the ":". Insert a space when needed:mylist[s : e].
: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 listthis 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 anempty list then.
:let list[4] = "four":let listlist[0][3] = itemTo change part of a list you can specify the first and last item to bemodified. The value must at least have the number of items in the range:
:let list[3:5] = [3, 4, 5]To add items to a List in-place, you can use:let+= (list-concatenation):
:let listA = [1, 2]:let listA += [3, 4]
:let listA = [1, 2]:let listB = listA:let listB += [3, 4]:echo listA[1, 2, 3, 4]
: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 themap()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 typesmust 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 ' .. cendfor
: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. Forexample, to add up all the numbers in a list:
:exe 'let sum = ' .. join(nrlist, '+')
:let mydict = {1: 'one', 2: 'two', 3: 'three'}:let emptydict = {}
: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 andkey 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 thevalues() function:
:for v in values(mydict): echo "value: " .. v:endforIf you want both the key and the value use theitems() function. It returnsa 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
: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. Formore info seelist-identity.
:let dict[4] = "four":let dict['one'] = itemRemoving an entry from a Dictionary is done withremove() 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 withextend():
:call extend(adict, bdict)This extends adict with all entries from bdict. Duplicate keys cause entriesin adict to be overwritten. An optional third argument can change this.Note that the order of entries in a Dictionary is irrelevant, thus don'texpect ":echo adict" to show the items from bdict after the older entries inadict.
: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)
: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 theDictionary is aFuncref. The local variable "self" refers to the dictionarythe function was invoked from.
: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 aFuncrefthat references this function. The function can only be used through aFuncref. It will automatically be deleted when there is noFuncrefremaining that refers to it.
:function g:42
: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
: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 withreadfile() passing the
{type}
argumentset to "B", for example::let b = readfile('image.png', 'B')
: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 inthe 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 theget() function. When an itemis 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 longblob = 0z4455 + myblob
:let myblob += 0z6677
: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 issimilar 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 isbefore the first index, the result is an empty Blob. There is no errormessage.
:echo myblob[2:8]" result: 0z2233
:let blob[4] = 0x44When the index is just one beyond the end of the Blob, it is appended. Anyhigher index is an error.
let blob[1:3] = 0z445566The length of the replaced bytes must be exactly the same as the valueprovided.E972
:let blob[3:5] = 0z334455To add items to a Blob in-place, you can use:let+= (blob-concatenation):
:let blobA = 0z1122:let blobA += 0z3344
:let blobA = 0z1122:let blobB = blobA:let blobB += 0z3344:echo blobA0z11223344
if blob == 0z001122And for equal identity:
if blob is otherblob
:let blob = 0z112233:let blob2 = blob:echo blob == blob2
:echo blob is blob2
:let blob3 = blob[:]:echo blob == blob3
:echo blob is blob3
'string'
string constant, ' is doubled[expr1, ...]List{expr1: expr1, ...}
Dictionary #{key: expr1, ...}Dictionary &optionoption value(expr1)nested expressionvariableinternal variableva{ria}bleinternal variable with curly braces$VARenvironment variable@rcontents of register "r"function(expr1, ...)function callfunc{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 ?:. Theother two expressions can, thus allow for recursive use of ?:.Example:
:echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnumTo keep this readable, usingline-continuation is suggested:
:echo lnum == 1:\? "top":\: lnum == 1000:\? "last":\: lnumYou should always put a space before the ':', otherwise it can be mistaken foruse in a variable such as "a:1".
echo theList ?? 'list is empty'echo GetName() ?? 'unknown'These are similar, but not equal:
expr2 ?? expr1expr2 ? expr2 : expr1In the second line "expr2" is evaluated twice.
&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, furtherarguments are not evaluated. This is like what happens in C. For example:
let a = 1echo a || bThis is valid even if there is no variable called "b" because "a" isTRUE,so the result must beTRUE. Similarly below:
echo exists("b") && b == "yes"This is valid whether "b" has been defined or not. The second clause willonly be evaluated if "b" has been defined.
{cmp}
expr5if get(Part1, 'name') == get(Part2, 'name') " Part1 and Part2 refer to the same functionUsing "is" or "isnot" with aList,Dictionary orBlob checks whetherthe expressions are referring to the sameList,Dictionary orBlobinstance. A copy of aList is different from the originalList. Whenusing "is" without aList,Dictionary orBlob, it is equivalent tousing "equal", using "isnot" is equivalent to using "not equal". Except thata different type means the values are different:
echo 4 == '4'1echo 4 is '4'0echo 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.
1 . 90 + 90.0As:
(1 . 90) + 90.0That works, since the String "190" is automatically converted to the Number190, 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 thisattempts to concatenate a Float and a String.
byteidx()
for an alternative, or usesplit()
to turn the string into a list of characters. Example, to get thebyte 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 thecursor:
: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 aList index is equal to or higher than the length of theList, or more negative than the length of theList, this results in anerror.
: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
: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 aBlob this results in a newBlob with the bytes in theindexes 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 aFuncref results in anerror.
mylist[n:] " uses variable nmylist[s:] " uses namespace s:, error!expr8.nameentry in aDictionaryexpr-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 confusionalways put spaces around the dot for String concatenation.
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())
mylist\ ->filter(filterexpr)\ ->map(mapexpr)\ ->sort()\ ->join()When using the lambda form there must be no white space between the } and the
{N}
and{M}
are numbers. Both{N}
and{M}
must be present and can onlycontain 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 currentlocale is.{M}
1e40missing .{M}:let pi = 3.14159265359:let e = 2.71828182846Or, if you don't want to write them in as floating-point literals, you canalso use functions, like the following:
:let pi = acos(-1.0):let e = exp(1.0)
:echo printf('%.15e', atan(1))
<BS>
\eescape<Esc>
\fformfeed 0x0C\nnewline<NL>
\rreturn<CR>
\ttab<Tab>
\\backslash\"double quote\<xxx>Special key named "xxx". e.g. "\<C-W>" forCTRL-W
. This is for usein 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 asmentioned above.\<*xxx>Like \<xxx> but prepends a modifier instead of including it in thecharacter. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is fourbytes: 3 for the CTRL modifier and then character "W".:let b = 0zFF00ED015DAF
if a =~ "\\s*"if a =~ '\s*'
let your_name = input("What's your name? ")
echoecho $"Hello, {your_name}!"
echo $"The square root of {{9}} is {sqrt(9)}"
{9}
is 3.0echo "tabstop is " .. &tabstopif &expandtabAny option name can be used here. Seeoptions. When using the local valueand there is no buffer-local or window-local value, the global value is usedanyway.
getenv()
andsetenv()
can also be used and work forenvironment variables with non-alphanumeric names.The functionenviron()
can be used to get a Dict with all environmentvariables.:echo $shell:echo expand("$shell")The first one probably doesn't echo anything, the second echoes the $shellvariable (if your shell supports it).
:let F = {arg1, arg2 -> arg1 - arg2}:echo F(5, 2)
:let F = {-> 'error function'}:echo F('ignored')
: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 withsort(),map() andfilter():
: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 scoperefers to the closure. This cycle results in the memory not being freed.Recommendation: don't do this.
<lambda>
42'. If you get an errorfor a lambda expression, you can find what it is with the following command::function <lambda>42See also:numbered-function
:for k in keys(s:): unlet s:[k]:endfor
:if my_changedtick != b:changedtick:let my_changedtick = b:changedtick:call My_Update():endif
let s:counter = 0function MyCounter() let s:counter = s:counter + 1 echo s:counterendfunctioncommand Tick call MyCounter()You can now invoke "Tick" from any script, and the "s:counter" variable inthat script will not be changed, only the "s:counter" in the script where"Tick" was defined is used.
let s:counter = 0command Tick let s:counter = s:counter + 1 | echo s:counterWhen calling a function and invoking a user-defined command, the context forscript variables is set to the script where the function or command wasdefined.
let s:counter = 0function StartCounting(incr) if a:incr function MyCounter() let s:counter = s:counter + 1 endfunction else function MyCounter() let s:counter = s:counter - 1 endfunction endifendfunctionThis defines the MyCounter() function either for counting up or counting downwhen calling StartCounting(). It doesn't matter from where StartCounting() iscalled, 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 scriptvariables for each buffer. Use local buffer variables insteadb:var.
my_{adjective}_variableWhen Vim encounters this, it evaluates the expression inside the braces, putsthat in place of the expression, and re-interprets the whole as a variablename. 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" dependingon 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.
: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}
:letE18Set internal variable{var-name}
to the result of theexpression{expr1}
. The variable will get the typefrom the{expr}
. If{var-name}
didn't exist yet, itis created.{var-name}
[{idx}
] ={expr1}
E689{expr1}
.{var-name}
must refer to a list and{idx}
must be a valid index in that list. For nested listthe index can be repeated.This cannot be used to add an item to aList.This cannot be used to set a byte in a String. Youcan do that like this::let var = var[0:2] .. 'X' .. var[4:]
{var-name}
[{idx1}
:{idx2}] ={expr1}
E708E709E710Set a sequence of items in aList to the result ofthe expression{expr1}
, which must be a list with thecorrect 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 theend of the list, items will be added.{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 typeof{var}
and{expr1}
don't fit the operator.+=
modifies aList or aBlob in-place instead ofcreating a new one.{expr1}
:let-environment:let-$Set environment variable{env-name}
to the result ofthe 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 thisworks like "=".{expr1}
:let-register:let-@Write the result of the expression{expr1}
in register{reg-name}
.{reg-name}
must be a single letter, andmust be the name of a writable register (seeregisters). "@@" can be used for the unnamedregister, "@/" for the search pattern.If the result of{expr1}
ends in a<CR>
or<NL>
, theregister will be linewise, otherwise it will be set tocharwise.This can be used to clear the last search pattern::let @/ = ""
{expr1}
Append{expr1}
to register{reg-name}
. If theregister was empty it's like setting it to{expr1}
.{expr1}
:let-option:let-&Set option{option-name}
to the result of theexpression{expr1}
. A String or Number value isalways converted to the type of the option.For an option local to a window or buffer the effectis just like using the:set command: both the localvalue 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-unpackE687E688{expr1}
must evaluate to aList. The first item inthe list is assigned to{name1}
, the second item to{name2}
, etc.The number of names must match the number of items intheList.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 theassignments 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 eachList item.{name}
, ..., ;{lastname}
] ={expr1}
E452{lastname}
. If there are noremaining 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 eachList item.{var-name}
=<< [trim] [eval]{endmarker}
text...text...{endmarker}
Set internal variable{var-name}
to aListcontaining the lines of text bounded by the string{endmarker}
.{expr}
is evaluated and the result replaces theexpression, like withinterpolated-string.Example where $HOME is expanded:let lines =<< trim eval END some text See the file {$HOME}/.vimrc more textEND
{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 forwhite space after{endmarker}
!{endmarker}
, then indentation is stripped so you cando:let text =<< trim END if ok echo 'done' endifEND
["if ok", " echo 'done'", "endif"]
The marker must line up with "let" and the indentationof the first line is removed from all the text lines.Specifically: all the leading indentation exactlymatching the leading indentation of the firstnon-empty text line is stripped from the input lines.All leading indentation exactly matching the leadingindentation beforelet
is stripped from the linecontaining{endmarker}
. Note that the differencebetween space and tab matters here.{var-name}
didn't exist yet, it is created.Cannot be followed by another command, but can befollowed by a comment.set cpo+=Clet var =<< END \ leading backslashENDset cpo-=C
let var1 =<< ENDSample text 1 Sample text 2Sample text 3ENDlet data =<< trim DATA 1 2 3 4 5 6 7 8DATAlet code =<< trim eval CODE let v = {10 + 20} let h = "{$HOME}" let s = "{Str1()} abc {Str2()}" let n = {MyFunc(3, 4)}CODE
{var-name}
..List the value of variable{var-name}
. Multiplevariable names may be given. Special names recognizedhere:E738<nothing>
String#Number*Funcref{name}
...:unlet:unlE108E795Remove the internal variable{name}
. Several variablenames can be given, they are all removed. The namemay also be aList orDictionary item.With [!] no error message is given for non-existingvariables.One or more items from aList can be removed::unlet list[3] " remove fourth item:unlet list[3:] " remove fourth item to last
:unlet dict['two']:unlet dict.two
{env-name}
.Can mix{name}
and ${env-name} in one :unlet command.No error message is given for a non-existingvariable, also without !.If the system does not support deleting an environmentvariable, it is made empty.{var-name}
={expr1}
:cons[t] [{name1}
,{name2}
, ...] ={expr1}
:cons[t] [{name}
, ..., ;{lastname}
] ={expr1}
:cons[t]{var-name}
=<< [trim] [eval]{marker}
text...text...{marker}
Similar to:let, but additionally lock the variableafter setting the value. This is the same as lockingthe 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
{var-name}
If no argument is given or only{var-name}
is given,the behavior is the same as:let.{name}
...:lockvar:lockvLock the internal variable{name}
. Locking means thatit can no longer be changed (until it is unlocked).A locked variable can be deleted::lockvar v:let v = 'asdf' " fails!:unlet v " works
{name}
".If you try to lock or unlock a built-in variable youwill get an error message "E940: Cannot lock or unlockvariable{name}
".{name}
but not itsvalue.1Lock theList orDictionary itself,cannot add or remove items, but canstill change their values.2Also lock the values, cannot changethe items. If an item is aList orDictionary, cannot add or removeitems, but can still change thevalues.3Like 2 but for theList /Dictionary in theList /Dictionary, one level deeper.The default [depth] is 2, thus when{name}
is aListorDictionary the values cannot be changed.let mylist = [1, 2, 3]lockvar 0 mylistlet mylist[0] = 77" OKcall add(mylist, 4)" OKlet mylist = [7, 8, 9] " Error!
:let l = [0, 1, 2, 3]:let cl = l:lockvar l:let cl[1] = 99" won't work!
{name}
...:unlockvar:unloUnlock the internal variable{name}
. Does theopposite of:lockvar.{name}
does not exist.{expr1}
:if:end:endif:enE171E579E580: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 toalways use:endif
to avoid confusion and to makeauto-indenting work properly.:if
and:endif
is ignored. These twocommands were just to allow for future expansions in abackward compatible way. Nesting was allowed. Notethat any:else
or:elseif
was ignored, theelse
part was not executed either.:if version >= 500: version-5-specific-commands:endif
endif
. Sometimes an older Vim has a problem with anew command. For example,:silent
is recognized asa:substitute
command. In that case:execute
canavoid problems::if version >= 600: execute "silent 1,$delete":endif
:append
and:insert
commands don't workproperly in between:if
and:endif
.:else
or:endif
if they previously were not beingexecuted.{expr1}
Short for:else
:if
, with the addition that thereis no extra:endif
.{expr1}
:while:endwhile:wh:endwE170E585E588E733: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 theloop, execution continues after theendwhile
.Example::let lnum = 1:while lnum <= line("$") :call FixLine(lnum) :let lnum = lnum + 1:endwhile
:append
and:insert
commands don't workproperly inside a:while
and:for
loop.{var}
in{object}
:forE690E732:endfo[r]:endfo:endforRepeat the commands between:for
and:endfor
foreach item in{object}
.{object}
can be aList,aBlob or aString.{var}
is set to the value of each item.endfor
.Changing{object}
inside the loop affects what itemsare used. Make a copy if this is unwanted::for item in copy(mylist)
{object}
is aList and not making a copy, Vimstores a reference to the next item in theListbefore 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 wayto make aList empty):for item in mylist call remove(mylist, 0)endfor
{object}
is aBlob, Vim always makes a copy toiterate over. Unlike withList, modifying theBlob does not affect the iteration.{object}
is aString each item is a string withone character, plus any combining characters.{var1}
,{var2}
, ...] in{listlist}
:endfo[r]Like:for
above, but each item in{listlist}
must bea 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
:while
or:for
loop, jumps backto the start of the loop.:try
inside the loop butbefore the matching:finally
(if present), thecommands following the:finally
up to the matching:endtry
are executed first. This process applies toall nested:try
s inside the loop. The outermost:endtry
then jumps back to the start of the loop.:while
or:for
loop, skips tothe command after the matching:endwhile
or:endfor
.If it is used after a:try
inside the loop butbefore the matching:finally
(if present), thecommands following the:finally
up to the matching:endtry
are executed first. This process applies toall nested:try
s inside the loop. The outermost:endtry
then jumps to the command after the loop.:try
and:endtry
including everything beingexecuted across:source
commands, function calls,or autocommand invocations.:finally
command following, execution continuesafter the:finally
. Otherwise, or when the:endtry
is reached thereafter, the next(dynamically) surrounding:try
is checked fora corresponding:finally
etc. Then the scriptprocessing is terminated. Whether a functiondefinition has an "abort" argument does not matter.Example:try | call Unknown() | finally | echomsg "cleanup" | endtryechomsg "not reached"
:try
and:endtry
is converted to an exception. Itcan be caught as if it were thrown by a:throw
command (see:catch
). In this case, the scriptprocessing 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 theerror exception is not caught, always beginning withthe error number.Examples:try | sleep 100 | catch /^Vim:Interrupt$/ | endtrytry | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
:catch
,:finally
, or:endtry
that belongs to the same:try
as the:catch
are executed when an exceptionmatching{pattern}
is being thrown and has not yetbeen caught by a previous:catch
. Otherwise, thesecommands 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 specialmeaning (e.g., '|' or '"') and doesn't occur inside{pattern}
.Information about the exception is available inv:exception. Also seethrow-variables.NOTE: It is not reliable to ":catch" the TEXT ofan error message because it may vary in differentlocales.:endtry
are executed whenever the part between the matching:try
and the:finally
is left: either by fallingthrough to the:finally
or by a:continue
,:break
,:finish
, or:return
, or by an error orinterrupt or exception (see:throw
).{expr1}
The{expr1}
is evaluated and thrown as an exception.If the:throw
is used after a:try
but before thefirst corresponding:catch
, commands are skippeduntil the first:catch
matching{expr1}
is reached.If there is no such:catch
or if the:throw
isused after a:catch
but before the:finally
, thecommands following the:finally
(if present) up tothe matching:endtry
are executed. If the:throw
is after the:finally
, commands up to the:endtry
are skipped. At the:endtry
, this process appliesagain for the next dynamically surrounding:try
(which may be found in a calling function or sourcingscript), until a matching:catch
has been found.If the exception is not caught, the command processingis terminated.Example::try | throw "oops" | catch /^oo/ | echo "caught" | endtry
{expr1}
..Echoes each{expr1}
, with a space in between. Thefirst{expr1}
starts on a new line.Also see:comment.Use "\n" to start a new line. Use "\r" to move thecursor 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
causes a redraw afterwards (redraws are oftenpostponed until you type something), force a redrawwith the:redraw
command. Example::new | redraw | echo "there is a new window"
:let l = []:call add(l, l):let l2 = []:call add(l2, [l2]):echo l l2
{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 aVim command, and:!echo
, which is an external shellcommand::!echo %--> filename
:!echo "%"--> filename or "filename"
:echo %--> nothing
:echo "%"--> %
:echo expand("%")--> filename
{name}
Use the highlight group{name}
for the following:echo
,:echon
and:echomsg
commands. Also usedfor theinput()
prompt. Example::echohl WarningMsg | echo "Don't panic!" | echohl None
{expr1}
..Echo the expression(s) as a true message, saving themessage in themessage-history.Spaces are placed between the arguments as with the:echo
command. But unprintable characters aredisplayed, not interpreted.The parsing works slightly different from:echo
,more like:execute
. All the expressions are firstevaluated and concatenated before echoing anything.If expressions does not evaluate to a Number orString, 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."
{expr1}
..Echo the expression(s) as an error message, saving themessage in themessage-history. When used in ascript 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(seetry-echoerr).Example::echoerr "This script just failed!"
:echohl
.And to get a beep::exe "normal \<Esc>"
{expr}
Evaluate{expr}
and discard the result. Example::eval Getlist()->Filter()->append('$')
append()
call appends the List with text to thebuffer. This is similar to:call
but works with anyexpression.:ev
or:eva
, butthese are hard to recognize and therefore not to beused.{expr1}
..Executes the string that results from the evaluationof{expr1}
as an Ex command.Multiple arguments are concatenated, with a space inbetween. To avoid the extra space use the ".."operator to concatenate strings into one argument.{expr1}
is used as the processed command, command lineediting 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, seeexpr-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'
: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 theappropriate actions. Exceptions from the try block may be caught. Exceptionsfrom the try block and also the catch clauses may cause cleanup actions. When no exception is thrown during execution of the try block, the controlis transferred to the finally clause, if present. After its execution, thescript continues with the line following the ":endtry". When an exception occurs during execution of the try block, the remaininglines in the try block are skipped. The exception is matched against thepatterns specified as arguments to the ":catch" commands. The catch clauseafter the first matching ":catch" is taken, other catch clauses are notexecuted. 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 executioncontinues 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 bythat try conditional and none of the catch clauses is executed. Only thefinally clause, if present, is taken. The exception pends during execution ofthe finally clause. It is resumed at the ":endtry", so that commands afterthe ":endtry" are not executed and the exception might be caught elsewhere,seetry-nesting. When during execution of a catch clause another exception is thrown, theremaining lines in that catch clause are not executed. The new exception isnot matched against the patterns in any of the ":catch" commands of the sametry conditional and none of its catch clauses is taken. If there is, however,a finally clause, it is executed, and the exception pends during itsexecution. The commands following the ":endtry" are not executed. The newexception might, however, be caught elsewhere, seetry-nesting. When during execution of the finally clause (if present) an exception isthrown, the remaining lines in the finally clause are skipped. If the finallyclause has been taken because of an exception from the try block or one of thecatch clauses, the original (pending) exception is discarded. The commandsfollowing the ":endtry" are not executed, and the exception from the finallyclause is propagated and can be caught elsewhere, seetry-nesting.
:throw 4711:throw "string"
: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 notexecuted.
: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.
: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 arespecified. Only the first match counts. So you should place the morespecific ":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 isnever taken.
: catch /^\d\+$/: echo "Number thrown. Value is" v:exceptionYou may also be interested where an exception was thrown. This is stored inv:throwpoint. And you can obtain the stack trace fromv:stacktrace.Note that "v:exception", "v:stacktrace" and "v:throwpoint" are valid for theexception 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 caughtCaught "4711" in function Foo, line 4Caught "oops" in function Foo, line 10Nothing caughtA practical example: The following command ":LineNumber" displays the linenumber 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: 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 finallyclause is executed. The exception is then caught by the outer tryconditional. The example displays "inner finally" and then "foo".
: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".
:function! Bar(): try: call Foo(): catch /.*/: echo "Rethrow" v:exception: throw v:exception: endtry:endfunction
:try: try: asdf: catch /.*/: echoerr v:exception: endtry:catch /.*/: echo v:exception:endtryThis code displays
CTRL-C
, the settings remain inan inconsistent state. The same may happen to you in the development phase ofa script when an error occurs or you explicitly throw an exception withoutcatching it. You can solve these problems by using a try conditional witha finally clause for restoring the settings. Its execution is guaranteed onnormal control flow, on error, on an explicit ":throw", and on interrupt.(Note that errors and interrupts from inside the try conditional are convertedto exceptions. When not caught, they terminate the script after the finallyclause 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 scriptchanges global settings which need to be restored on failure or normal exit ofthat function or script part.
: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 anextra ":return" in the finally clause. (Above all, this would override thereturn value.)
: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 shouldthink about catching or ignoring the errors in these commands, seecatch-errors andignore-errors.
Vim({cmdname}):{errmsg}or
Vim:{errmsg}
{cmdname}
is the name of the command that failed; the second form is used whenthe command name is not known.{errmsg}
is the error message usually producedwhen the error occurs outside try conditionals. It always begins witha capital "E", followed by a two or three-digit error number, a colon, anda 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 thecommand 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: novarE15: Invalid expression: novarOnly the first is used for the exception value, since it is the most specificone (seeexcept-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 /No such variable/only works in the English locale, but not when the user has selecteda different language by the:language command. It is however helpful tocite 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 couldcatch more than you want. With the ":write" command, some autocommands couldbe 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 scriptwriter: a user of your script might have defined such autocommands. You wouldthen 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 ignoreintentionally.
:silent! nunmap kThis works also when a try conditional is active.
CTRL-C
) is converted tothe exception "Vim:Interrupt". You can catch it like every exception. Thescript 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 fora new command. If you pressCTRL-C
at the prompt, the script is terminated.CTRL-C
would be pressed on a specific line inyour script, use the debug mode and execute the>quit or>interruptcommand on that line. Seedebug-scripts.:catch /.*/:catch //:catchcatch everything, error exceptions, interrupt exceptions and exceptionsexplicitly thrown by the:throw command. This is useful at the top level ofa 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 arestrongly encouraged to catch only for problems that you can really handle byspecifying a pattern argument to the ":catch". Example: Catching all could make it nearly impossible to interrupt a scriptby 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!".
: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 (asyou can see by checking'modified'), since the exception from the BufWritePreautocommand abandons the ":write". The exception is then caught and thescript displays:
Caught: FAIL from BufWrite Auto commands for "*"
: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 actionfails, 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
: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 displaysfirst
File successfully written!then
Error on writing (file contents not changed)then
Error after writingetc.
: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
) usea flat hierarchy: they are all in the "Vim" class. You cannot throw yourselfexceptions with the "Vim" prefix; they are reserved for Vim. Vim error exceptions are parameterized with the name of the command thatfailed, if known. Seecatch-errors.: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 finallyouter catch-all caught "Vim(catch):E54: Unmatched \("outer finallyThe original exception is discarded and an error exception is raised, instead.
: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 theerror exception is discarded and the "E488: Trailing characters" message getsdisplayed.
echo novarcauses
E121: Undefined variable: novarE15: Invalid expression: novarThe value of the error exception inside try conditionals is:
Vim(echo):E121: Undefined variable: novar
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 waynot intended by the user. Example:
try try | unlet novar # | catch | echo v:exception | endtrycatch /.*/ echo "outer catch:" v:exceptionendtryThis displays "outer catch: Vim(unlet):E488: Trailing characters", and thena "E600: Missing :endtry" error message is given, seeexcept-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")))
:" 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
command can be used to get a list of all script files thathave been sourced. There is also thegetscriptinfo()
function, but theinformation returned is not exactly the same. In case you need to manipulatethe output ofscriptnames
this code can be used:" Get the output of ":scriptnames" in the scriptnames_output variable.let scriptnames_output = ''redir => scriptnames_outputsilent scriptnamesredir 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 endifendforunlet scriptnames_output
CTRL-R
= in the command line.The sandbox is also used for the:sandbox command.{cmd}
Execute{cmd}
in the sandbox. Useful to evaluate anoption that may have been set from a modeline, e.g.'foldexpr'.Error
is usedand some other intermediate groups are present.=
in:lethl-NvimAugmentedAssignment NvimAssignment Generic,+=
/`-=`/`.=`hl-NvimAssignmentWithAddition NvimAugmentedAssignment+=
in:let+=hl-NvimAssignmentWithSubtraction NvimAugmentedAssignment-=
in:let-=hl-NvimAssignmentWithConcatenation NvimAugmentedAssignment.=
in:let.=#
/`?` nearexpr4 ophl-NvimBinaryPlus NvimBinaryOperatorexpr-+hl-NvimBinaryMinus NvimBinaryOperatorexpr--hl-NvimConcat NvimBinaryOperatorexpr-.hl-NvimConcatOrSubscript NvimConcatexpr-. orexpr-entryhl-NvimOr NvimBinaryOperatorexpr-barbarhl-NvimAnd NvimBinaryOperatorexpr-&&hl-NvimMultiplication NvimBinaryOperatorexpr-starhl-NvimDivision NvimBinaryOperatorexpr-/hl-NvimMod NvimBinaryOperatorexpr-%{
/`}` inlambdahl-NvimNestingParenthesis NvimParenthesis(
/`)` inexpr-nestinghl-NvimCallingParenthesis NvimParenthesis(
/`)` inexpr-function[
/`]` inexpr-[]hl-NvimSubscriptColon NvimSubscript:
inexpr-[:]hl-NvimCurly NvimSubscript{
/`}` incurly-braces-names{
/`}` indict literalhl-NvimList NvimContainer[
/`]` inlist literal:
ininternal-variableshl-NvimIdentifierScopeDelimiter NvimIdentifier:
after namespace letterhl-NvimIdentifierName NvimIdentifier Rest of the identhl-NvimIdentifierKey NvimIdentifier Identifier afterexpr-entry:
indict literalhl-NvimComma Delimiter,
indict orlist literal orexpr-functionhl-NvimArrow Delimiter->
inlambda0
foroctal-number0x
forhex-number0b
forbinary-numberhl-NvimFloat NvimNumber Floating-point number&
inexpr-optionhl-NvimOptionScope NvimIdentifierScope Option scope if anyhl-NvimOptionScopeDelimiter NvimIdentifierScopeDelimiter:
after option scopehl-NvimOptionName NvimIdentifier Option name$
inexpr-envhl-NvimEnvironmentName NvimIdentifier Env variable name'
inexpr-'hl-NvimSingleQuotedBody NvimStringBody Literal part ofexpr-' string bodyhl-NvimSingleQuotedQuote NvimStringSpecial''
insideexpr-' string body"
inexpr-quotehl-NvimDoubleQuotedBody NvimStringBody Literal part ofexpr-quote bodyhl-NvimDoubleQuotedEscape NvimStringSpecial Validexpr-quote escape sequencehl-NvimDoubleQuotedUnknownEscape NvimInvalidValue Unrecognizedexpr-quote escape sequence