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