robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
b107154ba2
master
1*vimeval.txt* Nvim 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7Expression evaluation *expression* *expr* *E15* *eval* *eval.txt* 8 9Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|. 10 11 Type |gO| to see the table of contents. 12 13============================================================================== 141. Variables *variables* 15 161.1 Variable types ~ 17 *E712* *E896* *E897* *E899* *E908* *E909* 18 *E928* *E964* *E966* *E1023* *E1098* *E1174* *E1175* 19 *E1203* *E1206* *E1210* *E1211* *E1212* *E1219* *E1220* 20 *E1222* *E1225* *E1226* *E1238* *E1250* *E1252* *E1256* 21 *E1265* *E1297* *E5010* *E5050* *E5060* *E5070* *E5071* 22 *E5299* *E5300* *E5401* *E5420* *E6000* 23There are seven types of variables: 24 25 *Number* *Integer* 26Number A 32 or 64 bit signed number. |expr-number| 27 The number of bits is available in |v:numbersize|. 28 Examples: -123 0x10 0177 0o177 0b1011 29 30Float A floating point number. |floating-point-format| *Float* 31 Examples: 123.456 1.15e-6 -1.1e3 32 33String A NUL terminated string of 8-bit unsigned characters (bytes). 34 |expr-string| Examples: "ab\txx\"--" 'x-z''a,c' 35 36Funcref A reference to a function |Funcref|. 37 Example: function("strlen") 38 It can be bound to a dictionary and arguments, it then works 39 like a Partial. 40 Example: function("Callback", [arg], myDict) 41 42List An ordered sequence of items, see |List| for details. 43 Example: [1, 2, ['a', 'b']] 44 45Dictionary An associative, unordered array: Each entry has a key and a 46 value. |Dictionary| 47 Examples: > 48 {"blue": "#0000ff", "red": "#ff0000"} 49 #{blue: "#0000ff", red: "#ff0000"} 50 51Blob Binary Large Object. Stores any sequence of bytes. See |Blob| 52 for details. 53 Example: 0zFF00ED015DAF 54 0z is an empty Blob. 55 56The Number and String types are converted automatically, depending on how they 57are used. 58 59Conversion from a Number to a String is by making the ASCII representation of 60the Number. Examples: 61 Number 123 --> String "123" ~ 62 Number 0 --> String "0" ~ 63 Number -1 --> String "-1" ~ 64 *octal* 65Conversion from a String to a Number is done by converting the first digits to 66a number. Hexadecimal "0xf9", Octal "017" or "0o17", and Binary "0b10" 67numbers are recognized. If the String doesn't start with digits, the result 68is zero. Examples: 69 String "456" --> Number 456 ~ 70 String "6bar" --> Number 6 ~ 71 String "foo" --> Number 0 ~ 72 String "0xf1" --> Number 241 ~ 73 String "0100" --> Number 64 ~ 74 String "0o100" --> Number 64 ~ 75 String "0b101" --> Number 5 ~ 76 String "-8" --> Number -8 ~ 77 String "+8" --> Number 0 ~ 78 79To force conversion from String to Number, add zero to it: > 80 :echo "0100" + 0 81< 64 ~ 82 83To avoid a leading zero to cause octal conversion, or for using a different 84base, use |str2nr()|. 85 86 *TRUE* *FALSE* *Boolean* 87For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE. 88You can also use |v:false| and |v:true|. 89When TRUE is returned from a function it is the Number one, FALSE is the 90number zero. 91 92Note that in the command: > 93 :if "foo" 94 :" NOT executed 95"foo" is converted to 0, which means FALSE. If the string starts with a 96non-zero number it means TRUE: > 97 :if "8foo" 98 :" executed 99To test for a non-empty string, use empty(): > 100 :if !empty("foo") 101 102< *falsy* *truthy* 103An expression can be used as a condition, ignoring the type and only using 104whether the value is "sort of true" or "sort of false". Falsy is: 105 the number zero 106 empty string, blob, list or dictionary 107Other values are truthy. Examples: 108 0 falsy 109 1 truthy 110 -1 truthy 111 0.0 falsy 112 0.1 truthy 113 '' falsy 114 'x' truthy 115 [] falsy 116 [0] truthy 117 {} falsy 118 #{x: 1} truthy 119 0z falsy 120 0z00 truthy 121 122 *non-zero-arg* 123Function arguments often behave slightly different from |TRUE|: If the 124argument is present and it evaluates to a non-zero Number, |v:true| or a 125non-empty String, then the value is considered to be TRUE. 126Note that " " and "0" are also non-empty strings, thus considered to be TRUE. 127A List, Dictionary or Float is not a Number or String, thus evaluate to FALSE. 128 129 *E745* *E728* *E703* *E729* *E730* *E731* 130 *E974* *E975* *E976* 131|List|, |Dictionary|, |Funcref|, and |Blob| types are not automatically 132converted. 133 134 *E805* *E806* *E808* 135When mixing Number and Float the Number is converted to Float. Otherwise 136there is no automatic conversion of Float. You can use str2float() for String 137to Float, printf() for Float to String and float2nr() for Float to Number. 138 139 *E362* *E891* *E892* *E893* *E894* *E907* 140When expecting a Float a Number can also be used, but nothing else. 141 142 *no-type-checking* 143You will not get an error if you try to change the type of a variable. 144 145 1461.2 Function references ~ 147 *Funcref* *E695* *E718* *E1192* 148A Funcref variable is obtained with the |function()| function, the |funcref()| 149function or created with the lambda expression |expr-lambda|. It can be used 150in an expression in the place of a function name, before the parenthesis 151around the arguments, to invoke the function it refers to. Example: > 152 153 :let Fn = function("MyFunc") 154 :echo Fn() 155< *E704* *E705* *E707* 156A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You 157can use "g:" but the following name must still start with a capital. You 158cannot have both a Funcref variable and a function with the same name. 159 160A special case is defining a function and directly assigning its Funcref to a 161Dictionary entry. Example: > 162 :function dict.init() dict 163 : let self.val = 0 164 :endfunction 165 166The key of the Dictionary can start with a lower case letter. The actual 167function name is not used here. Also see |numbered-function|. 168 169A Funcref can also be used with the |:call| command: > 170 :call Fn() 171 :call dict.init() 172 173The name of the referenced function can be obtained with |string()|. > 174 :let func = string(Fn) 175 176You can use |call()| to invoke a Funcref and use a list variable for the 177arguments: > 178 :let r = call(Fn, mylist) 179< 180 *Partial* 181A Funcref optionally binds a Dictionary and/or arguments. This is also called 182a Partial. This is created by passing the Dictionary and/or arguments to 183function() or funcref(). When calling the function the Dictionary and/or 184arguments will be passed to the function. Example: > 185 186 let Cb = function('Callback', ['foo'], myDict) 187 call Cb('bar') 188 189This will invoke the function as if using: > 190 call myDict.Callback('foo', 'bar') 191 192Note that binding a function to a Dictionary also happens when the function is 193a member of the Dictionary: > 194 195 let myDict.myFunction = MyFunction 196 call myDict.myFunction() 197 198Here MyFunction() will get myDict passed as "self". This happens when the 199"myFunction" member is accessed. When assigning "myFunction" to otherDict 200and calling it, it will be bound to otherDict: > 201 202 let otherDict.myFunction = myDict.myFunction 203 call otherDict.myFunction() 204 205Now "self" will be "otherDict". But when the dictionary was bound explicitly 206this won't happen: > 207 208 let myDict.myFunction = function(MyFunction, myDict) 209 let otherDict.myFunction = myDict.myFunction 210 call otherDict.myFunction() 211 212Here "self" will be "myDict", because it was bound explicitly. 213 214 2151.3 Lists ~ 216 *list* *List* *Lists* *E686* 217A List is an ordered sequence of items. An item can be of any type. Items 218can be accessed by their index number. Items can be added and removed at any 219position in the sequence. 220 221 222List creation ~ 223 *E696* *E697* 224A List is created with a comma-separated list of items in square brackets. 225Examples: > 226 :let mylist = [1, two, 3, "four"] 227 :let emptylist = [] 228 229An item can be any expression. Using a List for an item creates a 230List of Lists: > 231 :let nestlist = [[11, 12], [21, 22], [31, 32]] 232 233An extra comma after the last item is ignored. 234 235 236List index ~ 237 *list-index* *E684* 238An item in the List can be accessed by putting the index in square brackets 239after the List. Indexes are zero-based, thus the first item has index zero. > 240 :let item = mylist[0] " get the first item: 1 241 :let item = mylist[2] " get the third item: 3 242 243When the resulting item is a list this can be repeated: > 244 :let item = nestlist[0][1] " get the first list, second item: 12 245< 246A negative index is counted from the end. Index -1 refers to the last item in 247the List, -2 to the last but one item, etc. > 248 :let last = mylist[-1] " get the last item: "four" 249 250To avoid an error for an invalid index use the |get()| function. When an item 251is not available it returns zero or the default value you specify: > 252 :echo get(mylist, idx) 253 :echo get(mylist, idx, "NONE") 254 255 256List concatenation ~ 257 *list-concatenation* 258Two lists can be concatenated with the "+" operator: > 259 :let longlist = mylist + [5, 6] 260 :let longlist = [5, 6] + mylist 261To prepend or append an item, turn it into a list by putting [] around it. 262 263A list can be concatenated with another one in-place using |:let+=| or 264|extend()|: > 265 :let mylist += [7, 8] 266 :call extend(mylist, [7, 8]) 267< 268See |list-modification| below for more about changing a list in-place. 269 270 271Sublist ~ 272 *sublist* 273A part of the List can be obtained by specifying the first and last index, 274separated by a colon in square brackets: > 275 :let shortlist = mylist[2:-1] " get List [3, "four"] 276 277Omitting the first index is similar to zero. Omitting the last index is 278similar to -1. > 279 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"] 280 :let shortlist = mylist[2:2] " List with one item: [3] 281 :let otherlist = mylist[:] " make a copy of the List 282 283Notice that the last index is inclusive. If you prefer using an exclusive 284index use the |slice()| method. 285 286If the first index is beyond the last item of the List or the second item is 287before the first item, the result is an empty list. There is no error 288message. 289 290If the second index is equal to or greater than the length of the list the 291length minus one is used: > 292 :let mylist = [0, 1, 2, 3] 293 :echo mylist[2:8] " result: [2, 3] 294 295NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for 296using a single letter variable before the ":". Insert a space when needed: 297mylist[s : e]. 298 299 300List identity ~ 301 *list-identity* 302When variable "aa" is a list and you assign it to another variable "bb", both 303variables refer to the same list. Thus changing the list "aa" will also 304change "bb": > 305 :let aa = [1, 2, 3] 306 :let bb = aa 307 :call add(aa, 4) 308 :echo bb 309< [1, 2, 3, 4] 310 311Making a copy of a list is done with the |copy()| function. Using [:] also 312works, as explained above. This creates a shallow copy of the list: Changing 313a list item in the list will also change the item in the copied list: > 314 :let aa = [[1, 'a'], 2, 3] 315 :let bb = copy(aa) 316 :call add(aa, 4) 317 :let aa[0][1] = 'aaa' 318 :echo aa 319< [[1, aaa], 2, 3, 4] > 320 :echo bb 321< [[1, aaa], 2, 3] 322 323To make a completely independent list use |deepcopy()|. This also makes a 324copy of the values in the list, recursively. Up to a hundred levels deep. 325 326The operator "is" can be used to check if two variables refer to the same 327List. "isnot" does the opposite. In contrast "==" compares if two lists have 328the same value. > 329 :let alist = [1, 2, 3] 330 :let blist = [1, 2, 3] 331 :echo alist is blist 332< 0 > 333 :echo alist == blist 334< 1 335 336Note about comparing lists: Two lists are considered equal if they have the 337same length and all items compare equal, as with using "==". There is one 338exception: When comparing a number with a string they are considered 339different. There is no automatic type conversion, as with using "==" on 340variables. Example: > 341 echo 4 == "4" 342< 1 > 343 echo [4] == ["4"] 344< 0 345 346Thus comparing Lists is more strict than comparing numbers and strings. You 347can compare simple values this way too by putting them in a list: > 348 349 :let a = 5 350 :let b = "5" 351 :echo a == b 352< 1 > 353 :echo [a] == [b] 354< 0 355 356 357List unpack ~ 358 359To unpack the items in a list to individual variables, put the variables in 360square brackets, like list items: > 361 :let [var1, var2] = mylist 362 363When the number of variables does not match the number of items in the list 364this produces an error. To handle any extra items from the list append ";" 365and a variable name: > 366 :let [var1, var2; rest] = mylist 367 368This works like: > 369 :let var1 = mylist[0] 370 :let var2 = mylist[1] 371 :let rest = mylist[2:] 372 373Except that there is no error if there are only two items. "rest" will be an 374empty list then. 375 376 377List modification ~ 378 *list-modification* 379To change a specific item of a list use |:let| this way: > 380 :let list[4] = "four" 381 :let listlist[0][3] = item 382 383To change part of a list you can specify the first and last item to be 384modified. The value must at least have the number of items in the range: > 385 :let list[3:5] = [3, 4, 5] 386 387To add items to a List in-place, you can use |:let+=| (|list-concatenation|): > 388 :let listA = [1, 2] 389 :let listA += [3, 4] 390< 391When two variables refer to the same List, changing one List in-place will 392cause the referenced List to be changed in-place: > 393 :let listA = [1, 2] 394 :let listB = listA 395 :let listB += [3, 4] 396 :echo listA 397 [1, 2, 3, 4] 398< 399Adding and removing items from a list is done with functions. Here are a few 400examples: > 401 :call insert(list, 'a') " prepend item 'a' 402 :call insert(list, 'a', 3) " insert item 'a' before list[3] 403 :call add(list, "new") " append String item 404 :call add(list, [1, 2]) " append a List as one new item 405 :call extend(list, [1, 2]) " extend the list with two more items 406 :let i = remove(list, 3) " remove item 3 407 :unlet list[3] " idem 408 :let l = remove(list, 3, -1) " remove items 3 to last item 409 :unlet list[3 : ] " idem 410 :call filter(list, 'v:val !~ "x"') " remove items with an 'x' 411 412Changing the order of items in a list: > 413 :call sort(list) " sort a list alphabetically 414 :call reverse(list) " reverse the order of items 415 :call uniq(sort(list)) " sort and remove duplicates 416 417 418For loop ~ 419 420The |:for| loop executes commands for each item in a |List|, |String| or |Blob|. 421A variable is set to each item in sequence. Example with a List: > 422 :for item in mylist 423 : call Doit(item) 424 :endfor 425 426This works like: > 427 :let index = 0 428 :while index < len(mylist) 429 : let item = mylist[index] 430 : :call Doit(item) 431 : let index = index + 1 432 :endwhile 433 434If all you want to do is modify each item in the list then the |map()| 435function will be a simpler method than a for loop. 436 437Just like the |:let| command, |:for| also accepts a list of variables. This 438requires the argument to be a List of Lists. > 439 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]] 440 : call Doit(lnum, col) 441 :endfor 442 443This works like a |:let| command is done for each list item. Again, the types 444must remain the same to avoid an error. 445 446It is also possible to put remaining items in a List variable: > 447 :for [i, j; rest] in listlist 448 : call Doit(i, j) 449 : if !empty(rest) 450 : echo "remainder: " .. string(rest) 451 : endif 452 :endfor 453 454For a Blob one byte at a time is used. 455 456For a String one character, including any composing characters, is used as a 457String. Example: > 458 for c in text 459 echo 'This character is ' .. c 460 endfor 461 462 463List functions ~ 464 *E714* 465Functions that are useful with a List: > 466 :let r = call(funcname, list) " call a function with an argument list 467 :if empty(list) " check if list is empty 468 :let l = len(list) " number of items in list 469 :let big = max(list) " maximum value in list 470 :let small = min(list) " minimum value in list 471 :let xs = count(list, 'x') " count nr of times 'x' appears in list 472 :let i = index(list, 'x') " index of first 'x' in list 473 :let lines = getline(1, 10) " get ten text lines from buffer 474 :call append('$', lines) " append text lines in buffer 475 :let list = split("a b c") " create list from items in a string 476 :let string = join(list, ', ') " create string from list items 477 :let s = string(list) " String representation of list 478 :call map(list, '">> " .. v:val') " prepend ">> " to each item 479 480Don't forget that a combination of features can make things simple. For 481example, to add up all the numbers in a list: > 482 :exe 'let sum = ' .. join(nrlist, '+') 483 484 4851.4 Dictionaries ~ 486 *Dict* *dict* *Dictionaries* *Dictionary* 487A Dictionary is an associative array: Each entry has a key and a value. The 488entry can be located with the key. The entries are stored without a specific 489ordering. 490 491 492Dictionary creation ~ 493 *E720* *E721* *E722* *E723* 494A Dictionary is created with a comma-separated list of entries in curly 495braces. Each entry has a key and a value, separated by a colon. Each key can 496only appear once. Examples: > 497 :let mydict = {1: 'one', 2: 'two', 3: 'three'} 498 :let emptydict = {} 499< *E713* *E716* *E717* 500A key is always a String. You can use a Number, it will be converted to a 501String automatically. Thus the String '4' and the number 4 will find the same 502entry. Note that the String '04' and the Number 04 are different, since the 503Number will be converted to the String '4', leading zeros are dropped. The 504empty string can also be used as a key. 505 *literal-Dict* *#{}* 506To avoid having to put quotes around every key the #{} form can be used. This 507does require the key to consist only of ASCII letters, digits, '-' and '_'. 508Example: > 509 :let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3} 510Note that 333 here is the string "333". Empty keys are not possible with #{}. 511 512A value can be any expression. Using a Dictionary for a value creates a 513nested Dictionary: > 514 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}} 515 516An extra comma after the last entry is ignored. 517 518 519Accessing entries ~ 520 521The normal way to access an entry is by putting the key in square brackets: > 522 :let val = mydict["one"] 523 :let mydict["four"] = 4 524 525You can add new entries to an existing Dictionary this way, unlike Lists. 526 527For keys that consist entirely of letters, digits and underscore the following 528form can be used |expr-entry|: > 529 :let val = mydict.one 530 :let mydict.four = 4 531 532Since an entry can be any type, also a List and a Dictionary, the indexing and 533key lookup can be repeated: > 534 :echo dict.key[idx].key 535 536 537Dictionary to List conversion ~ 538 539You may want to loop over the entries in a dictionary. For this you need to 540turn the Dictionary into a List and pass it to |:for|. 541 542Most often you want to loop over the keys, using the |keys()| function: > 543 :for key in keys(mydict) 544 : echo key .. ': ' .. mydict[key] 545 :endfor 546 547The List of keys is unsorted. You may want to sort them first: > 548 :for key in sort(keys(mydict)) 549 550To loop over the values use the |values()| function: > 551 :for v in values(mydict) 552 : echo "value: " .. v 553 :endfor 554 555If you want both the key and the value use the |items()| function. It returns 556a List in which each item is a List with two items, the key and the value: > 557 :for [key, value] in items(mydict) 558 : echo key .. ': ' .. value 559 :endfor 560 561 562Dictionary identity ~ 563 *dict-identity* 564Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a 565Dictionary. Otherwise, assignment results in referring to the same 566Dictionary: > 567 :let onedict = {'a': 1, 'b': 2} 568 :let adict = onedict 569 :let adict['a'] = 11 570 :echo onedict['a'] 571 11 572 573Two Dictionaries compare equal if all the key-value pairs compare equal. For 574more info see |list-identity|. 575 576 577Dictionary modification ~ 578 *dict-modification* 579To change an already existing entry of a Dictionary, or to add a new entry, 580use |:let| this way: > 581 :let dict[4] = "four" 582 :let dict['one'] = item 583 584Removing an entry from a Dictionary is done with |remove()| or |:unlet|. 585Three ways to remove the entry with key "aaa" from dict: > 586 :let i = remove(dict, 'aaa') 587 :unlet dict.aaa 588 :unlet dict['aaa'] 589 590Merging a Dictionary with another is done with |extend()|: > 591 :call extend(adict, bdict) 592This extends adict with all entries from bdict. Duplicate keys cause entries 593in adict to be overwritten. An optional third argument can change this. 594Note that the order of entries in a Dictionary is irrelevant, thus don't 595expect ":echo adict" to show the items from bdict after the older entries in 596adict. 597 598Weeding out entries from a Dictionary can be done with |filter()|: > 599 :call filter(dict, 'v:val =~ "x"') 600This removes all entries from "dict" with a value not matching 'x'. 601This can also be used to remove all entries: > 602 call filter(dict, 0) 603 604 605Dictionary function ~ 606 *Dictionary-function* *self* *E725* *E862* 607When a function is defined with the "dict" attribute it can be used in a 608special way with a dictionary. Example: > 609 :function Mylen() dict 610 : return len(self.data) 611 :endfunction 612 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")} 613 :echo mydict.len() 614 615This is like a method in object oriented programming. The entry in the 616Dictionary is a |Funcref|. The local variable "self" refers to the dictionary 617the function was invoked from. 618 619It is also possible to add a function without the "dict" attribute as a 620Funcref to a Dictionary, but the "self" variable is not available then. 621 622 *numbered-function* *anonymous-function* 623To avoid the extra name for the function it can be defined and directly 624assigned to a Dictionary in this way: > 625 :let mydict = {'data': [0, 1, 2, 3]} 626 :function mydict.len() 627 : return len(self.data) 628 :endfunction 629 :echo mydict.len() 630 631The function will then get a number and the value of dict.len is a |Funcref| 632that references this function. The function can only be used through a 633|Funcref|. It will automatically be deleted when there is no |Funcref| 634remaining that refers to it. 635 636It is not necessary to use the "dict" attribute for a numbered function. 637 638If you get an error for a numbered function, you can find out what it is with 639a trick. Assuming the function is 42, the command is: > 640 :function g:42 641 642 643Functions for Dictionaries ~ 644 *E715* 645Functions that can be used with a Dictionary: > 646 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo" 647 :if empty(dict) " TRUE if dict is empty 648 :let l = len(dict) " number of items in dict 649 :let big = max(dict) " maximum value in dict 650 :let small = min(dict) " minimum value in dict 651 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict 652 :let s = string(dict) " String representation of dict 653 :call map(dict, '">> " .. v:val') " prepend ">> " to each item 654 655 6561.5 Blobs ~ 657 *blob* *Blob* *Blobs* *E978* 658A Blob is a binary object. It can be used to read an image from a file and 659send it over a channel, for example. 660 661A Blob mostly behaves like a |List| of numbers, where each number has the 662value of an 8-bit byte, from 0 to 255. 663 664 665Blob creation ~ 666 667A Blob can be created with a |blob-literal|: > 668 :let b = 0zFF00ED015DAF 669Dots can be inserted between bytes (pair of hex characters) for readability, 670they don't change the value: > 671 :let b = 0zFF00.ED01.5DAF 672 673A blob can be read from a file with |readfile()| passing the {type} argument 674set to "B", for example: > 675 :let b = readfile('image.png', 'B') 676 677 678Blob index ~ 679 *blob-index* *E979* 680A byte in the Blob can be accessed by putting the index in square brackets 681after the Blob. Indexes are zero-based, thus the first byte has index zero. > 682 :let myblob = 0z00112233 683 :let byte = myblob[0] " get the first byte: 0x00 684 :let byte = myblob[2] " get the third byte: 0x22 685 686A negative index is counted from the end. Index -1 refers to the last byte in 687the Blob, -2 to the last but one byte, etc. > 688 :let last = myblob[-1] " get the last byte: 0x33 689 690To avoid an error for an invalid index use the |get()| function. When an item 691is not available it returns -1 or the default value you specify: > 692 :echo get(myblob, idx) 693 :echo get(myblob, idx, 999) 694 695 696Blob iteration ~ 697 698The |:for| loop executes commands for each byte of a Blob. The loop variable is 699set to each byte in the Blob. Example: > 700 :for byte in 0z112233 701 : call Doit(byte) 702 :endfor 703This calls Doit() with 0x11, 0x22 and 0x33. 704 705 706Blob concatenation ~ 707 *blob-concatenation* 708Two blobs can be concatenated with the "+" operator: > 709 :let longblob = myblob + 0z4455 710 :let longblob = 0z4455 + myblob 711< 712A blob can be concatenated with another one in-place using |:let+=|: > 713 :let myblob += 0z6677 714< 715See |blob-modification| below for more about changing a blob in-place. 716 717 718Part of a blob ~ 719 720A part of the Blob can be obtained by specifying the first and last index, 721separated by a colon in square brackets: > 722 :let myblob = 0z00112233 723 :let shortblob = myblob[1:2] " get 0z1122 724 :let shortblob = myblob[2:-1] " get 0z2233 725 726Omitting the first index is similar to zero. Omitting the last index is 727similar to -1. > 728 :let endblob = myblob[2:] " from item 2 to the end: 0z2233 729 :let shortblob = myblob[2:2] " Blob with one byte: 0z22 730 :let otherblob = myblob[:] " make a copy of the Blob 731 732If the first index is beyond the last byte of the Blob or the second index is 733before the first index, the result is an empty Blob. There is no error 734message. 735 736If the second index is equal to or greater than the length of the Blob the 737length minus one is used: > 738 :echo myblob[2:8] " result: 0z2233 739 740 741Blob modification ~ 742 *blob-modification* 743To change a specific byte of a blob use |:let| this way: > 744 :let blob[4] = 0x44 745 746When the index is just one beyond the end of the Blob, it is appended. Any 747higher index is an error. 748 749To change a sequence of bytes the [:] notation can be used: > 750 let blob[1:3] = 0z445566 751The length of the replaced bytes must be exactly the same as the value 752provided. *E972* 753 754To change part of a blob you can specify the first and last byte to be 755modified. The value must have the same number of bytes in the range: > 756 :let blob[3:5] = 0z334455 757 758To add items to a Blob in-place, you can use |:let+=| (|blob-concatenation|): > 759 :let blobA = 0z1122 760 :let blobA += 0z3344 761< 762When two variables refer to the same Blob, changing one Blob in-place will 763cause the referenced Blob to be changed in-place: > 764 :let blobA = 0z1122 765 :let blobB = blobA 766 :let blobB += 0z3344 767 :echo blobA 768 0z11223344 769< 770You can also use the functions |add()|, |remove()| and |insert()|. 771 772 773Blob identity ~ 774 775Blobs can be compared for equality: > 776 if blob == 0z001122 777And for equal identity: > 778 if blob is otherblob 779< *blob-identity* *E977* 780When variable "aa" is a Blob and you assign it to another variable "bb", both 781variables refer to the same Blob. Then the "is" operator returns true. 782 783When making a copy using [:] or |copy()| the values are the same, but the 784identity is different: > 785 :let blob = 0z112233 786 :let blob2 = blob 787 :echo blob == blob2 788< 1 > 789 :echo blob is blob2 790< 1 > 791 :let blob3 = blob[:] 792 :echo blob == blob3 793< 1 > 794 :echo blob is blob3 795< 0 796 797Making a copy of a Blob is done with the |copy()| function. Using [:] also 798works, as explained above. 799 800 8011.6 More about variables ~ 802 *more-variables* 803If you need to know the type of a variable or expression, use the |type()| 804function. 805 806When the '!' flag is included in the 'shada' option, global variables that 807start with an uppercase letter, and don't contain a lowercase letter, are 808stored in the shada file |shada-file|. 809 810When the 'sessionoptions' option contains "global", global variables that 811start with an uppercase letter and contain at least one lowercase letter are 812stored in the session file |session-file|. 813 814variable name can be stored where ~ 815my_var_6 not 816My_Var_6 session file 817MY_VAR_6 shada file 818 819 820It's possible to form a variable name with curly braces, see 821|curly-braces-names|. 822 823============================================================================== 8242. Expression syntax *expression-syntax* 825 826Expression syntax summary, from least to most significant: 827 828|expr1| expr2 829 expr2 ? expr1 : expr1 if-then-else 830 831|expr2| expr3 832 expr3 || expr3 ... logical OR 833 834|expr3| expr4 835 expr4 && expr4 ... logical AND 836 837|expr4| expr5 838 expr5 == expr5 equal 839 expr5 != expr5 not equal 840 expr5 > expr5 greater than 841 expr5 >= expr5 greater than or equal 842 expr5 < expr5 smaller than 843 expr5 <= expr5 smaller than or equal 844 expr5 =~ expr5 regexp matches 845 expr5 !~ expr5 regexp doesn't match 846 847 expr5 ==? expr5 equal, ignoring case 848 expr5 ==# expr5 equal, match case 849 etc. As above, append ? for ignoring case, # for 850 matching case 851 852 expr5 is expr5 same |List|, |Dictionary| or |Blob| instance 853 expr5 isnot expr5 different |List|, |Dictionary| or |Blob| 854 instance 855 856|expr5| expr6 857 expr6 + expr6 ... number addition, list or blob concatenation 858 expr6 - expr6 ... number subtraction 859 expr6 . expr6 ... string concatenation 860 expr6 .. expr6 ... string concatenation 861 862|expr6| expr7 863 expr7 * expr7 ... number multiplication 864 expr7 / expr7 ... number division 865 expr7 % expr7 ... number modulo 866 867|expr7| expr8 868 ! expr7 logical NOT 869 - expr7 unary minus 870 + expr7 unary plus 871 872|expr8| expr9 873 expr8[expr1] byte of a String or item of a |List| 874 expr8[expr1 : expr1] substring of a String or sublist of a |List| 875 expr8.name entry in a |Dictionary| 876 expr8(expr1, ...) function call with |Funcref| variable 877 expr8->name(expr1, ...) |method| call 878 879|expr9| number number constant 880 "string" string constant, backslash is special 881 `'string'` string constant, ' is doubled 882 [expr1, ...] |List| 883 `{expr1: expr1, ...}` |Dictionary| 884 #{key: expr1, ...} |Dictionary| 885 &option option value 886 (expr1) nested expression 887 variable internal variable 888 va{ria}ble internal variable with curly braces 889 $VAR environment variable 890 @r contents of register "r" 891 function(expr1, ...) function call 892 func{ti}on(expr1, ...) function call with curly braces 893 `{args -> expr1}` lambda expression 894 895 896"..." indicates that the operations in this level can be concatenated. 897Example: > 898 &nu || &list && &shell == "csh" 899 900All expressions within one level are parsed from left to right. 901 902Expression nesting is limited to 1000 levels deep (300 when build with MSVC) 903to avoid running out of stack and crashing. *E1169* 904 905 906------------------------------------------------------------------------------ 907expr1 *expr1* *ternary* *falsy-operator* *??* *E109* 908 909The ternary operator: expr2 ? expr1 : expr1 910The falsy operator: expr2 ?? expr1 911 912Ternary operator ~ 913 914The expression before the '?' is evaluated to a number. If it evaluates to 915|TRUE|, the result is the value of the expression between the '?' and ':', 916otherwise the result is the value of the expression after the ':'. 917Example: > 918 :echo lnum == 1 ? "top" : lnum 919 920Since the first expression is an "expr2", it cannot contain another ?:. The 921other two expressions can, thus allow for recursive use of ?:. 922Example: > 923 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum 924 925To keep this readable, using |line-continuation| is suggested: > 926 :echo lnum == 1 927 :\ ? "top" 928 :\ : lnum == 1000 929 :\ ? "last" 930 :\ : lnum 931 932You should always put a space before the ':', otherwise it can be mistaken for 933use in a variable such as "a:1". 934 935Falsy operator ~ 936 937This is also known as the "null coalescing operator", but that's too 938complicated, thus we just call it the falsy operator. 939 940The expression before the '??' is evaluated. If it evaluates to 941|truthy|, this is used as the result. Otherwise the expression after the '??' 942is evaluated and used as the result. This is most useful to have a default 943value for an expression that may result in zero or empty: > 944 echo theList ?? 'list is empty' 945 echo GetName() ?? 'unknown' 946 947These are similar, but not equal: > 948 expr2 ?? expr1 949 expr2 ? expr2 : expr1 950In the second line "expr2" is evaluated twice. 951 952 953------------------------------------------------------------------------------ 954expr2 and expr3 *expr2* *expr3* 955 956expr3 || expr3 .. logical OR *expr-barbar* 957expr4 && expr4 .. logical AND *expr-&&* 958 959The "||" and "&&" operators take one argument on each side. The arguments 960are (converted to) Numbers. The result is: 961 962 input output ~ 963n1 n2 n1 || n2 n1 && n2 ~ 964|FALSE| |FALSE| |FALSE| |FALSE| 965|FALSE| |TRUE| |TRUE| |FALSE| 966|TRUE| |FALSE| |TRUE| |FALSE| 967|TRUE| |TRUE| |TRUE| |TRUE| 968 969The operators can be concatenated, for example: > 970 971 &nu || &list && &shell == "csh" 972 973Note that "&&" takes precedence over "||", so this has the meaning of: > 974 975 &nu || (&list && &shell == "csh") 976 977Once the result is known, the expression "short-circuits", that is, further 978arguments are not evaluated. This is like what happens in C. For example: > 979 980 let a = 1 981 echo a || b 982 983This is valid even if there is no variable called "b" because "a" is |TRUE|, 984so the result must be |TRUE|. Similarly below: > 985 986 echo exists("b") && b == "yes" 987 988This is valid whether "b" has been defined or not. The second clause will 989only be evaluated if "b" has been defined. 990 991 992------------------------------------------------------------------------------ 993expr4 *expr4* 994 995expr5 {cmp} expr5 996 997Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1 998if it evaluates to true. 999 1000 *expr-==* *expr-!=* *expr->* *expr->=* 1001 *expr-<* *expr-<=* *expr-=~* *expr-!~* 1002 *expr-==#* *expr-!=#* *expr->#* *expr->=#* 1003 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#* 1004 *expr-==?* *expr-!=?* *expr->?* *expr->=?* 1005 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?* 1006 *expr-is* *expr-isnot* *expr-is#* *expr-isnot#* 1007 *expr-is?* *expr-isnot?* 1008 use 'ignorecase' match case ignore case ~ 1009equal == ==# ==? 1010not equal != !=# !=? 1011greater than > ># >? 1012greater than or equal >= >=# >=? 1013smaller than < <# <? 1014smaller than or equal <= <=# <=? 1015regexp matches =~ =~# =~? 1016regexp doesn't match !~ !~# !~? 1017same instance is is# is? 1018different instance isnot isnot# isnot? 1019 1020Examples: 1021"abc" ==# "Abc" evaluates to 0 1022"abc" ==? "Abc" evaluates to 1 1023"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise 1024 1025 *E691* *E692* 1026A |List| can only be compared with a |List| and only "equal", "not equal", 1027"is" and "isnot" can be used. This compares the values of the list, 1028recursively. Ignoring case means case is ignored when comparing item values. 1029 1030 *E735* *E736* 1031A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not 1032equal", "is" and "isnot" can be used. This compares the key/values of the 1033|Dictionary| recursively. Ignoring case means case is ignored when comparing 1034item values. 1035 1036 *E694* 1037A |Funcref| can only be compared with a |Funcref| and only "equal", "not 1038equal", "is" and "isnot" can be used. Case is never ignored. Whether 1039arguments or a Dictionary are bound (with a partial) matters. The 1040Dictionaries must also be equal (or the same, in case of "is") and the 1041arguments must be equal (or the same). 1042 1043To compare Funcrefs to see if they refer to the same function, ignoring bound 1044Dictionary and arguments, use |get()| to get the function name: > 1045 if get(Part1, 'name') == get(Part2, 'name') 1046 " Part1 and Part2 refer to the same function 1047 1048Using "is" or "isnot" with a |List|, |Dictionary| or |Blob| checks whether 1049the expressions are referring to the same |List|, |Dictionary| or |Blob| 1050instance. A copy of a |List| is different from the original |List|. When 1051using "is" without a |List|, |Dictionary| or |Blob|, it is equivalent to 1052using "equal", using "isnot" is equivalent to using "not equal". Except that 1053a different type means the values are different: > 1054 echo 4 == '4' 1055 1 1056 echo 4 is '4' 1057 0 1058 echo 0 is [] 1059 0 1060"is#"/"isnot#" and "is?"/"isnot?" can be used to match and ignore case. 1061 1062When comparing a String with a Number, the String is converted to a Number, 1063and the comparison is done on Numbers. This means that: > 1064 echo 0 == 'x' 1065 1 1066because 'x' converted to a Number is zero. However: > 1067 echo [0] == ['x'] 1068 0 1069Inside a List or Dictionary this conversion is not used. 1070 1071When comparing two Strings, this is done with strcmp() or stricmp(). This 1072results in the mathematical difference (comparing byte values), not 1073necessarily the alphabetical difference in the local language. 1074 1075When using the operators with a trailing '#', or the short version and 1076'ignorecase' is off, the comparing is done with strcmp(): case matters. 1077 1078When using the operators with a trailing '?', or the short version and 1079'ignorecase' is set, the comparing is done with stricmp(): case is ignored. 1080 1081'smartcase' is not used. 1082 1083The "=~" and "!~" operators match the lefthand argument with the righthand 1084argument, which is used as a pattern. See |pattern| for what a pattern is. 1085This matching is always done like 'magic' was set and 'cpoptions' is empty, no 1086matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts 1087portable. To avoid backslashes in the regexp pattern to be doubled, use a 1088single-quote string, see |literal-string|. 1089Since a string is considered to be a single line, a multi-line pattern 1090(containing \n, backslash-n) will not match. However, a literal NL character 1091can be matched like an ordinary character. Examples: 1092 "foo\nbar" =~ "\n" evaluates to 1 1093 "foo\nbar" =~ "\\n" evaluates to 0 1094 1095 1096------------------------------------------------------------------------------ 1097expr5 and expr6 *expr5* *expr6* 1098 1099expr6 + expr6 Number addition, |List| or |Blob| concatenation *expr-+* 1100expr6 - expr6 Number subtraction *expr--* 1101expr6 . expr6 String concatenation *expr-.* 1102expr6 .. expr6 String concatenation *expr-..* 1103 1104For |Lists| only "+" is possible and then both expr6 must be a list. The 1105result is a new list with the two lists Concatenated. 1106 1107For String concatenation ".." is preferred, since "." is ambiguous, it is also 1108used for |Dict| member access and floating point numbers. 1109 1110expr7 * expr7 Number multiplication *expr-star* 1111expr7 / expr7 Number division *expr-/* 1112expr7 % expr7 Number modulo *expr-%* 1113 1114For all, except "." and "..", Strings are converted to Numbers. 1115For bitwise operators see |and()|, |or()| and |xor()|. 1116 1117Note the difference between "+" and ".": 1118 "123" + "456" = 579 1119 "123" . "456" = "123456" 1120 1121Since '.' has the same precedence as '+' and '-', you need to read: > 1122 1 . 90 + 90.0 1123As: > 1124 (1 . 90) + 90.0 1125That works, since the String "190" is automatically converted to the Number 1126190, which can be added to the Float 90.0. However: > 1127 1 . 90 * 90.0 1128Should be read as: > 1129 1 . (90 * 90.0) 1130Since '.' has lower precedence than "*". This does NOT work, since this 1131attempts to concatenate a Float and a String. 1132 1133When dividing a Number by zero the result depends on the value: 1134 0 / 0 = -0x80000000 (like NaN for Float) 1135 >0 / 0 = 0x7fffffff (like positive infinity) 1136 <0 / 0 = -0x7fffffff (like negative infinity) 1137 (before Vim 7.2 it was always 0x7fffffff) 1138 1139When 64-bit Number support is enabled: 1140 0 / 0 = -0x8000000000000000 (like NaN for Float) 1141 >0 / 0 = 0x7fffffffffffffff (like positive infinity) 1142 <0 / 0 = -0x7fffffffffffffff (like negative infinity) 1143 1144When the righthand side of '%' is zero, the result is 0. 1145 1146None of these work for |Funcref|s. 1147 1148. and % do not work for Float. *E804* 1149 1150 1151------------------------------------------------------------------------------ 1152expr7 *expr7* 1153 1154! expr7 logical NOT *expr-!* 1155- expr7 unary minus *expr-unary--* 1156+ expr7 unary plus *expr-unary-+* 1157 1158For '!' |TRUE| becomes |FALSE|, |FALSE| becomes |TRUE| (one). 1159For '-' the sign of the number is changed. 1160For '+' the number is unchanged. Note: "++" has no effect. 1161 1162A String will be converted to a Number first. 1163 1164These three can be repeated and mixed. Examples: 1165 !-1 == 0 1166 !!8 == 1 1167 --9 == 9 1168 1169 1170------------------------------------------------------------------------------ 1171expr8 *expr8* 1172 1173This expression is either |expr9| or a sequence of the alternatives below, 1174in any order. E.g., these are all possible: 1175 expr8[expr1].name 1176 expr8.name[expr1] 1177 expr8(expr1, ...)[expr1].name 1178 expr8->(expr1, ...)[expr1] 1179Evaluation is always from left to right. 1180 1181 1182expr8[expr1] item of String or |List| *expr-[]* *E111* 1183 *subscript* 1184In legacy Vim script: 1185If expr8 is a Number or String this results in a String that contains the 1186expr1'th single byte from expr8. expr8 is used as a String (a number is 1187automatically converted to a String), expr1 as a Number. This doesn't 1188recognize multibyte encodings, see `byteidx()` for an alternative, or use 1189`split()` to turn the string into a list of characters. Example, to get the 1190byte under the cursor: > 1191 :let c = getline(".")[col(".") - 1] 1192 1193Index zero gives the first byte. This is like it works in C. Careful: 1194text column numbers start with one! Example, to get the byte under the 1195cursor: > 1196 :let c = getline(".")[col(".") - 1] 1197 1198Index zero gives the first byte. Careful: text column numbers start with one! 1199 1200If the length of the String is less than the index, the result is an empty 1201String. A negative index always results in an empty string (reason: backward 1202compatibility). Use [-1:] to get the last byte. 1203 1204If expr8 is a |List| then it results the item at index expr1. See |list-index| 1205for possible index values. If the index is out of range this results in an 1206error. Example: > 1207 :let item = mylist[-1] " get last item 1208 1209Generally, if a |List| index is equal to or higher than the length of the 1210|List|, or more negative than the length of the |List|, this results in an 1211error. 1212 1213 1214expr8[expr1a : expr1b] substring or |sublist| *expr-[:]* *substring* 1215 1216If expr8 is a String this results in the substring with the bytes or 1217characters from expr1a to and including expr1b. expr8 is used as a String, 1218expr1a and expr1b are used as a Number. 1219 1220In legacy Vim script the indexes are byte indexes. This doesn't recognize 1221multibyte encodings, see |byteidx()| for computing the indexes. If expr8 is 1222a Number it is first converted to a String. 1223 1224The item at index expr1b is included, it is inclusive. For an exclusive index 1225use the |slice()| function. 1226 1227If expr1a is omitted zero is used. If expr1b is omitted the length of the 1228string minus one is used. 1229 1230A negative number can be used to measure from the end of the string. -1 is 1231the last character, -2 the last but one, etc. 1232 1233If an index goes out of range for the string characters are omitted. If 1234expr1b is smaller than expr1a the result is an empty string. 1235 1236Examples: > 1237 :let c = name[-1:] " last byte of a string 1238 :let c = name[0:-1] " the whole string 1239 :let c = name[-2:-2] " last but one byte of a string 1240 :let s = line(".")[4:] " from the fifth byte to the end 1241 :let s = s[:-3] " remove last two bytes 1242< 1243 *slice* 1244If expr8 is a |List| this results in a new |List| with the items indicated by 1245the indexes expr1a and expr1b. This works like with a String, as explained 1246just above. Also see |sublist| below. Examples: > 1247 :let l = mylist[:3] " first four items 1248 :let l = mylist[4:4] " List with one item 1249 :let l = mylist[:] " shallow copy of a List 1250 1251If expr8 is a |Blob| this results in a new |Blob| with the bytes in the 1252indexes expr1a and expr1b, inclusive. Examples: > 1253 :let b = 0zDEADBEEF 1254 :let bs = b[1:2] " 0zADBE 1255 :let bs = b[] " copy of 0zDEADBEEF 1256 1257Using expr8[expr1] or expr8[expr1a : expr1b] on a |Funcref| results in an 1258error. 1259 1260Watch out for confusion between a namespace and a variable followed by a colon 1261for a sublist: > 1262 mylist[n:] " uses variable n 1263 mylist[s:] " uses namespace s:, error! 1264 1265 1266expr8.name entry in a |Dictionary| *expr-entry* 1267 1268If expr8 is a |Dictionary| and it is followed by a dot, then the following 1269name will be used as a key in the |Dictionary|. This is just like: 1270expr8[name]. 1271 1272The name must consist of alphanumeric characters, just like a variable name, 1273but it may start with a number. Curly braces cannot be used. 1274 1275There must not be white space before or after the dot. 1276 1277Examples: > 1278 :let dict = {"one": 1, 2: "two"} 1279 :echo dict.one " shows "1" 1280 :echo dict.2 " shows "two" 1281 :echo dict .2 " error because of space before the dot 1282 1283Note that the dot is also used for String concatenation. To avoid confusion 1284always put spaces around the dot for String concatenation. 1285 1286 1287expr8(expr1, ...) |Funcref| function call *E1085* 1288 1289When expr8 is a |Funcref| type variable, invoke the function it refers to. 1290 1291 1292expr8->name([args]) method call *method* *->* 1293expr8->{lambda}([args]) 1294 1295 *E260* *E276* 1296For methods that are also available as global functions this is the same as: > 1297 name(expr8 [, args]) 1298There can also be methods specifically for the type of "expr8". 1299 1300This allows for chaining, passing the value that one method returns to the 1301next method: > 1302 mylist->filter(filterexpr)->map(mapexpr)->sort()->join() 1303< 1304Example of using a lambda: > 1305 GetPercentage()->{x -> x * 100}()->printf('%d%%') 1306< 1307When using -> the |expr7| operators will be applied first, thus: > 1308 -1.234->string() 1309Is equivalent to: > 1310 (-1.234)->string() 1311And NOT: > 1312 -(1.234->string()) 1313< 1314 *E274* 1315"->name(" must not contain white space. There can be white space before the 1316"->" and after the "(", thus you can split the lines like this: > 1317 mylist 1318 \ ->filter(filterexpr) 1319 \ ->map(mapexpr) 1320 \ ->sort() 1321 \ ->join() 1322 1323When using the lambda form there must be no white space between the } and the 1324(. 1325 1326 1327 *expr9* 1328------------------------------------------------------------------------------ 1329number 1330 1331number number constant *expr-number* 1332 1333 *0x* *hex-number* *0o* *octal-number* *0b* *binary-number* 1334Integer numbers can be written in multiple forms: 1335 1336 {N} decimal 1337 0x{N} or 0X{N} hexadecimal 1338 0o{N} or 0O{N} octal 1339 0{N} octal 1340 0b{N} or 0B{N} binary 1341 1342{N} is a sequence of decimal digits (0-9), hexadecimal digits (0-9, a-f and 1343A-F), octal digits (0-7) or binary digits (0 or 1). 1344 1345A leading "+" or "-" is not part of an integer literal. E.g., -123 is an 1346expression, the unary operator |expr-unary--| applied to the number 123. 1347 1348Examples: 1349 0xDEAD 1350 57005 1351 0b1101111010101101 1352 0o157255 1353 1354 *floating-point-format* 1355Floating point numbers can be written in two forms: 1356 1357 {N}.{M} 1358 {N}.{M}[eE][-+]{exp} 1359 1360{N} and {M} are sequences of decimal digits Both {N} and {M} must be present. 1361{exp} is the exponent, power of 10. 1362Only a decimal point is accepted, not a comma. No matter what the current 1363locale is. 1364 1365A leading "+" or "-" is not part of a floating point literal. E.g., -1.0e-3 1366is an expression, the unary operator |expr-unary--| applied to the float 1.0e-3. 1367The "-" in the exponent is part of the literal. 1368 1369Examples: 1370 123.456 1371 0.0001 1372 55.0 1373 0.123 1374 1.234e03 1375 1.0E-6 1376 3.1416e+88 1377 1378These are INVALID: 1379 3. empty {M} 1380 1e40 missing .{M} 1381 1382Rationale: 1383Before floating point was introduced, the text "123.456" was interpreted as 1384the two numbers "123" and "456", both converted to a string and concatenated, 1385resulting in the string "123456". Since this was considered pointless, and we 1386could not find it intentionally being used in Vim scripts, this backwards 1387incompatibility was accepted in favor of being able to use the normal notation 1388for floating point numbers. 1389 1390 *float-pi* *float-e* 1391A few useful values to copy&paste: > 1392 :let pi = 3.14159265359 1393 :let e = 2.71828182846 1394Or, if you don't want to write them in as floating-point literals, you can 1395also use functions, like the following: > 1396 :let pi = acos(-1.0) 1397 :let e = exp(1.0) 1398< 1399 *floating-point-precision* 1400The precision and range of floating points numbers depends on what "double" 1401means in the library Vim was compiled with. There is no way to change this at 1402runtime. 1403 1404The default for displaying a |Float| is to use 6 decimal places, like using 1405printf("%g", f). You can select something else when using the |printf()| 1406function. Example: > 1407 :echo printf('%.15e', atan(1)) 1408< 7.853981633974483e-01 1409 1410 1411------------------------------------------------------------------------------ 1412string *string* *String* *expr-string* *E114* 1413 1414"string" string constant *expr-quote* 1415 1416Note that double quotes are used. 1417 1418A string constant accepts these special characters: 1419\... three-digit octal number (e.g., "\316") 1420\.. two-digit octal number (must be followed by non-digit) 1421\. one-digit octal number (must be followed by non-digit) 1422\x.. byte specified with two hex numbers (e.g., "\x1f") 1423\x. byte specified with one hex number (must be followed by non-hex char) 1424\X.. same as \x.. 1425\X. same as \x. 1426\u.... character specified with up to 4 hex numbers, stored as UTF-8 1427 (e.g., "\u02a4") 1428\U.... same as \u but allows up to 8 hex numbers. 1429\b backspace <BS> 1430\e escape <Esc> 1431\f formfeed 0x0C 1432\n newline <NL> 1433\r return <CR> 1434\t tab <Tab> 1435\\ backslash 1436\" double quote 1437\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W. This is for use 1438 in mappings, the 0x80 byte is escaped. 1439 To use the double quote character it must be escaped: "<M-\">". 1440 Don't use <Char-xxxx> to get a UTF-8 character, use \uxxxx as 1441 mentioned above. 1442\<*xxx> Like \<xxx> but prepends a modifier instead of including it in the 1443 character. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is 1444 four bytes: 3 for the CTRL modifier and then character "W". 1445 1446Note that "\xff" is stored as the byte 255, which may be invalid in some 1447encodings. Use "\u00ff" to store character 255 correctly as UTF-8. 1448 1449Note that "\000" and "\x00" force the end of the string. 1450 1451 1452------------------------------------------------------------------------------ 1453blob-literal *blob-literal* *E973* 1454 1455Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes. 1456The sequence must be an even number of hex characters. Example: > 1457 :let b = 0zFF00ED015DAF 1458 1459 1460------------------------------------------------------------------------------ 1461literal-string *literal-string* *E115* 1462 1463`'string'` string constant *expr-'* 1464 1465Note that single quotes are used. 1466 1467This string is taken as it is. No backslashes are removed or have a special 1468meaning. The only exception is that two quotes stand for one quote. 1469 1470Single quoted strings are useful for patterns, so that backslashes do not need 1471to be doubled. These two commands are equivalent: > 1472 if a =~ "\\s*" 1473 if a =~ '\s*' 1474 1475 1476------------------------------------------------------------------------------ 1477interpolated-string *$quote* *interpolated-string* 1478 1479$"string" interpolated string constant *expr-$quote* 1480$'string' interpolated literal string constant *expr-$'* 1481 1482Interpolated strings are an extension of the |string| and |literal-string|, 1483allowing the inclusion of Vim script expressions (see |expr1|). Any 1484expression returning a value can be enclosed between curly braces. The value 1485is converted to a string. All the text and results of the expressions 1486are concatenated to make a new string. 1487 *E1278* *E1279* 1488To include an opening brace '{' or closing brace '}' in the string content 1489double it. For double quoted strings using a backslash also works. A single 1490closing brace '}' will result in an error. 1491 1492Examples: > 1493 let your_name = input("What's your name? ") 1494< What's your name? Peter ~ 1495> 1496 echo 1497 echo $"Hello, {your_name}!" 1498< Hello, Peter! ~ 1499> 1500 echo $"The square root of {{9}} is {sqrt(9)}" 1501< The square root of {9} is 3.0 ~ 1502 1503 *string-offset-encoding* 1504A string consists of multiple characters. UTF-8 uses one byte for ASCII 1505characters, two bytes for other latin characters and more bytes for other 1506characters. 1507 1508A string offset can count characters or bytes. Other programs may use 1509UTF-16 encoding (16-bit words) and an offset of UTF-16 words. Some functions 1510use byte offsets, usually for UTF-8 encoding. Other functions use character 1511offsets, in which case the encoding doesn't matter. 1512 1513The different offsets for the string "a©😊" are below: 1514 1515 UTF-8 offsets: 1516 [0]: 61, [1]: C2, [2]: A9, [3]: F0, [4]: 9F, [5]: 98, [6]: 8A 1517 UTF-16 offsets: 1518 [0]: 0061, [1]: 00A9, [2]: D83D, [3]: DE0A 1519 UTF-32 (character) offsets: 1520 [0]: 00000061, [1]: 000000A9, [2]: 0001F60A 1521 1522You can use the "g8" and "ga" commands on a character to see the 1523decimal/hex/octal values. 1524 1525The functions |byteidx()|, |utf16idx()| and |charidx()| can be used to convert 1526between these indices. The functions |strlen()|, |strutf16len()| and 1527|strcharlen()| return the number of bytes, UTF-16 code units and characters in 1528a string respectively. 1529 1530------------------------------------------------------------------------------ 1531option *expr-option* *E112* *E113* 1532 1533&option option value, local value if possible 1534&g:option global option value 1535&l:option local option value 1536 1537Examples: > 1538 echo "tabstop is " .. &tabstop 1539 if &expandtab 1540 1541Any option name can be used here. See |options|. When using the local value 1542and there is no buffer-local or window-local value, the global value is used 1543anyway. 1544 1545 1546------------------------------------------------------------------------------ 1547register *expr-register* *@r* 1548 1549@r contents of register 'r' 1550 1551The result is the contents of the named register, as a single string. 1552Newlines are inserted where required. To get the contents of the unnamed 1553register use @" or @@. See |registers| for an explanation of the available 1554registers. 1555 1556When using the '=' register you get the expression itself, not what it 1557evaluates to. Use |eval()| to evaluate it. 1558 1559 1560nesting *expr-nesting* *E110* 1561------- 1562(expr1) nested expression 1563 1564 1565------------------------------------------------------------------------------ 1566environment variable *expr-env* 1567 1568$VAR environment variable 1569 1570The String value of any environment variable. When it is not defined, the 1571result is an empty string. 1572 1573The functions `getenv()` and `setenv()` can also be used and work for 1574environment variables with non-alphanumeric names. 1575The function `environ()` can be used to get a Dict with all environment 1576variables. 1577 1578 1579 *expr-env-expand* 1580Note that there is a difference between using $VAR directly and using 1581expand("$VAR"). Using it directly will only expand environment variables that 1582are known inside the current Vim session. Using expand() will first try using 1583the environment variables known inside the current Vim session. If that 1584fails, a shell will be used to expand the variable. This can be slow, but it 1585does expand all variables that the shell knows about. Example: > 1586 :echo $shell 1587 :echo expand("$shell") 1588The first one probably doesn't echo anything, the second echoes the $shell 1589variable (if your shell supports it). 1590 1591 1592------------------------------------------------------------------------------ 1593internal variable *expr-variable* 1594 1595variable internal variable 1596See below |internal-variables|. 1597 1598 1599------------------------------------------------------------------------------ 1600function call *expr-function* *E116* *E118* *E119* *E120* 1601 1602function(expr1, ...) function call 1603See below |functions|. 1604 1605 1606------------------------------------------------------------------------------ 1607lambda expression *expr-lambda* *lambda* 1608 1609`{args -> expr1}` lambda expression *E451* 1610 1611A lambda expression creates a new unnamed function which returns the result of 1612evaluating |expr1|. Lambda expressions differ from |user-function|s in 1613the following ways: 1614 16151. The body of the lambda expression is an |expr1| and not a sequence of |Ex| 1616 commands. 16172. The prefix "a:" should not be used for arguments. E.g.: > 1618 :let F = {arg1, arg2 -> arg1 - arg2} 1619 :echo F(5, 2) 1620< 3 1621 1622The arguments are optional. Example: > 1623 :let F = {-> 'error function'} 1624 :echo F('ignored') 1625< error function 1626 *closure* 1627Lambda expressions can access outer scope variables and arguments. This is 1628often called a closure. Example where "i" and "a:arg" are used in a lambda 1629while they already exist in the function scope. They remain valid even after 1630the function returns: > 1631 :function Foo(arg) 1632 : let i = 3 1633 : return {x -> x + i - a:arg} 1634 :endfunction 1635 :let Bar = Foo(4) 1636 :echo Bar(6) 1637< 5 1638Note that the variables must exist in the outer scope before the lambda is 1639defined for this to work. See also |:func-closure|. 1640 1641Lambda and closure support can be checked with: > 1642 if has('lambda') 1643 1644Examples for using a lambda expression with |sort()|, |map()| and |filter()|: > 1645 :echo map([1, 2, 3], {idx, val -> val + 1}) 1646< [2, 3, 4] > 1647 :echo sort([3,7,2,1,4], {a, b -> a - b}) 1648< [1, 2, 3, 4, 7] 1649 1650The lambda expression is also useful for jobs and timers: > 1651 :let timer = timer_start(500, 1652 \ {-> execute("echo 'Handler called'", "")}, 1653 \ {'repeat': 3}) 1654< Handler called 1655 Handler called 1656 Handler called 1657 1658Note that it is possible to cause memory to be used and not freed if the 1659closure is referenced by the context it depends on: > 1660 function Function() 1661 let x = 0 1662 let F = {-> x} 1663 endfunction 1664The closure uses "x" from the function scope, and "F" in that same scope 1665refers to the closure. This cycle results in the memory not being freed. 1666Recommendation: don't do this. 1667 1668Notice how execute() is used to execute an Ex command. That's ugly though. 1669 1670 1671Lambda expressions have internal names like '<lambda>42'. If you get an error 1672for a lambda expression, you can find what it is with the following command: > 1673 :function <lambda>42 1674See also: |numbered-function| 1675 1676============================================================================== 16773. Internal variable *internal-variables* *E461* 1678 1679An internal variable name can be made up of letters, digits and '_'. But it 1680cannot start with a digit. It's also possible to use curly braces, see 1681|curly-braces-names|. 1682 1683An internal variable is created with the ":let" command |:let|. 1684An internal variable is explicitly destroyed with the ":unlet" command 1685|:unlet|. 1686Using a name that is not an internal variable or refers to a variable that has 1687been destroyed results in an error. 1688 1689 *variable-scope* 1690There are several name spaces for variables. Which one is to be used is 1691specified by what is prepended: 1692 1693 (nothing) In a function: local to a function; otherwise: global 1694|buffer-variable| b: Local to the current buffer. 1695|window-variable| w: Local to the current window. 1696|tabpage-variable| t: Local to the current tab page. 1697|global-variable| g: Global. 1698|local-variable| l: Local to a function. 1699|script-variable| s: Local to a |:source|d Vim script. 1700|function-argument| a: Function argument (only inside a function). 1701|vim-variable| v: Global, predefined by Vim. 1702 1703The scope name by itself can be used as a |Dictionary|. For example, to 1704delete all script-local variables: > 1705 :for k in keys(s:) 1706 : unlet s:[k] 1707 :endfor 1708< 1709 *buffer-variable* *b:var* *b:* 1710A variable name that is preceded with "b:" is local to the current buffer. 1711Thus you can have several "b:foo" variables, one for each buffer. 1712This kind of variable is deleted when the buffer is wiped out or deleted with 1713|:bdelete|. 1714 1715One local buffer variable is predefined: 1716 *b:changedtick* *changetick* 1717b:changedtick The total number of changes to the current buffer. It is 1718 incremented for each change. An undo command is also a change 1719 in this case. Resetting 'modified' when writing the buffer is 1720 also counted. 1721 This can be used to perform an action only when the buffer has 1722 changed. Example: > 1723 :if my_changedtick != b:changedtick 1724 : let my_changedtick = b:changedtick 1725 : call My_Update() 1726 :endif 1727< You cannot change or delete the b:changedtick variable. 1728 1729 *window-variable* *w:var* *w:* 1730A variable name that is preceded with "w:" is local to the current window. It 1731is deleted when the window is closed. 1732 1733 *tabpage-variable* *t:var* *t:* 1734A variable name that is preceded with "t:" is local to the current tab page, 1735It is deleted when the tab page is closed. 1736 1737 *global-variable* *g:var* *g:* 1738Inside functions global variables are accessed with "g:". Omitting this will 1739access a variable local to a function. But "g:" can also be used in any other 1740place if you like. 1741 1742 *local-variable* *l:var* *l:* 1743Inside functions local variables are accessed without prepending anything. 1744But you can also prepend "l:" if you like. However, without prepending "l:" 1745you may run into reserved variable names. For example "count". By itself it 1746refers to "v:count". Using "l:count" you can have a local variable with the 1747same name. 1748 1749 *script-variable* *s:var* 1750In a Vim script variables starting with "s:" can be used. They cannot be 1751accessed from outside of the scripts, thus are local to the script. 1752 1753They can be used in: 1754- commands executed while the script is sourced 1755- functions defined in the script 1756- autocommands defined in the script 1757- functions and autocommands defined in functions and autocommands which were 1758 defined in the script (recursively) 1759- user defined commands defined in the script 1760Thus not in: 1761- other scripts sourced from this one 1762- mappings 1763- menus 1764- etc. 1765 1766Script variables can be used to avoid conflicts with global variable names. 1767Take this example: > 1768 1769 let s:counter = 0 1770 function MyCounter() 1771 let s:counter = s:counter + 1 1772 echo s:counter 1773 endfunction 1774 command Tick call MyCounter() 1775 1776You can now invoke "Tick" from any script, and the "s:counter" variable in 1777that script will not be changed, only the "s:counter" in the script where 1778"Tick" was defined is used. 1779 1780Another example that does the same: > 1781 1782 let s:counter = 0 1783 command Tick let s:counter = s:counter + 1 | echo s:counter 1784 1785When calling a function and invoking a user-defined command, the context for 1786script variables is set to the script where the function or command was 1787defined. 1788 1789The script variables are also available when a function is defined inside a 1790function that is defined in a script. Example: > 1791 1792 let s:counter = 0 1793 function StartCounting(incr) 1794 if a:incr 1795 function MyCounter() 1796 let s:counter = s:counter + 1 1797 endfunction 1798 else 1799 function MyCounter() 1800 let s:counter = s:counter - 1 1801 endfunction 1802 endif 1803 endfunction 1804 1805This defines the MyCounter() function either for counting up or counting down 1806when calling StartCounting(). It doesn't matter from where StartCounting() is 1807called, the s:counter variable will be accessible in MyCounter(). 1808 1809When the same script is sourced again it will use the same script variables. 1810They will remain valid as long as Vim is running. This can be used to 1811maintain a counter: > 1812 1813 if !exists("s:counter") 1814 let s:counter = 1 1815 echo "script executed for the first time" 1816 else 1817 let s:counter = s:counter + 1 1818 echo "script executed " .. s:counter .. " times now" 1819 endif 1820 1821Note that this means that filetype plugins don't get a different set of script 1822variables for each buffer. Use local buffer variables instead |b:var|. 1823 1824 1825PREDEFINED VIM VARIABLES *vim-variable* 1826 *E963* 1827 1828The alphabetic list of all builtin variables and details are in a separate 1829help file: |vvars|. 1830 1831============================================================================== 18324. Builtin Functions *vim-function* *functions* 1833 1834The Vimscript subsystem (referred to as "eval" internally) provides builtin 1835functions. Scripts can also define |user-function|s. 1836 1837See |function-list| to browse functions by topic. 1838 1839The alphabetic list of all builtin functions and details are in a separate 1840help file: |vimscript-functions|. 1841 1842============================================================================== 18435. Defining functions *user-function* 1844 1845New functions can be defined. These can be called just like builtin 1846functions. The function takes arguments, executes a sequence of Ex commands 1847and can return a value. 1848 1849You can find most information about defining functions in |userfunc.txt|. 1850 1851============================================================================== 18526. Curly braces names *curly-braces-names* 1853 1854In most places where you can use a variable, you can use a "curly braces name" 1855variable. This is a regular variable name with one or more expressions 1856wrapped in braces {} like this: > 1857 my_{adjective}_variable 1858 1859When Vim encounters this, it evaluates the expression inside the braces, puts 1860that in place of the expression, and re-interprets the whole as a variable 1861name. So in the above example, if the variable "adjective" was set to 1862"noisy", then the reference would be to "my_noisy_variable", whereas if 1863"adjective" was set to "quiet", then it would be to "my_quiet_variable". 1864 1865One application for this is to create a set of variables governed by an option 1866value. For example, the statement > 1867 echo my_{&background}_message 1868 1869would output the contents of "my_dark_message" or "my_light_message" depending 1870on the current value of 'background'. 1871 1872You can use multiple brace pairs: > 1873 echo my_{adverb}_{adjective}_message 1874..or even nest them: > 1875 echo my_{ad{end_of_word}}_message 1876where "end_of_word" is either "verb" or "jective". 1877 1878However, the expression inside the braces must evaluate to a valid single 1879variable name, e.g. this is invalid: > 1880 :let foo='a + b' 1881 :echo c{foo}d 1882.. since the result of expansion is "ca + bd", which is not a variable name. 1883 1884 *curly-braces-function-names* 1885You can call and define functions by an evaluated name in a similar way. 1886Example: > 1887 :let func_end='whizz' 1888 :call my_func_{func_end}(parameter) 1889 1890This would call the function "my_func_whizz(parameter)". 1891 1892This does NOT work: > 1893 :let i = 3 1894 :let @{i} = '' " error 1895 :echo @{i} " error 1896 1897============================================================================== 18987. Commands *expression-commands* 1899 1900:let {var-name} = {expr1} *:let* *E18* 1901 Set internal variable {var-name} to the result of the 1902 expression {expr1}. The variable will get the type 1903 from the {expr}. If {var-name} didn't exist yet, it 1904 is created. 1905 1906:let {var-name}[{idx}] = {expr1} *E689* 1907 Set a list item to the result of the expression 1908 {expr1}. {var-name} must refer to a list and {idx} 1909 must be a valid index in that list. For nested list 1910 the index can be repeated. 1911 This cannot be used to add an item to a |List|. 1912 This cannot be used to set a byte in a String. You 1913 can do that like this: > 1914 :let var = var[0:2] .. 'X' .. var[4:] 1915< When {var-name} is a |Blob| then {idx} can be the 1916 length of the blob, in which case one byte is 1917 appended. 1918 1919 *E711* *E719* 1920:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710* 1921 Set a sequence of items in a |List| to the result of 1922 the expression {expr1}, which must be a list with the 1923 correct number of items. 1924 {idx1} can be omitted, zero is used instead. 1925 {idx2} can be omitted, meaning the end of the list. 1926 When the selected range of items is partly past the 1927 end of the list, items will be added. 1928 1929 *:let+=* *:let-=* *:letstar=* 1930 *:let/=* *:let%=* *:let.=* *:let..=* *E734* 1931:let {var} += {expr1} Like ":let {var} = {var} + {expr1}". 1932:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}". 1933`:let {var} *= {expr1}` Like ":let {var} = {var} * {expr1}". 1934:let {var} /= {expr1} Like ":let {var} = {var} / {expr1}". 1935:let {var} %= {expr1} Like ":let {var} = {var} % {expr1}". 1936:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}". 1937:let {var} ..= {expr1} Like ":let {var} = {var} .. {expr1}". 1938 These fail if {var} was not set yet and when the type 1939 of {var} and {expr1} don't fit the operator. 1940 `+=` modifies a |List| or a |Blob| in-place instead of 1941 creating a new one. 1942 1943 1944:let ${env-name} = {expr1} *:let-environment* *:let-$* 1945 Set environment variable {env-name} to the result of 1946 the expression {expr1}. The type is always String. 1947:let ${env-name} .= {expr1} 1948:let ${env-name} ..= {expr1} 1949 Append {expr1} to the environment variable {env-name}. 1950 If the environment variable didn't exist yet this 1951 works like "=". 1952 1953:let @{reg-name} = {expr1} *:let-register* *:let-@* 1954 Write the result of the expression {expr1} in register 1955 {reg-name}. {reg-name} must be a single letter, and 1956 must be the name of a writable register (see 1957 |registers|). "@@" can be used for the unnamed 1958 register, "@/" for the search pattern. 1959 If the result of {expr1} ends in a <CR> or <NL>, the 1960 register will be linewise, otherwise it will be set to 1961 charwise. 1962 This can be used to clear the last search pattern: > 1963 :let @/ = "" 1964< This is different from searching for an empty string, 1965 that would match everywhere. 1966 1967:let @{reg-name} .= {expr1} 1968:let @{reg-name} ..= {expr1} 1969 Append {expr1} to register {reg-name}. If the 1970 register was empty it's like setting it to {expr1}. 1971 1972:let &{option-name} = {expr1} *:let-option* *:let-&* 1973 Set option {option-name} to the result of the 1974 expression {expr1}. A String or Number value is 1975 always converted to the type of the option. 1976 For an option local to a window or buffer the effect 1977 is just like using the |:set| command: both the local 1978 value and the global value are changed. 1979 Example: > 1980 :let &path = &path .. ',/usr/local/include' 1981 1982:let &{option-name} .= {expr1} 1983:let &{option-name} ..= {expr1} 1984 For a string option: Append {expr1} to the value. 1985 Does not insert a comma like |:set+=|. 1986 1987:let &{option-name} += {expr1} 1988:let &{option-name} -= {expr1} 1989 For a number or boolean option: Add or subtract 1990 {expr1}. 1991 1992:let &l:{option-name} = {expr1} 1993:let &l:{option-name} += {expr1} 1994:let &l:{option-name} -= {expr1} 1995:let &l:{option-name} .= {expr1} 1996:let &l:{option-name} ..= {expr1} 1997 Like above, but only set the local value of an option 1998 (if there is one). Works like |:setlocal|. 1999 2000:let &g:{option-name} = {expr1} 2001:let &g:{option-name} += {expr1} 2002:let &g:{option-name} -= {expr1} 2003:let &g:{option-name} .= {expr1} 2004:let &g:{option-name} ..= {expr1} 2005 Like above, but only set the global value of an option 2006 (if there is one). Works like |:setglobal|. 2007 2008:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688* 2009 {expr1} must evaluate to a |List|. The first item in 2010 the list is assigned to {name1}, the second item to 2011 {name2}, etc. 2012 The number of names must match the number of items in 2013 the |List|. 2014 Each name can be one of the items of the ":let" 2015 command as mentioned above. 2016 Example: > 2017 :let [s, item] = GetItem(s) 2018< Detail: {expr1} is evaluated first, then the 2019 assignments are done in sequence. This matters if 2020 {name2} depends on {name1}. Example: > 2021 :let x = [0, 1] 2022 :let i = 0 2023 :let [i, x[i]] = [1, 2] 2024 :echo x 2025< The result is [0, 2]. 2026 2027:let [{name1}, {name2}, ...] += {expr1} 2028:let [{name1}, {name2}, ...] -= {expr1} 2029`:let [{name1}, {name2}, ...] *= {expr1}` 2030:let [{name1}, {name2}, ...] /= {expr1} 2031:let [{name1}, {name2}, ...] %= {expr1} 2032:let [{name1}, {name2}, ...] .= {expr1} 2033:let [{name1}, {name2}, ...] ..= {expr1} 2034 Like above, but add, subtract, multiply, divide, 2035 modulo, or append the value for each |List| item. 2036 2037:let [{name}, ..., ; {lastname}] = {expr1} *E452* 2038 Like |:let-unpack| above, but the |List| may have more 2039 items than there are names. A list of the remaining 2040 items is assigned to {lastname}. If there are no 2041 remaining items {lastname} is set to an empty list. 2042 Example: > 2043 :let [a, b; rest] = ["aval", "bval", 3, 4] 2044< 2045:let [{name}, ..., ; {lastname}] += {expr1} 2046:let [{name}, ..., ; {lastname}] -= {expr1} 2047:let [{name}, ..., ; {lastname}] .= {expr1} 2048:let [{name}, ..., ; {lastname}] ..= {expr1} 2049 Like above, but add/subtract/append the value for each 2050 |List| item. 2051 2052 *:let=<<* *:let-heredoc* 2053 *E990* *E991* *E172* *E221* *E1145* 2054:let {var-name} =<< [trim] [eval] {endmarker} 2055text... 2056text... 2057{endmarker} 2058 Set internal variable {var-name} to a |List| 2059 containing the lines of text bounded by the string 2060 {endmarker}. 2061 2062 If "eval" is not specified, then each line of text is 2063 used as a |literal-string|, except that single quotes 2064 does not need to be doubled. 2065 If "eval" is specified, then any Vim expression in the 2066 form {expr} is evaluated and the result replaces the 2067 expression, like with |interpolated-string|. 2068 Example where $HOME is expanded: > 2069 let lines =<< trim eval END 2070 some text 2071 See the file {$HOME}/.vimrc 2072 more text 2073 END 2074< There can be multiple Vim expressions in a single line 2075 but an expression cannot span multiple lines. If any 2076 expression evaluation fails, then the assignment 2077 fails. 2078 2079 {endmarker} must not contain white space. 2080 {endmarker} cannot start with a lower case character. 2081 The last line should end only with the {endmarker} 2082 string without any other character. Watch out for 2083 white space after {endmarker}! 2084 2085 Without "trim" any white space characters in the lines 2086 of text are preserved. If "trim" is specified before 2087 {endmarker}, then indentation is stripped so you can 2088 do: > 2089 let text =<< trim END 2090 if ok 2091 echo 'done' 2092 endif 2093 END 2094< Results in: `["if ok", " echo 'done'", "endif"]` 2095 The end marker must line up with "let" and the 2096 indentation of the first line is removed from all the 2097 text lines. 2098 Specifically: all the leading indentation exactly 2099 matching the leading indentation of the first 2100 non-empty text line is stripped from the input lines. 2101 All leading indentation exactly matching the leading 2102 indentation before `let` is stripped from the line 2103 containing {endmarker}. Note that the difference 2104 between space and tab matters here. 2105 2106 If {var-name} didn't exist yet, it is created. 2107 Cannot be followed by another command, but can be 2108 followed by a comment. 2109 2110 To avoid line continuation to be applied, consider 2111 adding 'C' to 'cpoptions': > 2112 set cpo+=C 2113 let var =<< END 2114 \ leading backslash 2115 END 2116 set cpo-=C 2117< 2118 Examples: > 2119 let var1 =<< END 2120 Sample text 1 2121 Sample text 2 2122 Sample text 3 2123 END 2124 2125 let data =<< trim DATA 2126 1 2 3 4 2127 5 6 7 8 2128 DATA 2129 2130 let code =<< trim eval CODE 2131 let v = {10 + 20} 2132 let h = "{$HOME}" 2133 let s = "{Str1()} abc {Str2()}" 2134 let n = {MyFunc(3, 4)} 2135 CODE 2136< 2137 *E121* 2138:let {var-name} ... List the value of variable {var-name}. Multiple 2139 variable names may be given. Special names recognized 2140 here: *E738* 2141 g: global variables 2142 b: local buffer variables 2143 w: local window variables 2144 t: local tab page variables 2145 s: script-local variables 2146 l: local function variables 2147 v: Vim variables. 2148 2149:let List the values of all variables. The type of the 2150 variable is indicated before the value: 2151 <nothing> String 2152 # Number 2153 * Funcref 2154 2155:unl[et][!] {name} ... *:unlet* *:unl* *E108* *E795* 2156 Remove the internal variable {name}. Several variable 2157 names can be given, they are all removed. The name 2158 may also be a |List| or |Dictionary| item. 2159 With [!] no error message is given for non-existing 2160 variables. 2161 One or more items from a |List| can be removed: > 2162 :unlet list[3] " remove fourth item 2163 :unlet list[3:] " remove fourth item to last 2164< One item from a |Dictionary| can be removed at a time: > 2165 :unlet dict['two'] 2166 :unlet dict.two 2167< This is especially useful to clean up used global 2168 variables and script-local variables (these are not 2169 deleted when the script ends). Function-local 2170 variables are automatically deleted when the function 2171 ends. 2172 2173:unl[et] ${env-name} ... *:unlet-environment* *:unlet-$* 2174 Remove environment variable {env-name}. 2175 Can mix {name} and ${env-name} in one :unlet command. 2176 No error message is given for a non-existing 2177 variable, also without !. 2178 If the system does not support deleting an environment 2179 variable, it is made empty. 2180 2181 *:cons* *:const* 2182:cons[t] {var-name} = {expr1} 2183:cons[t] [{name1}, {name2}, ...] = {expr1} 2184:cons[t] [{name}, ..., ; {lastname}] = {expr1} 2185:cons[t] {var-name} =<< [trim] [eval] {endmarker} 2186text... 2187text... 2188{endmarker} 2189 Similar to |:let|, but additionally lock the variable 2190 after setting the value. This is the same as locking 2191 the variable with |:lockvar| just after |:let|, thus: > 2192 :const x = 1 2193< is equivalent to: > 2194 :let x = 1 2195 :lockvar! x 2196< This is useful if you want to make sure the variable 2197 is not modified. If the value is a List or Dictionary 2198 literal then the items also cannot be changed: > 2199 const ll = [1, 2, 3] 2200 let ll[1] = 5 " Error! 2201< Nested references are not locked: > 2202 let lvar = ['a'] 2203 const lconst = [0, lvar] 2204 let lconst[0] = 2 " Error! 2205 let lconst[1][0] = 'b' " OK 2206< *E995* 2207 It is an error to specify an existing variable with 2208 |:const|. > 2209 :let x = 1 2210 :const x = 1 " Error! 2211< *E996* 2212 Note that environment variables, option values and 2213 register values cannot be used here, since they cannot 2214 be locked. 2215 2216:cons[t] 2217:cons[t] {var-name} 2218 If no argument is given or only {var-name} is given, 2219 the behavior is the same as |:let|. 2220 2221:lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv* 2222 Lock the internal variable {name}. Locking means that 2223 it can no longer be changed (until it is unlocked). 2224 A locked variable can be deleted: > 2225 :lockvar v 2226 :let v = 'asdf' " fails! 2227 :unlet v " works 2228< *E741* *E940* *E1122* 2229 If you try to change a locked variable you get an 2230 error message: "E741: Value is locked: {name}". 2231 If you try to lock or unlock a built-in variable you 2232 will get an error message "E940: Cannot lock or unlock 2233 variable {name}". 2234 2235 [depth] is relevant when locking a |List| or 2236 |Dictionary|. It specifies how deep the locking goes: 2237 0 Lock the variable {name} but not its 2238 value. 2239 1 Lock the |List| or |Dictionary| itself, 2240 cannot add or remove items, but can 2241 still change their values. 2242 2 Also lock the values, cannot change 2243 the items. If an item is a |List| or 2244 |Dictionary|, cannot add or remove 2245 items, but can still change the 2246 values. 2247 3 Like 2 but for the |List| / 2248 |Dictionary| in the |List| / 2249 |Dictionary|, one level deeper. 2250 The default [depth] is 2, thus when {name} is a |List| 2251 or |Dictionary| the values cannot be changed. 2252 2253 Example with [depth] 0: > 2254 let mylist = [1, 2, 3] 2255 lockvar 0 mylist 2256 let mylist[0] = 77 " OK 2257 call add(mylist, 4) " OK 2258 let mylist = [7, 8, 9] " Error! 2259< *E743* 2260 For unlimited depth use [!] and omit [depth]. 2261 However, there is a maximum depth of 100 to catch 2262 loops. 2263 2264 Note that when two variables refer to the same |List| 2265 and you lock one of them, the |List| will also be 2266 locked when used through the other variable. 2267 Example: > 2268 :let l = [0, 1, 2, 3] 2269 :let cl = l 2270 :lockvar l 2271 :let cl[1] = 99 " won't work! 2272< You may want to make a copy of a list to avoid this. 2273 See |deepcopy()|. 2274 2275 2276:unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo* 2277 Unlock the internal variable {name}. Does the 2278 opposite of |:lockvar|. 2279 2280 No error is given if {name} does not exist. 2281 2282:if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580* 2283:en[dif] Execute the commands until the next matching `:else` 2284 or `:endif` if {expr1} evaluates to non-zero. 2285 Although the short forms work, it is recommended to 2286 always use `:endif` to avoid confusion and to make 2287 auto-indenting work properly. 2288 2289 From Vim version 4.5 until 5.0, every Ex command in 2290 between the `:if` and `:endif` is ignored. These two 2291 commands were just to allow for future expansions in a 2292 backward compatible way. Nesting was allowed. Note 2293 that any `:else` or `:elseif` was ignored, the `else` 2294 part was not executed either. 2295 2296 You can use this to remain compatible with older 2297 versions: > 2298 :if version >= 500 2299 : version-5-specific-commands 2300 :endif 2301< The commands still need to be parsed to find the 2302 `endif`. Sometimes an older Vim has a problem with a 2303 new command. For example, `:silent` is recognized as 2304 a `:substitute` command. In that case `:execute` can 2305 avoid problems: > 2306 :if version >= 600 2307 : execute "silent 1,$delete" 2308 :endif 2309< 2310 NOTE: The `:append` and `:insert` commands don't work 2311 properly in between `:if` and `:endif`. 2312 2313 *:else* *:el* *E581* *E583* 2314:el[se] Execute the commands until the next matching `:else` 2315 or `:endif` if they previously were not being 2316 executed. 2317 2318 *:elseif* *:elsei* *E582* *E584* 2319:elsei[f] {expr1} Short for `:else` `:if`, with the addition that there 2320 is no extra `:endif`. 2321 2322:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw* 2323 *E170* *E585* *E588* *E733* 2324:endw[hile] Repeat the commands between `:while` and `:endwhile`, 2325 as long as {expr1} evaluates to non-zero. 2326 When an error is detected from a command inside the 2327 loop, execution continues after the `endwhile`. 2328 Example: > 2329 :let lnum = 1 2330 :while lnum <= line("$") 2331 :call FixLine(lnum) 2332 :let lnum = lnum + 1 2333 :endwhile 2334< 2335 NOTE: The `:append` and `:insert` commands don't work 2336 properly inside a `:while` and `:for` loop. 2337 2338:for {var} in {object} *:for* *E690* *E732* 2339:endfo[r] *:endfo* *:endfor* 2340 Repeat the commands between `:for` and `:endfor` for 2341 each item in {object}. {object} can be a |List|, 2342 a |Blob| or a |String|. 2343 2344 Variable {var} is set to the value of each item. 2345 2346 When an error is detected for a command inside the 2347 loop, execution continues after the `endfor`. 2348 Changing {object} inside the loop affects what items 2349 are used. Make a copy if this is unwanted: > 2350 :for item in copy(mylist) 2351< 2352 When {object} is a |List| and not making a copy, Vim 2353 stores a reference to the next item in the |List| 2354 before executing the commands with the current item. 2355 Thus the current item can be removed without effect. 2356 Removing any later item means it will not be found. 2357 Thus the following example works (an inefficient way 2358 to make a |List| empty): > 2359 for item in mylist 2360 call remove(mylist, 0) 2361 endfor 2362< Note that reordering the |List| (e.g., with sort() or 2363 reverse()) may have unexpected effects. 2364 2365 When {object} is a |Blob|, Vim always makes a copy to 2366 iterate over. Unlike with |List|, modifying the 2367 |Blob| does not affect the iteration. 2368 2369 When {object} is a |String| each item is a string with 2370 one character, plus any combining characters. 2371 2372:for [{var1}, {var2}, ...] in {listlist} 2373:endfo[r] 2374 Like `:for` above, but each item in {listlist} must be 2375 a list, of which each item is assigned to {var1}, 2376 {var2}, etc. Example: > 2377 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]] 2378 :echo getline(lnum)[col] 2379 :endfor 2380< 2381 *:continue* *:con* *E586* 2382:con[tinue] When used inside a `:while` or `:for` loop, jumps back 2383 to the start of the loop. 2384 2385 If it is used after a `:try` inside the loop but 2386 before the matching `:finally` (if present), the 2387 commands following the `:finally` up to the matching 2388 `:endtry` are executed first. This process applies to 2389 all nested `:try`s inside the loop. The outermost 2390 `:endtry` then jumps back to the start of the loop. 2391 2392 *:break* *:brea* *E587* 2393:brea[k] When used inside a `:while` or `:for` loop, skips to 2394 the command after the matching `:endwhile` or 2395 `:endfor`. 2396 If it is used after a `:try` inside the loop but 2397 before the matching `:finally` (if present), the 2398 commands following the `:finally` up to the matching 2399 `:endtry` are executed first. This process applies to 2400 all nested `:try`s inside the loop. The outermost 2401 `:endtry` then jumps to the command after the loop. 2402 2403:try *:try* *:endt* *:endtry* *E600* *E601* *E602* 2404:endt[ry] Change the error handling for the commands between 2405 `:try` and `:endtry` including everything being 2406 executed across `:source` commands, function calls, 2407 or autocommand invocations. 2408 2409 When an error or interrupt is detected and there is 2410 a `:finally` command following, execution continues 2411 after the `:finally`. Otherwise, or when the 2412 `:endtry` is reached thereafter, the next 2413 (dynamically) surrounding `:try` is checked for 2414 a corresponding `:finally` etc. Then the script 2415 processing is terminated. Whether a function 2416 definition has an "abort" argument does not matter. 2417 Example: > 2418 try | call Unknown() | finally | echomsg "cleanup" | endtry 2419 echomsg "not reached" 2420< 2421 Moreover, an error or interrupt (dynamically) inside 2422 `:try` and `:endtry` is converted to an exception. It 2423 can be caught as if it were thrown by a `:throw` 2424 command (see `:catch`). In this case, the script 2425 processing is not terminated. 2426 2427 The value "Vim:Interrupt" is used for an interrupt 2428 exception. An error in a Vim command is converted 2429 to a value of the form "Vim({command}):{errmsg}", 2430 other errors are converted to a value of the form 2431 "Vim:{errmsg}". {command} is the full command name, 2432 and {errmsg} is the message that is displayed if the 2433 error exception is not caught, always beginning with 2434 the error number. 2435 Examples: > 2436 try | sleep 100 | catch /^Vim:Interrupt$/ | endtry 2437 try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry 2438< 2439 *:cat* *:catch* 2440 *E603* *E604* *E605* *E654* 2441:cat[ch] [/{pattern}/] The following commands until the next `:catch`, 2442 `:finally`, or `:endtry` that belongs to the same 2443 `:try` as the `:catch` are executed when an exception 2444 matching {pattern} is being thrown and has not yet 2445 been caught by a previous `:catch`. Otherwise, these 2446 commands are skipped. 2447 Pattern can start with "Vim({cmd})" to indicate an 2448 exception that occurred when executing the Ex command 2449 {cmd}. When {pattern} is omitted all errors are 2450 caught. Examples: > 2451 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C) 2452 :catch /^Vim\%((\S\+)\)\=:E/ " catch all Vim errors 2453 :catch /^Vim\%((\S\+)\)\=:/ " catch errors and interrupts 2454 :catch /^Vim(write):/ " catch all errors in :write 2455 :catch /^Vim(!):/ " catch all errors in :! 2456 :catch /^Vim\%((\S\+)\)\=:E123:/ " catch error E123 2457 :catch /my-exception/ " catch user exception 2458 :catch /.*/ " catch everything 2459 :catch " same as /.*/ 2460< 2461 Another character can be used instead of / around the 2462 {pattern}, so long as it does not have a special 2463 meaning (e.g., '|' or '"') and doesn't occur inside 2464 {pattern}. 2465 Information about the exception is available in 2466 |v:exception|. Also see |throw-variables|. 2467 NOTE: It is not reliable to ":catch" the TEXT of 2468 an error message because it may vary in different 2469 locales. 2470 2471 *:fina* *:finally* *E606* *E607* 2472:fina[lly] The following commands until the matching `:endtry` 2473 are executed whenever the part between the matching 2474 `:try` and the `:finally` is left: either by falling 2475 through to the `:finally` or by a `:continue`, 2476 `:break`, `:finish`, or `:return`, or by an error or 2477 interrupt or exception (see `:throw`). 2478 2479 *:th* *:throw* *E608* 2480:th[row] {expr1} The {expr1} is evaluated and thrown as an exception. 2481 If the `:throw` is used after a `:try` but before the 2482 first corresponding `:catch`, commands are skipped 2483 until the first `:catch` matching {expr1} is reached. 2484 If there is no such `:catch` or if the `:throw` is 2485 used after a `:catch` but before the `:finally`, the 2486 commands following the `:finally` (if present) up to 2487 the matching `:endtry` are executed. If the `:throw` 2488 is after the `:finally`, commands up to the `:endtry` 2489 are skipped. At the `:endtry`, this process applies 2490 again for the next dynamically surrounding `:try` 2491 (which may be found in a calling function or sourcing 2492 script), until a matching `:catch` has been found. 2493 If the exception is not caught, the command processing 2494 is terminated. 2495 Example: > 2496 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry 2497< Note that "catch" may need to be on a separate line 2498 for when an error causes the parsing to skip the whole 2499 line and not see the "|" that separates the commands. 2500 2501 *:ec* *:echo* 2502:ec[ho] {expr1} ... Echoes each {expr1}, with a space in between. The 2503 first {expr1} starts on a new line. 2504 Also see |:comment|. 2505 Use "\n" to start a new line. Use "\r" to move the 2506 cursor to the first column. 2507 Uses the highlighting set by the `:echohl` command. 2508 Cannot be followed by a comment. 2509 Example: > 2510 :echo "the value of 'shell' is" &shell 2511< *:echo-redraw* 2512 A later redraw may make the message disappear again. 2513 And since Vim mostly postpones redrawing until it's 2514 finished with a sequence of commands this happens 2515 quite often. To avoid that a command from before the 2516 `:echo` causes a redraw afterwards (redraws are often 2517 postponed until you type something), force a redraw 2518 with the `:redraw` command. Example: > 2519 :new | redraw | echo "there is a new window" 2520< *:echo-self-refer* 2521 When printing nested containers echo prints second 2522 occurrence of the self-referencing container using 2523 "[...@level]" (self-referencing |List|) or 2524 "{...@level}" (self-referencing |Dict|): > 2525 :let l = [] 2526 :call add(l, l) 2527 :let l2 = [] 2528 :call add(l2, [l2]) 2529 :echo l l2 2530< echoes "[[...@0]] [[[...@0]]]". Echoing "[l]" will 2531 echo "[[[...@1]]]" because l first occurs at second 2532 level. 2533 2534 *:echon* 2535:echon {expr1} ... Echoes each {expr1}, without anything added. Also see 2536 |:comment|. 2537 Uses the highlighting set by the `:echohl` command. 2538 Cannot be followed by a comment. 2539 Example: > 2540 :echon "the value of 'shell' is " &shell 2541< 2542 Note the difference between using `:echo`, which is a 2543 Vim command, and `:!echo`, which is an external shell 2544 command: > 2545 :!echo % --> filename 2546< The arguments of ":!" are expanded, see |:_%|. > 2547 :!echo "%" --> filename or "filename" 2548< Like the previous example. Whether you see the double 2549 quotes or not depends on your 'shell'. > 2550 :echo % --> nothing 2551< The '%' is an illegal character in an expression. > 2552 :echo "%" --> % 2553< This just echoes the '%' character. > 2554 :echo expand("%") --> filename 2555< This calls the expand() function to expand the '%'. 2556 2557 *:echoh* *:echohl* 2558:echoh[l] {name} Use the highlight group {name} for the following 2559 `:echo`, `:echon` and `:echomsg` commands. Also used 2560 for the `input()` prompt. Example: > 2561 :echohl WarningMsg | echo "Don't panic!" | echohl None 2562< Don't forget to set the group back to "None", 2563 otherwise all following echo's will be highlighted. 2564 2565 *:echom* *:echomsg* 2566:echom[sg] {expr1} ... Echo the expression(s) as a true message, saving the 2567 message in the |message-history|. 2568 Spaces are placed between the arguments as with the 2569 `:echo` command. But unprintable characters are 2570 displayed, not interpreted. 2571 The parsing works slightly different from `:echo`, 2572 more like `:execute`. All the expressions are first 2573 evaluated and concatenated before echoing anything. 2574 If expressions does not evaluate to a Number or 2575 String, string() is used to turn it into a string. 2576 Uses the highlighting set by the `:echohl` command. 2577 Example: > 2578 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see." 2579< See |:echo-redraw| to avoid the message disappearing 2580 when the screen is redrawn. 2581 2582 *:echoe* *:echoerr* 2583:echoe[rr] {expr1} ... Echo the expression(s) as an error message, saving the 2584 message in the |message-history|. When used in a 2585 script or function the line number will be added. 2586 Spaces are placed between the arguments as with the 2587 `:echomsg` command. When used inside a try conditional, 2588 the message is raised as an error exception instead 2589 (see |try-echoerr|). 2590 Example: > 2591 :echoerr "This script just failed!" 2592< If you just want a highlighted message use `:echohl`. 2593 And to get a beep: > 2594 :exe "normal \<Esc>" 2595< 2596 *:eval* 2597:eval {expr} Evaluate {expr} and discard the result. Example: > 2598 :eval Getlist()->Filter()->append('$') 2599 2600< The expression is supposed to have a side effect, 2601 since the resulting value is not used. In the example 2602 the `append()` call appends the List with text to the 2603 buffer. This is similar to `:call` but works with any 2604 expression. 2605 2606 The command can be shortened to `:ev` or `:eva`, but 2607 these are hard to recognize and therefore not to be 2608 used. 2609 2610 The command cannot be followed by "|" and another 2611 command, since "|" is seen as part of the expression. 2612 2613 2614 *:exe* *:execute* 2615:exe[cute] {expr1} ... Executes the string that results from the evaluation 2616 of {expr1} as an Ex command. 2617 Multiple arguments are concatenated, with a space in 2618 between. To avoid the extra space use the ".." 2619 operator to concatenate strings into one argument. 2620 {expr1} is used as the processed command, command line 2621 editing keys are not recognized. 2622 Cannot be followed by a comment. 2623 Examples: > 2624 :execute "buffer" nextbuf 2625 :execute "normal" count .. "w" 2626< 2627 ":execute" can be used to append a command to commands 2628 that don't accept a '|'. Example: > 2629 :execute '!ls' | echo "theend" 2630 2631< ":execute" is also a nice way to avoid having to type 2632 control characters in a Vim script for a ":normal" 2633 command: > 2634 :execute "normal ixxx\<Esc>" 2635< This has an <Esc> character, see |expr-string|. 2636 2637 Be careful to correctly escape special characters in 2638 file names. The |fnameescape()| function can be used 2639 for Vim commands, |shellescape()| for |:!| commands. 2640 Examples: > 2641 :execute "e " .. fnameescape(filename) 2642 :execute "!ls " .. shellescape(filename, 1) 2643< 2644 Note: The executed string may be any command-line, but 2645 starting or ending "if", "while" and "for" does not 2646 always work, because when commands are skipped the 2647 ":execute" is not evaluated and Vim loses track of 2648 where blocks start and end. Also "break" and 2649 "continue" should not be inside ":execute". 2650 This example does not work, because the ":execute" is 2651 not evaluated and Vim does not see the "while", and 2652 gives an error for finding an ":endwhile": > 2653 :if 0 2654 : execute 'while i > 5' 2655 : echo "test" 2656 : endwhile 2657 :endif 2658< 2659 It is allowed to have a "while" or "if" command 2660 completely in the executed string: > 2661 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile' 2662< 2663 2664 *:exe-comment* 2665 ":execute", ":echo" and ":echon" cannot be followed by 2666 a comment directly, because they see the '"' as the 2667 start of a string. But, you can use '|' followed by a 2668 comment. Example: > 2669 :echo "foo" | "this is a comment 2670 2671============================================================================== 26728. Exception handling *exception-handling* 2673 2674The Vim script language comprises an exception handling feature. This section 2675explains how it can be used in a Vim script. 2676 2677Exceptions may be raised by Vim on an error or on interrupt, see 2678|catch-errors| and |catch-interrupt|. You can also explicitly throw an 2679exception by using the ":throw" command, see |throw-catch|. 2680 2681 2682TRY CONDITIONALS *try-conditionals* 2683 2684Exceptions can be caught or can cause cleanup code to be executed. You can 2685use a try conditional to specify catch clauses (that catch exceptions) and/or 2686a finally clause (to be executed for cleanup). 2687 A try conditional begins with a |:try| command and ends at the matching 2688|:endtry| command. In between, you can use a |:catch| command to start 2689a catch clause, or a |:finally| command to start a finally clause. There may 2690be none or multiple catch clauses, but there is at most one finally clause, 2691which must not be followed by any catch clauses. The lines before the catch 2692clauses and the finally clause is called a try block. > 2693 2694 :try 2695 : ... 2696 : ... TRY BLOCK 2697 : ... 2698 :catch /{pattern}/ 2699 : ... 2700 : ... CATCH CLAUSE 2701 : ... 2702 :catch /{pattern}/ 2703 : ... 2704 : ... CATCH CLAUSE 2705 : ... 2706 :finally 2707 : ... 2708 : ... FINALLY CLAUSE 2709 : ... 2710 :endtry 2711 2712The try conditional allows to watch code for exceptions and to take the 2713appropriate actions. Exceptions from the try block may be caught. Exceptions 2714from the try block and also the catch clauses may cause cleanup actions. 2715 When no exception is thrown during execution of the try block, the control 2716is transferred to the finally clause, if present. After its execution, the 2717script continues with the line following the ":endtry". 2718 When an exception occurs during execution of the try block, the remaining 2719lines in the try block are skipped. The exception is matched against the 2720patterns specified as arguments to the ":catch" commands. The catch clause 2721after the first matching ":catch" is taken, other catch clauses are not 2722executed. The catch clause ends when the next ":catch", ":finally", or 2723":endtry" command is reached - whatever is first. Then, the finally clause 2724(if present) is executed. When the ":endtry" is reached, the script execution 2725continues in the following line as usual. 2726 When an exception that does not match any of the patterns specified by the 2727":catch" commands is thrown in the try block, the exception is not caught by 2728that try conditional and none of the catch clauses is executed. Only the 2729finally clause, if present, is taken. The exception pends during execution of 2730the finally clause. It is resumed at the ":endtry", so that commands after 2731the ":endtry" are not executed and the exception might be caught elsewhere, 2732see |try-nesting|. 2733 When during execution of a catch clause another exception is thrown, the 2734remaining lines in that catch clause are not executed. The new exception is 2735not matched against the patterns in any of the ":catch" commands of the same 2736try conditional and none of its catch clauses is taken. If there is, however, 2737a finally clause, it is executed, and the exception pends during its 2738execution. The commands following the ":endtry" are not executed. The new 2739exception might, however, be caught elsewhere, see |try-nesting|. 2740 When during execution of the finally clause (if present) an exception is 2741thrown, the remaining lines in the finally clause are skipped. If the finally 2742clause has been taken because of an exception from the try block or one of the 2743catch clauses, the original (pending) exception is discarded. The commands 2744following the ":endtry" are not executed, and the exception from the finally 2745clause is propagated and can be caught elsewhere, see |try-nesting|. 2746 2747The finally clause is also executed, when a ":break" or ":continue" for 2748a ":while" loop enclosing the complete try conditional is executed from the 2749try block or a catch clause. Or when a ":return" or ":finish" is executed 2750from the try block or a catch clause of a try conditional in a function or 2751sourced script, respectively. The ":break", ":continue", ":return", or 2752":finish" pends during execution of the finally clause and is resumed when the 2753":endtry" is reached. It is, however, discarded when an exception is thrown 2754from the finally clause. 2755 When a ":break" or ":continue" for a ":while" loop enclosing the complete 2756try conditional or when a ":return" or ":finish" is encountered in the finally 2757clause, the rest of the finally clause is skipped, and the ":break", 2758":continue", ":return" or ":finish" is executed as usual. If the finally 2759clause has been taken because of an exception or an earlier ":break", 2760":continue", ":return", or ":finish" from the try block or a catch clause, 2761this pending exception or command is discarded. 2762 2763For examples see |throw-catch| and |try-finally|. 2764 2765 2766NESTING OF TRY CONDITIONALS *try-nesting* 2767 2768Try conditionals can be nested arbitrarily. That is, a complete try 2769conditional can be put into the try block, a catch clause, or the finally 2770clause of another try conditional. If the inner try conditional does not 2771catch an exception thrown in its try block or throws a new exception from one 2772of its catch clauses or its finally clause, the outer try conditional is 2773checked according to the rules above. If the inner try conditional is in the 2774try block of the outer try conditional, its catch clauses are checked, but 2775otherwise only the finally clause is executed. It does not matter for 2776nesting, whether the inner try conditional is directly contained in the outer 2777one, or whether the outer one sources a script or calls a function containing 2778the inner try conditional. 2779 2780When none of the active try conditionals catches an exception, just their 2781finally clauses are executed. Thereafter, the script processing terminates. 2782An error message is displayed in case of an uncaught exception explicitly 2783thrown by a ":throw" command. For uncaught error and interrupt exceptions 2784implicitly raised by Vim, the error message(s) or interrupt message are shown 2785as usual. 2786 2787For examples see |throw-catch|. 2788 2789 2790EXAMINING EXCEPTION HANDLING CODE *except-examine* 2791 2792Exception handling code can get tricky. If you are in doubt what happens, set 2793'verbose' to 13 or use the ":13verbose" command modifier when sourcing your 2794script file. Then you see when an exception is thrown, discarded, caught, or 2795finished. When using a verbosity level of at least 14, things pending in 2796a finally clause are also shown. This information is also given in debug mode 2797(see |debug-scripts|). 2798 2799 2800THROWING AND CATCHING EXCEPTIONS *throw-catch* 2801 2802You can throw any number or string as an exception. Use the |:throw| command 2803and pass the value to be thrown as argument: > 2804 :throw 4711 2805 :throw "string" 2806< *throw-expression* 2807You can also specify an expression argument. The expression is then evaluated 2808first, and the result is thrown: > 2809 :throw 4705 + strlen("string") 2810 :throw strpart("strings", 0, 6) 2811 2812An exception might be thrown during evaluation of the argument of the ":throw" 2813command. Unless it is caught there, the expression evaluation is abandoned. 2814The ":throw" command then does not throw a new exception. 2815 Example: > 2816 2817 :function! Foo(arg) 2818 : try 2819 : throw a:arg 2820 : catch /foo/ 2821 : endtry 2822 : return 1 2823 :endfunction 2824 : 2825 :function! Bar() 2826 : echo "in Bar" 2827 : return 4710 2828 :endfunction 2829 : 2830 :throw Foo("arrgh") + Bar() 2831 2832This throws "arrgh", and "in Bar" is not displayed since Bar() is not 2833executed. > 2834 :throw Foo("foo") + Bar() 2835however displays "in Bar" and throws 4711. 2836 2837Any other command that takes an expression as argument might also be 2838abandoned by an (uncaught) exception during the expression evaluation. The 2839exception is then propagated to the caller of the command. 2840 Example: > 2841 2842 :if Foo("arrgh") 2843 : echo "then" 2844 :else 2845 : echo "else" 2846 :endif 2847 2848Here neither of "then" or "else" is displayed. 2849 2850 *catch-order* 2851Exceptions can be caught by a try conditional with one or more |:catch| 2852commands, see |try-conditionals|. The values to be caught by each ":catch" 2853command can be specified as a pattern argument. The subsequent catch clause 2854gets executed when a matching exception is caught. 2855 Example: > 2856 2857 :function! Foo(value) 2858 : try 2859 : throw a:value 2860 : catch /^\d\+$/ 2861 : echo "Number thrown" 2862 : catch /.*/ 2863 : echo "String thrown" 2864 : endtry 2865 :endfunction 2866 : 2867 :call Foo(0x1267) 2868 :call Foo('string') 2869 2870The first call to Foo() displays "Number thrown", the second "String thrown". 2871An exception is matched against the ":catch" commands in the order they are 2872specified. Only the first match counts. So you should place the more 2873specific ":catch" first. The following order does not make sense: > 2874 2875 : catch /.*/ 2876 : echo "String thrown" 2877 : catch /^\d\+$/ 2878 : echo "Number thrown" 2879 2880The first ":catch" here matches always, so that the second catch clause is 2881never taken. 2882 2883 *throw-variables* 2884If you catch an exception by a general pattern, you may access the exact value 2885in the variable |v:exception|: > 2886 2887 : catch /^\d\+$/ 2888 : echo "Number thrown. Value is" v:exception 2889 2890You may also be interested where an exception was thrown. This is stored in 2891|v:throwpoint|. And you can obtain the stack trace from |v:stacktrace|. 2892Note that "v:exception", "v:stacktrace" and "v:throwpoint" are valid for the 2893exception most recently caught as long it is not finished. 2894 Example: > 2895 2896 :function! Caught() 2897 : if v:exception != "" 2898 : echo 'Caught "' .. v:exception .. '" in ' .. v:throwpoint 2899 : else 2900 : echo 'Nothing caught' 2901 : endif 2902 :endfunction 2903 : 2904 :function! Foo() 2905 : try 2906 : try 2907 : try 2908 : throw 4711 2909 : finally 2910 : call Caught() 2911 : endtry 2912 : catch /.*/ 2913 : call Caught() 2914 : throw "oops" 2915 : endtry 2916 : catch /.*/ 2917 : call Caught() 2918 : finally 2919 : call Caught() 2920 : endtry 2921 :endfunction 2922 : 2923 :call Foo() 2924 2925This displays > 2926 2927 Nothing caught 2928 Caught "4711" in function Foo, line 4 2929 Caught "oops" in function Foo, line 10 2930 Nothing caught 2931 2932A practical example: The following command ":LineNumber" displays the line 2933number in the script or function where it has been used: > 2934 2935 :function! LineNumber() 2936 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "") 2937 :endfunction 2938 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry 2939< 2940 *try-nested* 2941An exception that is not caught by a try conditional can be caught by 2942a surrounding try conditional: > 2943 2944 :try 2945 : try 2946 : throw "foo" 2947 : catch /foobar/ 2948 : echo "foobar" 2949 : finally 2950 : echo "inner finally" 2951 : endtry 2952 :catch /foo/ 2953 : echo "foo" 2954 :endtry 2955 2956The inner try conditional does not catch the exception, just its finally 2957clause is executed. The exception is then caught by the outer try 2958conditional. The example displays "inner finally" and then "foo". 2959 2960 *throw-from-catch* 2961You can catch an exception and throw a new one to be caught elsewhere from the 2962catch clause: > 2963 2964 :function! Foo() 2965 : throw "foo" 2966 :endfunction 2967 : 2968 :function! Bar() 2969 : try 2970 : call Foo() 2971 : catch /foo/ 2972 : echo "Caught foo, throw bar" 2973 : throw "bar" 2974 : endtry 2975 :endfunction 2976 : 2977 :try 2978 : call Bar() 2979 :catch /.*/ 2980 : echo "Caught" v:exception 2981 :endtry 2982 2983This displays "Caught foo, throw bar" and then "Caught bar". 2984 2985 *rethrow* 2986There is no real rethrow in the Vim script language, but you may throw 2987"v:exception" instead: > 2988 2989 :function! Bar() 2990 : try 2991 : call Foo() 2992 : catch /.*/ 2993 : echo "Rethrow" v:exception 2994 : throw v:exception 2995 : endtry 2996 :endfunction 2997< *try-echoerr* 2998Note that this method cannot be used to "rethrow" Vim error or interrupt 2999exceptions, because it is not possible to fake Vim internal exceptions. 3000Trying so causes an error exception. You should throw your own exception 3001denoting the situation. If you want to cause a Vim error exception containing 3002the original error exception value, you can use the |:echoerr| command: > 3003 3004 :try 3005 : try 3006 : asdf 3007 : catch /.*/ 3008 : echoerr v:exception 3009 : endtry 3010 :catch /.*/ 3011 : echo v:exception 3012 :endtry 3013 3014This code displays 3015 3016 Vim(echoerr):Vim:E492: Not an editor command: asdf ~ 3017 3018 3019CLEANUP CODE *try-finally* 3020 3021Scripts often change global settings and restore them at their end. If the 3022user however interrupts the script by pressing CTRL-C, the settings remain in 3023an inconsistent state. The same may happen to you in the development phase of 3024a script when an error occurs or you explicitly throw an exception without 3025catching it. You can solve these problems by using a try conditional with 3026a finally clause for restoring the settings. Its execution is guaranteed on 3027normal control flow, on error, on an explicit ":throw", and on interrupt. 3028(Note that errors and interrupts from inside the try conditional are converted 3029to exceptions. When not caught, they terminate the script after the finally 3030clause has been executed.) 3031Example: > 3032 3033 :try 3034 : let s:saved_ts = &ts 3035 : set ts=17 3036 : 3037 : " Do the hard work here. 3038 : 3039 :finally 3040 : let &ts = s:saved_ts 3041 : unlet s:saved_ts 3042 :endtry 3043 3044This method should be used locally whenever a function or part of a script 3045changes global settings which need to be restored on failure or normal exit of 3046that function or script part. 3047 3048 *break-finally* 3049Cleanup code works also when the try block or a catch clause is left by 3050a ":continue", ":break", ":return", or ":finish". 3051 Example: > 3052 3053 :let first = 1 3054 :while 1 3055 : try 3056 : if first 3057 : echo "first" 3058 : let first = 0 3059 : continue 3060 : else 3061 : throw "second" 3062 : endif 3063 : catch /.*/ 3064 : echo v:exception 3065 : break 3066 : finally 3067 : echo "cleanup" 3068 : endtry 3069 : echo "still in while" 3070 :endwhile 3071 :echo "end" 3072 3073This displays "first", "cleanup", "second", "cleanup", and "end". > 3074 3075 :function! Foo() 3076 : try 3077 : return 4711 3078 : finally 3079 : echo "cleanup\n" 3080 : endtry 3081 : echo "Foo still active" 3082 :endfunction 3083 : 3084 :echo Foo() "returned by Foo" 3085 3086This displays "cleanup" and "4711 returned by Foo". You don't need to add an 3087extra ":return" in the finally clause. (Above all, this would override the 3088return value.) 3089 3090 *except-from-finally* 3091Using either of ":continue", ":break", ":return", ":finish", or ":throw" in 3092a finally clause is possible, but not recommended since it abandons the 3093cleanup actions for the try conditional. But, of course, interrupt and error 3094exceptions might get raised from a finally clause. 3095 Example where an error in the finally clause stops an interrupt from 3096working correctly: > 3097 3098 :try 3099 : try 3100 : echo "Press CTRL-C for interrupt" 3101 : while 1 3102 : endwhile 3103 : finally 3104 : unlet novar 3105 : endtry 3106 :catch /novar/ 3107 :endtry 3108 :echo "Script still running" 3109 :sleep 1 3110 3111If you need to put commands that could fail into a finally clause, you should 3112think about catching or ignoring the errors in these commands, see 3113|catch-errors| and |ignore-errors|. 3114 3115 3116CATCHING ERRORS *catch-errors* 3117 3118If you want to catch specific errors, you just have to put the code to be 3119watched in a try block and add a catch clause for the error message. The 3120presence of the try conditional causes all errors to be converted to an 3121exception. No message is displayed and |v:errmsg| is not set then. To find 3122the right pattern for the ":catch" command, you have to know how the format of 3123the error exception is. 3124 Error exceptions have the following format: > 3125 3126 Vim({cmdname}):{errmsg} 3127or > 3128 Vim:{errmsg} 3129 3130{cmdname} is the name of the command that failed; the second form is used when 3131the command name is not known. {errmsg} is the error message usually produced 3132when the error occurs outside try conditionals. It always begins with 3133a capital "E", followed by a two or three-digit error number, a colon, and 3134a space. 3135 3136Examples: 3137 3138The command > 3139 :unlet novar 3140normally produces the error message > 3141 E108: No such variable: "novar" 3142which is converted inside try conditionals to an exception > 3143 Vim(unlet):E108: No such variable: "novar" 3144 3145The command > 3146 :dwim 3147normally produces the error message > 3148 E492: Not an editor command: dwim 3149which is converted inside try conditionals to an exception > 3150 Vim:E492: Not an editor command: dwim 3151 3152You can catch all ":unlet" errors by a > 3153 :catch /^Vim(unlet):/ 3154or all errors for misspelled command names by a > 3155 :catch /^Vim:E492:/ 3156 3157Some error messages may be produced by different commands: > 3158 :function nofunc 3159and > 3160 :delfunction nofunc 3161both produce the error message > 3162 E128: Function name must start with a capital: nofunc 3163which is converted inside try conditionals to an exception > 3164 Vim(function):E128: Function name must start with a capital: nofunc 3165or > 3166 Vim(delfunction):E128: Function name must start with a capital: nofunc 3167respectively. You can catch the error by its number independently on the 3168command that caused it if you use the following pattern: > 3169 :catch /^Vim(\a\+):E128:/ 3170 3171Some commands like > 3172 :let x = novar 3173produce multiple error messages, here: > 3174 E121: Undefined variable: novar 3175 E15: Invalid expression: novar 3176Only the first is used for the exception value, since it is the most specific 3177one (see |except-several-errors|). So you can catch it by > 3178 :catch /^Vim(\a\+):E121:/ 3179 3180You can catch all errors related to the name "nofunc" by > 3181 :catch /\<nofunc\>/ 3182 3183You can catch all Vim errors in the ":write" and ":read" commands by > 3184 :catch /^Vim(\(write\|read\)):E\d\+:/ 3185 3186You can catch all Vim errors by the pattern > 3187 :catch /^Vim\((\a\+)\)\=:E\d\+:/ 3188< 3189 *catch-text* 3190NOTE: You should never catch the error message text itself: > 3191 :catch /No such variable/ 3192only works in the English locale, but not when the user has selected 3193a different language by the |:language| command. It is however helpful to 3194cite the message text in a comment: > 3195 :catch /^Vim(\a\+):E108:/ " No such variable 3196 3197 3198IGNORING ERRORS *ignore-errors* 3199 3200You can ignore errors in a specific Vim command by catching them locally: > 3201 3202 :try 3203 : write 3204 :catch 3205 :endtry 3206 3207But you are strongly recommended NOT to use this simple form, since it could 3208catch more than you want. With the ":write" command, some autocommands could 3209be executed and cause errors not related to writing, for instance: > 3210 3211 :au BufWritePre * unlet novar 3212 3213There could even be such errors you are not responsible for as a script 3214writer: a user of your script might have defined such autocommands. You would 3215then hide the error from the user. 3216 It is much better to use > 3217 3218 :try 3219 : write 3220 :catch /^Vim(write):/ 3221 :endtry 3222 3223which only catches real write errors. So catch only what you'd like to ignore 3224intentionally. 3225 3226For a single command that does not cause execution of autocommands, you could 3227even suppress the conversion of errors to exceptions by the ":silent!" 3228command: > 3229 :silent! nunmap k 3230This works also when a try conditional is active. 3231 3232 3233CATCHING INTERRUPTS *catch-interrupt* 3234 3235When there are active try conditionals, an interrupt (CTRL-C) is converted to 3236the exception "Vim:Interrupt". You can catch it like every exception. The 3237script is not terminated, then. 3238 Example: > 3239 3240 :function! TASK1() 3241 : sleep 10 3242 :endfunction 3243 3244 :function! TASK2() 3245 : sleep 20 3246 :endfunction 3247 3248 :while 1 3249 : let command = input("Type a command: ") 3250 : try 3251 : if command == "" 3252 : continue 3253 : elseif command == "END" 3254 : break 3255 : elseif command == "TASK1" 3256 : call TASK1() 3257 : elseif command == "TASK2" 3258 : call TASK2() 3259 : else 3260 : echo "\nIllegal command:" command 3261 : continue 3262 : endif 3263 : catch /^Vim:Interrupt$/ 3264 : echo "\nCommand interrupted" 3265 : " Caught the interrupt. Continue with next prompt. 3266 : endtry 3267 :endwhile 3268 3269You can interrupt a task here by pressing CTRL-C; the script then asks for 3270a new command. If you press CTRL-C at the prompt, the script is terminated. 3271 3272For testing what happens when CTRL-C would be pressed on a specific line in 3273your script, use the debug mode and execute the |>quit| or |>interrupt| 3274command on that line. See |debug-scripts|. 3275 3276 3277CATCHING ALL *catch-all* 3278 3279The commands > 3280 3281 :catch /.*/ 3282 :catch // 3283 :catch 3284 3285catch everything, error exceptions, interrupt exceptions and exceptions 3286explicitly thrown by the |:throw| command. This is useful at the top level of 3287a script in order to catch unexpected things. 3288 Example: > 3289 3290 :try 3291 : 3292 : " do the hard work here 3293 : 3294 :catch /MyException/ 3295 : 3296 : " handle known problem 3297 : 3298 :catch /^Vim:Interrupt$/ 3299 : echo "Script interrupted" 3300 :catch /.*/ 3301 : echo "Internal error (" .. v:exception .. ")" 3302 : echo " - occurred at " .. v:throwpoint 3303 :endtry 3304 :" end of script 3305 3306Note: Catching all might catch more things than you want. Thus, you are 3307strongly encouraged to catch only for problems that you can really handle by 3308specifying a pattern argument to the ":catch". 3309 Example: Catching all could make it nearly impossible to interrupt a script 3310by pressing CTRL-C: > 3311 3312 :while 1 3313 : try 3314 : sleep 1 3315 : catch 3316 : endtry 3317 :endwhile 3318 3319 3320EXCEPTIONS AND AUTOCOMMANDS *except-autocmd* 3321 3322Exceptions may be used during execution of autocommands. Example: > 3323 3324 :autocmd User x try 3325 :autocmd User x throw "Oops!" 3326 :autocmd User x catch 3327 :autocmd User x echo v:exception 3328 :autocmd User x endtry 3329 :autocmd User x throw "Arrgh!" 3330 :autocmd User x echo "Should not be displayed" 3331 : 3332 :try 3333 : doautocmd User x 3334 :catch 3335 : echo v:exception 3336 :endtry 3337 3338This displays "Oops!" and "Arrgh!". 3339 3340 *except-autocmd-Pre* 3341For some commands, autocommands get executed before the main action of the 3342command takes place. If an exception is thrown and not caught in the sequence 3343of autocommands, the sequence and the command that caused its execution are 3344abandoned and the exception is propagated to the caller of the command. 3345 Example: > 3346 3347 :autocmd BufWritePre * throw "FAIL" 3348 :autocmd BufWritePre * echo "Should not be displayed" 3349 : 3350 :try 3351 : write 3352 :catch 3353 : echo "Caught:" v:exception "from" v:throwpoint 3354 :endtry 3355 3356Here, the ":write" command does not write the file currently being edited (as 3357you can see by checking 'modified'), since the exception from the BufWritePre 3358autocommand abandons the ":write". The exception is then caught and the 3359script displays: > 3360 3361 Caught: FAIL from BufWrite Auto commands for "*" 3362< 3363 *except-autocmd-Post* 3364For some commands, autocommands get executed after the main action of the 3365command has taken place. If this main action fails and the command is inside 3366an active try conditional, the autocommands are skipped and an error exception 3367is thrown that can be caught by the caller of the command. 3368 Example: > 3369 3370 :autocmd BufWritePost * echo "File successfully written!" 3371 : 3372 :try 3373 : write /i/m/p/o/s/s/i/b/l/e 3374 :catch 3375 : echo v:exception 3376 :endtry 3377 3378This just displays: > 3379 3380 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e) 3381 3382If you really need to execute the autocommands even when the main action 3383fails, trigger the event from the catch clause. 3384 Example: > 3385 3386 :autocmd BufWritePre * set noreadonly 3387 :autocmd BufWritePost * set readonly 3388 : 3389 :try 3390 : write /i/m/p/o/s/s/i/b/l/e 3391 :catch 3392 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e 3393 :endtry 3394< 3395You can also use ":silent!": > 3396 3397 :let x = "ok" 3398 :let v:errmsg = "" 3399 :autocmd BufWritePost * if v:errmsg != "" 3400 :autocmd BufWritePost * let x = "after fail" 3401 :autocmd BufWritePost * endif 3402 :try 3403 : silent! write /i/m/p/o/s/s/i/b/l/e 3404 :catch 3405 :endtry 3406 :echo x 3407 3408This displays "after fail". 3409 3410If the main action of the command does not fail, exceptions from the 3411autocommands will be catchable by the caller of the command: > 3412 3413 :autocmd BufWritePost * throw ":-(" 3414 :autocmd BufWritePost * echo "Should not be displayed" 3415 : 3416 :try 3417 : write 3418 :catch 3419 : echo v:exception 3420 :endtry 3421< 3422 *except-autocmd-Cmd* 3423For some commands, the normal action can be replaced by a sequence of 3424autocommands. Exceptions from that sequence will be catchable by the caller 3425of the command. 3426 Example: For the ":write" command, the caller cannot know whether the file 3427had actually been written when the exception occurred. You need to tell it in 3428some way. > 3429 3430 :if !exists("cnt") 3431 : let cnt = 0 3432 : 3433 : autocmd BufWriteCmd * if &modified 3434 : autocmd BufWriteCmd * let cnt = cnt + 1 3435 : autocmd BufWriteCmd * if cnt % 3 == 2 3436 : autocmd BufWriteCmd * throw "BufWriteCmdError" 3437 : autocmd BufWriteCmd * endif 3438 : autocmd BufWriteCmd * write | set nomodified 3439 : autocmd BufWriteCmd * if cnt % 3 == 0 3440 : autocmd BufWriteCmd * throw "BufWriteCmdError" 3441 : autocmd BufWriteCmd * endif 3442 : autocmd BufWriteCmd * echo "File successfully written!" 3443 : autocmd BufWriteCmd * endif 3444 :endif 3445 : 3446 :try 3447 : write 3448 :catch /^BufWriteCmdError$/ 3449 : if &modified 3450 : echo "Error on writing (file contents not changed)" 3451 : else 3452 : echo "Error after writing" 3453 : endif 3454 :catch /^Vim(write):/ 3455 : echo "Error on writing" 3456 :endtry 3457 3458When this script is sourced several times after making changes, it displays 3459first > 3460 File successfully written! 3461then > 3462 Error on writing (file contents not changed) 3463then > 3464 Error after writing 3465etc. 3466 3467 *except-autocmd-ill* 3468You cannot spread a try conditional over autocommands for different events. 3469The following code is ill-formed: > 3470 3471 :autocmd BufWritePre * try 3472 : 3473 :autocmd BufWritePost * catch 3474 :autocmd BufWritePost * echo v:exception 3475 :autocmd BufWritePost * endtry 3476 : 3477 :write 3478 3479 3480EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param* 3481 3482Some programming languages allow to use hierarchies of exception classes or to 3483pass additional information with the object of an exception class. You can do 3484similar things in Vim. 3485 In order to throw an exception from a hierarchy, just throw the complete 3486class name with the components separated by a colon, for instance throw the 3487string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library. 3488 When you want to pass additional information with your exception class, add 3489it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)" 3490for an error when writing "myfile". 3491 With the appropriate patterns in the ":catch" command, you can catch for 3492base classes or derived classes of your hierarchy. Additional information in 3493parentheses can be cut out from |v:exception| with the ":substitute" command. 3494 Example: > 3495 3496 :function! CheckRange(a, func) 3497 : if a:a < 0 3498 : throw "EXCEPT:MATHERR:RANGE(" .. a:func .. ")" 3499 : endif 3500 :endfunction 3501 : 3502 :function! Add(a, b) 3503 : call CheckRange(a:a, "Add") 3504 : call CheckRange(a:b, "Add") 3505 : let c = a:a + a:b 3506 : if c < 0 3507 : throw "EXCEPT:MATHERR:OVERFLOW" 3508 : endif 3509 : return c 3510 :endfunction 3511 : 3512 :function! Div(a, b) 3513 : call CheckRange(a:a, "Div") 3514 : call CheckRange(a:b, "Div") 3515 : if (a:b == 0) 3516 : throw "EXCEPT:MATHERR:ZERODIV" 3517 : endif 3518 : return a:a / a:b 3519 :endfunction 3520 : 3521 :function! Write(file) 3522 : try 3523 : execute "write" fnameescape(a:file) 3524 : catch /^Vim(write):/ 3525 : throw "EXCEPT:IO(" .. getcwd() .. ", " .. a:file .. "):WRITEERR" 3526 : endtry 3527 :endfunction 3528 : 3529 :try 3530 : 3531 : " something with arithmetic and I/O 3532 : 3533 :catch /^EXCEPT:MATHERR:RANGE/ 3534 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "") 3535 : echo "Range error in" function 3536 : 3537 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV 3538 : echo "Math error" 3539 : 3540 :catch /^EXCEPT:IO/ 3541 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "") 3542 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "") 3543 : if file !~ '^/' 3544 : let file = dir .. "/" .. file 3545 : endif 3546 : echo 'I/O error for "' .. file .. '"' 3547 : 3548 :catch /^EXCEPT/ 3549 : echo "Unspecified error" 3550 : 3551 :endtry 3552 3553The exceptions raised by Vim itself (on error or when pressing CTRL-C) use 3554a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself 3555exceptions with the "Vim" prefix; they are reserved for Vim. 3556 Vim error exceptions are parameterized with the name of the command that 3557failed, if known. See |catch-errors|. 3558 3559 3560PECULIARITIES 3561 *except-compat* 3562The exception handling concept requires that the command sequence causing the 3563exception is aborted immediately and control is transferred to finally clauses 3564and/or a catch clause. 3565 3566In the Vim script language there are cases where scripts and functions 3567continue after an error: in functions without the "abort" flag or in a command 3568after ":silent!", control flow goes to the following line, and outside 3569functions, control flow goes to the line following the outermost ":endwhile" 3570or ":endif". On the other hand, errors should be catchable as exceptions 3571(thus, requiring the immediate abortion). 3572 3573This problem has been solved by converting errors to exceptions and using 3574immediate abortion (if not suppressed by ":silent!") only when a try 3575conditional is active. This is no restriction since an (error) exception can 3576be caught only from an active try conditional. If you want an immediate 3577termination without catching the error, just use a try conditional without 3578catch clause. (You can cause cleanup code being executed before termination 3579by specifying a finally clause.) 3580 3581When no try conditional is active, the usual abortion and continuation 3582behavior is used instead of immediate abortion. This ensures compatibility of 3583scripts written for Vim 6.1 and earlier. 3584 3585However, when sourcing an existing script that does not use exception handling 3586commands (or when calling one of its functions) from inside an active try 3587conditional of a new script, you might change the control flow of the existing 3588script on error. You get the immediate abortion on error and can catch the 3589error in the new script. If however the sourced script suppresses error 3590messages by using the ":silent!" command (checking for errors by testing 3591|v:errmsg| if appropriate), its execution path is not changed. The error is 3592not converted to an exception. (See |:silent|.) So the only remaining cause 3593where this happens is for scripts that don't care about errors and produce 3594error messages. You probably won't want to use such code from your new 3595scripts. 3596 3597 *except-syntax-err* 3598Syntax errors in the exception handling commands are never caught by any of 3599the ":catch" commands of the try conditional they belong to. Its finally 3600clauses, however, is executed. 3601 Example: > 3602 3603 :try 3604 : try 3605 : throw 4711 3606 : catch /\(/ 3607 : echo "in catch with syntax error" 3608 : catch 3609 : echo "inner catch-all" 3610 : finally 3611 : echo "inner finally" 3612 : endtry 3613 :catch 3614 : echo 'outer catch-all caught "' .. v:exception .. '"' 3615 : finally 3616 : echo "outer finally" 3617 :endtry 3618 3619This displays: > 3620 inner finally 3621 outer catch-all caught "Vim(catch):E54: Unmatched \(" 3622 outer finally 3623The original exception is discarded and an error exception is raised, instead. 3624 3625 *except-single-line* 3626The ":try", ":catch", ":finally", and ":endtry" commands can be put on 3627a single line, but then syntax errors may make it difficult to recognize the 3628"catch" line, thus you better avoid this. 3629 Example: > 3630 :try | unlet! foo # | catch | endtry 3631raises an error exception for the trailing characters after the ":unlet!" 3632argument, but does not see the ":catch" and ":endtry" commands, so that the 3633error exception is discarded and the "E488: Trailing characters" message gets 3634displayed. 3635 3636 *except-several-errors* 3637When several errors appear in a single command, the first error message is 3638usually the most specific one and therefore converted to the error exception. 3639 Example: > 3640 echo novar 3641causes > 3642 E121: Undefined variable: novar 3643 E15: Invalid expression: novar 3644The value of the error exception inside try conditionals is: > 3645 Vim(echo):E121: Undefined variable: novar 3646< *except-syntax-error* 3647But when a syntax error is detected after a normal error in the same command, 3648the syntax error is used for the exception being thrown. 3649 Example: > 3650 unlet novar # 3651causes > 3652 E108: No such variable: "novar" 3653 E488: Trailing characters 3654The value of the error exception inside try conditionals is: > 3655 Vim(unlet):E488: Trailing characters 3656This is done because the syntax error might change the execution path in a way 3657not intended by the user. Example: > 3658 try 3659 try | unlet novar # | catch | echo v:exception | endtry 3660 catch /.*/ 3661 echo "outer catch:" v:exception 3662 endtry 3663This displays "outer catch: Vim(unlet):E488: Trailing characters", and then 3664a "E600: Missing :endtry" error message is given, see |except-single-line|. 3665 3666============================================================================== 36679. Examples *eval-examples* 3668 3669Printing in Binary ~ 3670> 3671 :" The function Nr2Bin() returns the binary string representation of a number. 3672 :func Nr2Bin(nr) 3673 : let n = a:nr 3674 : let r = "" 3675 : while n 3676 : let r = '01'[n % 2] .. r 3677 : let n = n / 2 3678 : endwhile 3679 : return r 3680 :endfunc 3681 3682 :" The function String2Bin() converts each character in a string to a 3683 :" binary string, separated with dashes. 3684 :func String2Bin(str) 3685 : let out = '' 3686 : for ix in range(strlen(a:str)) 3687 : let out = out .. '-' .. Nr2Bin(char2nr(a:str[ix])) 3688 : endfor 3689 : return out[1:] 3690 :endfunc 3691 3692Example of its use: > 3693 :echo Nr2Bin(32) 3694result: "100000" > 3695 :echo String2Bin("32") 3696result: "110011-110010" 3697 3698 3699Sorting lines ~ 3700 3701This example sorts lines with a specific compare function. > 3702 3703 :func SortBuffer() 3704 : let lines = getline(1, '$') 3705 : call sort(lines, function("Strcmp")) 3706 : call setline(1, lines) 3707 :endfunction 3708 3709As a one-liner: > 3710 :call setline(1, sort(getline(1, '$'), function("Strcmp"))) 3711< 3712 3713scanf() replacement ~ 3714 *sscanf* 3715There is no sscanf() function in Vim. If you need to extract parts from a 3716line, you can use matchstr() and substitute() to do it. This example shows 3717how to get the file name, line number and column number out of a line like 3718"foobar.txt, 123, 45". > 3719 :" Set up the match bit 3720 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)' 3721 :"get the part matching the whole expression 3722 :let l = matchstr(line, mx) 3723 :"get each item out of the match 3724 :let file = substitute(l, mx, '\1', '') 3725 :let lnum = substitute(l, mx, '\2', '') 3726 :let col = substitute(l, mx, '\3', '') 3727 3728The input is in the variable "line", the results in the variables "file", 3729"lnum" and "col". (idea from Michael Geddes) 3730 3731 3732getting the scriptnames in a Dictionary ~ 3733 *scriptnames-dictionary* 3734The `:scriptnames` command can be used to get a list of all script files that 3735have been sourced. There is also the `getscriptinfo()` function, but the 3736information returned is not exactly the same. In case you need to manipulate 3737the output of `scriptnames` this code can be used: > 3738 " Get the output of ":scriptnames" in the scriptnames_output variable. 3739 let scriptnames_output = '' 3740 redir => scriptnames_output 3741 silent scriptnames 3742 redir END 3743 3744 " Split the output into lines and parse each line. Add an entry to the 3745 " "scripts" dictionary. 3746 let scripts = {} 3747 for line in split(scriptnames_output, "\n") 3748 " Only do non-blank lines. 3749 if line =~ '\S' 3750 " Get the first number in the line. 3751 let nr = matchstr(line, '\d\+') 3752 " Get the file name, remove the script number " 123: ". 3753 let name = substitute(line, '.\+:\s*', '', '') 3754 " Add an item to the Dictionary 3755 let scripts[nr] = name 3756 endif 3757 endfor 3758 unlet scriptnames_output 3759 3760============================================================================== 3761The sandbox *eval-sandbox* *sandbox* *E523* 3762 3763The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and 3764'foldtext' options may be evaluated in a sandbox. This means that you are 3765protected from these expressions having nasty side effects. This gives some 3766safety for when these options are set from a modeline. It is also used when 3767the command from a tags file is executed and for CTRL-R = in the command line. 3768The sandbox is also used for the |:sandbox| command. 3769 3770 *E48* 3771These items are not allowed in the sandbox: 3772 - changing the buffer text 3773 - defining or changing mapping, autocommands, user commands 3774 - setting certain options (see |option-summary|) 3775 - setting certain v: variables (see |v:var|) *E794* 3776 - executing a shell command 3777 - reading or writing a file 3778 - jumping to another buffer or editing a file 3779 - executing Python, Perl, etc. commands 3780This is not guaranteed 100% secure, but it should block most attacks. 3781 3782 *:san* *:sandbox* 3783:san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an 3784 option that may have been set from a modeline, e.g. 3785 'foldexpr'. 3786 3787 *sandbox-option* 3788A few options contain an expression. When this expression is evaluated it may 3789have to be done in the sandbox to avoid a security risk. But the sandbox is 3790restrictive, thus this only happens when the option was set from an insecure 3791location. Insecure in this context are: 3792- sourcing a .nvimrc or .exrc in the current directory 3793- while executing in the sandbox 3794- value coming from a modeline 3795- executing a function that was defined in the sandbox 3796 3797Note that when in the sandbox and saving an option value and restoring it, the 3798option will still be marked as it was set in the sandbox. 3799 3800============================================================================== 3801Textlock *textlock* 3802 3803In a few situations it is not allowed to change the text in the buffer, jump 3804to another window and some other things that might confuse or break what Vim 3805is currently doing. This mostly applies to things that happen when Vim is 3806actually doing something else. For example, a TextYankPost autocommand cannot 3807edit the text it is yanking. 3808 3809This is not allowed when the textlock is active: 3810 - changing the buffer text 3811 - jumping to another buffer or window 3812 - editing another file 3813 - closing a window or quitting Vim 3814 - etc. 3815 3816============================================================================== 3817Vim script library *vimscript-library* 3818 3819Vim comes bundled with a Vim script library, that can be used by runtime, 3820script authors. Currently, it only includes very few functions, but it may 3821grow over time. 3822 3823 *dist#vim* 3824The functions make use of the autoloaded prefix "dist#vim". 3825 3826The following functions are available: 3827 3828dist#vim#IsSafeExecutable(filetype, executable) ~ 3829 3830This function takes a filetype and an executable and checks whether it is safe 3831to execute the given executable. For security reasons users may not want to 3832have Vim execute random executables or may have forbidden to do so for 3833specific filetypes by setting the "<filetype>_exec" variable (|plugin_exec|). 3834 3835It returns |TRUE| or |FALSE| to indicate whether the plugin should run the given 3836executable. It takes the following arguments: 3837 3838 argument type ~ 3839 3840 filetype string 3841 executable string 3842 3843============================================================================== 3844Command-line expressions highlighting *expr-highlight* 3845 3846Expressions entered by the user in |i_CTRL-R_=|, |c_CTRL-\_e|, |quote=| are 3847highlighted by the built-in expressions parser. It uses highlight groups 3848described in the table below, which may be overridden by colorschemes. 3849 *hl-NvimInvalid* 3850Besides the "Nvim"-prefixed highlight groups described below, there are 3851"NvimInvalid"-prefixed highlight groups which have the same meaning but 3852indicate that the token contains an error or that an error occurred just 3853before it. They have mostly the same hierarchy, except that (by default) in 3854place of any non-Nvim-prefixed group NvimInvalid linking to `Error` is used 3855and some other intermediate groups are present. 3856 3857Group Default link Colored expression ~ 3858*hl-NvimInternalError* None, red/red Parser bug 3859 3860*hl-NvimAssignment* Operator Generic assignment 3861*hl-NvimPlainAssignment* NvimAssignment `=` in |:let| 3862*hl-NvimAugmentedAssignment* NvimAssignment Generic, `+=`/`-=`/`.=` 3863*hl-NvimAssignmentWithAddition* NvimAugmentedAssignment `+=` in |:let+=| 3864*hl-NvimAssignmentWithSubtraction* NvimAugmentedAssignment `-=` in |:let-=| 3865*hl-NvimAssignmentWithConcatenation* NvimAugmentedAssignment `.=` in |:let.=| 3866 3867*hl-NvimOperator* Operator Generic operator 3868 3869*hl-NvimUnaryOperator* NvimOperator Generic unary op 3870*hl-NvimUnaryPlus* NvimUnaryOperator |expr-unary-+| 3871*hl-NvimUnaryMinus* NvimUnaryOperator |expr-unary--| 3872*hl-NvimNot* NvimUnaryOperator |expr-!| 3873 3874*hl-NvimBinaryOperator* NvimOperator Generic binary op 3875*hl-NvimComparison* NvimBinaryOperator Any |expr4| operator 3876*hl-NvimComparisonModifier* NvimComparison `#`/`?` near |expr4| op 3877*hl-NvimBinaryPlus* NvimBinaryOperator |expr-+| 3878*hl-NvimBinaryMinus* NvimBinaryOperator |expr--| 3879*hl-NvimConcat* NvimBinaryOperator |expr-.| 3880*hl-NvimConcatOrSubscript* NvimConcat |expr-.| or |expr-entry| 3881*hl-NvimOr* NvimBinaryOperator |expr-barbar| 3882*hl-NvimAnd* NvimBinaryOperator |expr-&&| 3883*hl-NvimMultiplication* NvimBinaryOperator |expr-star| 3884*hl-NvimDivision* NvimBinaryOperator |expr-/| 3885*hl-NvimMod* NvimBinaryOperator |expr-%| 3886 3887*hl-NvimTernary* NvimOperator `?` in |expr1| 3888*hl-NvimTernaryColon* NvimTernary `:` in |expr1| 3889 3890*hl-NvimParenthesis* Delimiter Generic bracket 3891*hl-NvimLambda* NvimParenthesis `{`/`}` in |lambda| 3892*hl-NvimNestingParenthesis* NvimParenthesis `(`/`)` in |expr-nesting| 3893*hl-NvimCallingParenthesis* NvimParenthesis `(`/`)` in |expr-function| 3894 3895*hl-NvimSubscript* NvimParenthesis Generic subscript 3896*hl-NvimSubscriptBracket* NvimSubscript `[`/`]` in |expr-[]| 3897*hl-NvimSubscriptColon* NvimSubscript `:` in |expr-[:]| 3898*hl-NvimCurly* NvimSubscript `{`/`}` in 3899 |curly-braces-names| 3900 3901*hl-NvimContainer* NvimParenthesis Generic container 3902*hl-NvimDict* NvimContainer `{`/`}` in |dict| literal 3903*hl-NvimList* NvimContainer `[`/`]` in |list| literal 3904 3905*hl-NvimIdentifier* Identifier Generic identifier 3906*hl-NvimIdentifierScope* NvimIdentifier Namespace: letter 3907 before `:` in 3908 |internal-variables| 3909*hl-NvimIdentifierScopeDelimiter* NvimIdentifier `:` after namespace 3910 letter 3911*hl-NvimIdentifierName* NvimIdentifier Rest of the ident 3912*hl-NvimIdentifierKey* NvimIdentifier Identifier after 3913 |expr-entry| 3914 3915*hl-NvimColon* Delimiter `:` in |dict| literal 3916*hl-NvimComma* Delimiter `,` in |dict| or |list| 3917 literal or 3918 |expr-function| 3919*hl-NvimArrow* Delimiter `->` in |lambda| 3920 3921*hl-NvimRegister* SpecialChar |expr-register| 3922*hl-NvimNumber* Number Non-prefix digits 3923 in integer 3924 |expr-number| 3925*hl-NvimNumberPrefix* Type `0` for |octal-number| 3926 `0x` for |hex-number| 3927 `0b` for |binary-number| 3928*hl-NvimFloat* NvimNumber Floating-point 3929 number 3930 3931*hl-NvimOptionSigil* Type `&` in |expr-option| 3932*hl-NvimOptionScope* NvimIdentifierScope Option scope if any 3933*hl-NvimOptionScopeDelimiter* NvimIdentifierScopeDelimiter 3934 `:` after option scope 3935*hl-NvimOptionName* NvimIdentifier Option name 3936 3937*hl-NvimEnvironmentSigil* NvimOptionSigil `$` in |expr-env| 3938*hl-NvimEnvironmentName* NvimIdentifier Env variable name 3939 3940*hl-NvimString* String Generic string 3941*hl-NvimStringBody* NvimString Generic string 3942 literal body 3943*hl-NvimStringQuote* NvimString Generic string quote 3944*hl-NvimStringSpecial* SpecialChar Generic string 3945 non-literal body 3946 3947*hl-NvimSingleQuote* NvimStringQuote `'` in |expr-'| 3948*hl-NvimSingleQuotedBody* NvimStringBody Literal part of 3949 |expr-'| string body 3950*hl-NvimSingleQuotedQuote* NvimStringSpecial `''` inside |expr-'| 3951 string body 3952 3953*hl-NvimDoubleQuote* NvimStringQuote `"` in |expr-quote| 3954*hl-NvimDoubleQuotedBody* NvimStringBody Literal part of 3955 |expr-quote| body 3956*hl-NvimDoubleQuotedEscape* NvimStringSpecial Valid |expr-quote| 3957 escape sequence 3958*hl-NvimDoubleQuotedUnknownEscape* NvimInvalidValue Unrecognized 3959 |expr-quote| escape 3960 sequence 3961 3962 vim:tw=78:ts=8:noet:ft=help:norl: