eval.txt (198186B)
1 *eval.txt* For Vim version 9.2. Last change: 2026 Sep 30 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7 Expression evaluation *expression* *expr* *E15* *eval* 8 *E1002* 9 Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|. 10 11 Note: Expression evaluation can be disabled at compile time. If this has been 12 done, the features in this document are not available. See |+eval| and 13 |no-eval-feature|. 14 15 This file is mainly about the backwards compatible (legacy) Vim script. For 16 specifics of Vim9 script, which can execute much faster, supports type 17 checking and much more, see |vim9.txt|. Where the syntax or semantics differ 18 a remark is given. 19 20 1. Variables |variables| 21 1.1 Variable types 22 1.2 Function references |Funcref| 23 1.3 Lists |Lists| 24 1.4 Tuples |Tuples| 25 1.5 Dictionaries |Dictionaries| 26 1.6 Blobs |Blobs| 27 1.7 More about variables |more-variables| 28 2. Expression syntax |expression-syntax| 29 3. Internal variable |internal-variables| 30 4. Builtin Functions |functions| 31 5. Defining functions |user-functions| 32 6. Curly braces names |curly-braces-names| 33 7. Commands |expression-commands| 34 8. Exception handling |exception-handling| 35 9. Examples |eval-examples| 36 10. Vim script version |vimscript-version| 37 11. No +eval feature |no-eval-feature| 38 12. The sandbox |eval-sandbox| 39 13. Textlock |textlock| 40 14. Vim script library |vim-script-library| 41 15. Clipboard providers |clipboard-providers| 42 43 Testing support is documented in |testing.txt|. 44 Profiling is documented at |profiling|. 45 46 ============================================================================== 47 1. Variables *variables* 48 49 1.1 Variable types ~ 50 *E712* *E896* *E897* *E899* *E1098* 51 *E1107* *E1135* *E1138* *E1523* 52 There are eleven types of variables: 53 54 *Number* *Integer* 55 Number A 32 or 64 bit signed number. |expr-number| 56 The number of bits is available in |v:numbersize|. 57 Examples: -123 0x10 0177 0o177 0b1011 58 59 Float A floating point number. |floating-point-format| *Float* 60 Examples: 123.456 1.15e-6 -1.1e3 61 62 String A NUL terminated string of 8-bit unsigned characters (bytes). 63 |expr-string| Examples: "ab\txx\"--" 'x-z''a,c' 64 65 List An ordered sequence of items, see |List| for details. 66 Example: [1, 2, ['a', 'b']] 67 68 Tuple An ordered immutable sequence of items, see |Tuple| for 69 details. 70 Example: (1, 2, ('a', 'b')) 71 72 Dictionary An associative, unordered array: Each entry has a key and a 73 value. |Dictionary| 74 Examples: 75 {'blue': "#0000ff", 'red': "#ff0000"} 76 #{blue: "#0000ff", red: "#ff0000"} 77 78 Funcref A reference to a function |Funcref|. 79 Example: function("strlen") 80 It can be bound to a dictionary and arguments, it then works 81 like a Partial. 82 Example: function("Callback", [arg], myDict) 83 84 Special |v:false|, |v:true|, |v:none| and |v:null|. *Special* 85 86 Job Used for a job, see |job_start()|. *Job* *Jobs* 87 88 Channel Used for a channel, see |ch_open()|. *Channel* *Channels* 89 90 Blob Binary Large Object. Stores any sequence of bytes. See |Blob| 91 for details 92 Example: 0zFF00ED015DAF 93 0z is an empty Blob. 94 95 The Number and String types are converted automatically, depending on how they 96 are used. 97 98 Conversion from a Number to a String is by making the ASCII representation of 99 the Number. Examples: 100 Number 123 --> String "123" ~ 101 Number 0 --> String "0" ~ 102 Number -1 --> String "-1" ~ 103 *octal* 104 Conversion from a String to a Number only happens in legacy Vim script, not in 105 Vim9 script. It is done by converting the first digits to a number. 106 Hexadecimal "0xf9", Octal "017" or "0o17", and Binary "0b10" 107 numbers are recognized 108 NOTE: when using |Vim9| script or |scriptversion-4| octal with a leading "0" 109 is not recognized. The 0o notation requires patch 8.2.0886. 110 If the String doesn't start with digits, the result is zero. 111 Examples: 112 String "456" --> Number 456 ~ 113 String "6bar" --> Number 6 ~ 114 String "foo" --> Number 0 ~ 115 String "0xf1" --> Number 241 ~ 116 String "0100" --> Number 64 ~ 117 String "0o100" --> Number 64 ~ 118 String "0b101" --> Number 5 ~ 119 String "-8" --> Number -8 ~ 120 String "+8" --> Number 0 ~ 121 122 To force conversion from String to Number, add zero to it: > 123 :echo "0100" + 0 124 < 64 ~ 125 126 To avoid a leading zero to cause octal conversion, or for using a different 127 base, use |str2nr()|. 128 129 *TRUE* *FALSE* *Boolean* 130 For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE. 131 You can also use |v:false| and |v:true|, in Vim9 script |false| and |true|. 132 When TRUE is returned from a function it is the Number one, FALSE is the 133 number zero. 134 135 Note that in the command: > 136 :if "foo" 137 :" NOT executed 138 "foo" is converted to 0, which means FALSE. If the string starts with a 139 non-zero number it means TRUE: > 140 :if "8foo" 141 :" executed 142 To test for a non-empty string, use empty(): > 143 :if !empty("foo") 144 145 < *falsy* *truthy* 146 An expression can be used as a condition, ignoring the type and only using 147 whether the value is "sort of true" or "sort of false". Falsy is: 148 the number zero 149 empty string, blob, list or dictionary 150 Other values are truthy. Examples: 151 0 falsy 152 1 truthy 153 -1 truthy 154 0.0 falsy 155 0.1 truthy 156 '' falsy 157 'x' truthy 158 [] falsy 159 [0] truthy 160 {} falsy 161 #{x: 1} truthy 162 0z falsy 163 0z00 truthy 164 165 *non-zero-arg* 166 Function arguments often behave slightly different from |TRUE|: If the 167 argument is present and it evaluates to a non-zero Number, |v:true| or a 168 non-empty String, then the value is considered to be TRUE. 169 Note that " " and "0" are also non-empty strings, thus considered to be TRUE. 170 A List, Dictionary or Float is not a Number or String, thus evaluate to FALSE. 171 172 *E611* *E745* *E728* *E703* *E729* *E730* *E731* *E908* *E910* 173 *E913* *E974* *E975* *E976* *E1320* *E1322* *E1324* *E1520* 174 *E1522* 175 |List|, |Tuple|, |Dictionary|, |Funcref|, |Job|, |Channel|, |Blob|, |Class| 176 and |object| types are not automatically converted. 177 178 *E805* *E806* *E808* 179 When mixing Number and Float the Number is converted to Float. Otherwise 180 there is no automatic conversion of Float. You can use str2float() for String 181 to Float, printf() for Float to String and float2nr() for Float to Number. 182 183 *E362* *E891* *E892* *E893* *E894* 184 *E907* *E911* *E914* *E1521* 185 When comparing with a Float, or when a builtin function expects a Float, a 186 Number can be used instead. Aside from `v:null`, anything else gives an 187 error. Examples: 188 >vim 189 let f = 8.0 190 let Fr = function("abs") 191 echo f == 8 |" 1 192 echo f == v:null |" 0 193 echo f == v:false |" E362: Using a boolean value as a Float 194 echo sort([f, Fr], "f") |" E891: Using a funcref as a Float 195 echo f == "8" |" E892: Using a String as a Float 196 echo sort([f, []], "f") |" E893: Using a List as a Float 197 echo sort([f, {}], "f") |" E894: Using a Dictionary as a Float 198 echo f == v:none |" E907: Using a special value as a Float 199 echo f == (8, 0) |" E1521: Can only compare Tuple with Tuple 200 < 201 Note: Using a `job` gives E911 and using a `channel` gives E914. 202 In Vim9 script, all the `==` comparison equivalents give |E1072|. 203 204 *no-type-checking* 205 Changing the type of a variable is allowed in legacy Vim script. In Vim9 206 script, type mismatch error |E1012| is given when attempting to change the 207 type of a variable. 208 209 210 1.2 Function references ~ 211 *Funcref* *E695* *E718* *E1192* 212 A Funcref variable is obtained with the |function()| function, the |funcref()| 213 function, (in |Vim9| script) the name of a function, or created with the 214 lambda expression |expr-lambda|. It can be used in an expression in the place 215 of a function name, before the parenthesis around the arguments, to invoke the 216 function it refers to. Example in |Vim9| script: > 217 218 :var Fn = MyFunc 219 :echo Fn() 220 221 Legacy script: > 222 :let Fn = function("MyFunc") 223 :echo Fn() 224 < *E704* *E705* *E707* 225 A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You 226 can use "g:" but the following name must still start with a capital. You 227 cannot have both a Funcref variable and a function with the same name. 228 229 A special case is defining a function and directly assigning its Funcref to a 230 Dictionary entry. Example: > 231 :function dict.init() dict 232 : let self.val = 0 233 :endfunction 234 235 The key of the Dictionary can start with a lower case letter. The actual 236 function name is not used here. Also see |numbered-function|. 237 238 A Funcref can also be used with the |:call| command: > 239 :call Fn() 240 :call dict.init() 241 242 The name of the referenced function can be obtained with |string()|. > 243 :let func = string(Fn) 244 245 You can use |call()| to invoke a Funcref and use a list variable for the 246 arguments: > 247 :let r = call(Fn, mylist) 248 < 249 *Partial* 250 A Funcref optionally binds a Dictionary and/or arguments. This is also called 251 a Partial. This is created by passing the Dictionary and/or arguments to 252 function() or funcref(). When calling the function the Dictionary and/or 253 arguments will be passed to the function. Example: > 254 255 let Cb = function('Callback', ['foo'], myDict) 256 call Cb('bar') 257 258 This will invoke the function as if using: > 259 call myDict.Callback('foo', 'bar') 260 261 This is very useful when passing a function around, e.g. in the arguments of 262 |ch_open()|. 263 264 Note that binding a function to a Dictionary also happens when the function is 265 a member of the Dictionary: > 266 267 let myDict.myFunction = MyFunction 268 call myDict.myFunction() 269 270 Here MyFunction() will get myDict passed as "self". This happens when the 271 "myFunction" member is accessed. When making assigning "myFunction" to 272 otherDict and calling it, it will be bound to otherDict: > 273 274 let otherDict.myFunction = myDict.myFunction 275 call otherDict.myFunction() 276 277 Now "self" will be "otherDict". But when the dictionary was bound explicitly 278 this won't happen: > 279 280 let myDict.myFunction = function(MyFunction, myDict) 281 let otherDict.myFunction = myDict.myFunction 282 call otherDict.myFunction() 283 284 Here "self" will be "myDict", because it was bound explicitly. 285 286 287 1.3 Lists ~ 288 *list* *List* *Lists* *E686* 289 A List is an ordered sequence of items. An item can be of any type. Items 290 can be accessed by their index number. Items can be added and removed at any 291 position in the sequence. 292 293 294 List creation ~ 295 *E696* *E697* 296 A List is created with a comma-separated sequence of items in square brackets. 297 Examples: > 298 :let mylist = [1, "two", 3, "four"] 299 :let emptylist = [] 300 301 An item can be any expression. Using a List for an item creates a 302 List of Lists: > 303 :let nestlist = [[11, 12], [21, 22], [31, 32]] 304 305 An extra comma after the last item is ignored. 306 307 308 List index ~ 309 *list-index* *E684* 310 An item in the List can be accessed by putting the index in square brackets 311 after the List. Indexes are zero-based, thus the first item has index zero. > 312 :let item = mylist[0] " get the first item: 1 313 :let item = mylist[2] " get the third item: 3 314 315 When the resulting item is a list this can be repeated: > 316 :let item = nestlist[0][1] " get the first list, second item: 12 317 < 318 A negative index is counted from the end. Index -1 refers to the last item in 319 the List, -2 to the last but one item, etc. > 320 :let last = mylist[-1] " get the last item: "four" 321 322 To avoid an error for an invalid index use the |get()| function. When an item 323 is not available it returns zero or the default value you specify: > 324 :echo get(mylist, idx) 325 :echo get(mylist, idx, "NONE") 326 327 328 List concatenation ~ 329 *list-concatenation* 330 Two lists can be concatenated with the "+" operator: > 331 :let longlist = mylist + [5, 6] 332 :let longlist = [5, 6] + mylist 333 To prepend or append an item, turn it into a list by putting [] around it. 334 335 A list can be concatenated with another one in-place using |:let+=| or 336 |extend()|: > 337 :let mylist += [7, 8] 338 :call extend(mylist, [7, 8]) 339 < 340 See |list-modification| below for more about changing a list in-place. 341 342 343 Sublist ~ 344 *sublist* 345 A part of the List can be obtained by specifying the first and last index, 346 separated by a colon in square brackets: > 347 :let shortlist = mylist[2:-1] " get List [3, "four"] 348 349 Omitting the first index is similar to zero. Omitting the last index is 350 similar to -1. > 351 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"] 352 :let shortlist = mylist[2:2] " List with one item: [3] 353 :let otherlist = mylist[:] " make a copy of the List 354 355 Notice that the last index is inclusive. If you prefer using an exclusive 356 index use the |slice()| function. 357 358 If the first index is beyond the last item of the List or the last index is 359 before the first item, the result is an empty list. There is no error 360 message. 361 362 If the last index is equal to or greater than the length of the list the 363 length minus one is used: > 364 :let mylist = [0, 1, 2, 3] 365 :echo mylist[2:8] " result: [2, 3] 366 367 NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for 368 using a single letter variable before the ":". Insert a space when needed: 369 mylist[s : e]. 370 371 372 List identity ~ 373 *list-identity* 374 When variable "aa" is a list and you assign it to another variable "bb", both 375 variables refer to the same list. Thus changing the list "aa" will also 376 change "bb": > 377 :let aa = [1, 2, 3] 378 :let bb = aa 379 :call add(aa, 4) 380 :echo bb 381 < [1, 2, 3, 4] 382 383 Making a copy of a list is done with the |copy()| function. Using [:] also 384 works, as explained above. This creates a shallow copy of the list: Changing 385 a list item in the list will also change the item in the copied list: > 386 :let aa = [[1, 'a'], 2, 3] 387 :let bb = copy(aa) 388 :call add(aa, 4) 389 :let aa[0][1] = 'aaa' 390 :echo aa 391 < [[1, aaa], 2, 3, 4] > 392 :echo bb 393 < [[1, aaa], 2, 3] 394 395 To make a completely independent list use |deepcopy()|. This also makes a 396 copy of the values in the list, recursively. Up to a hundred levels deep. 397 398 The operator "is" can be used to check if two variables refer to the same 399 List. "isnot" does the opposite. In contrast "==" compares if two lists have 400 the same value. > 401 :let alist = [1, 2, 3] 402 :let blist = [1, 2, 3] 403 :echo alist is blist 404 < 0 > 405 :echo alist == blist 406 < 1 407 408 Note about comparing lists: Two lists are considered equal if they have the 409 same length and all items compare equal, as with using "==". There is one 410 exception: When comparing a number with a string they are considered 411 different. There is no automatic type conversion, as with using "==" on 412 variables. Example: > 413 echo 4 == "4" 414 < 1 > 415 echo [4] == ["4"] 416 < 0 417 418 Thus comparing Lists is more strict than comparing numbers and strings. You 419 can compare simple values this way too by putting them in a list: > 420 421 :let a = 5 422 :let b = "5" 423 :echo a == b 424 < 1 > 425 :echo [a] == [b] 426 < 0 427 428 429 List unpack ~ 430 431 To unpack the items in a list to individual variables, put the variables in 432 square brackets, like list items: > 433 :let [var1, var2] = mylist 434 435 When the number of variables does not match the number of items in the list 436 this produces an error. To handle any extra items from the list append ";" 437 and a variable name: > 438 :let [var1, var2; rest] = mylist 439 440 This works like: > 441 :let var1 = mylist[0] 442 :let var2 = mylist[1] 443 :let rest = mylist[2:] 444 445 Except that there is no error if there are only two items. "rest" will be an 446 empty list then. 447 448 449 List modification ~ 450 *list-modification* 451 To change a specific item of a list use |:let| this way: > 452 :let list[4] = "four" 453 :let listlist[0][3] = item 454 455 To change part of a list you can specify the first and last item to be 456 modified. The value must at least have the number of items in the range: > 457 :let list[3:5] = [3, 4, 5] 458 459 To add items to a List in-place, you can use |:let+=| (|list-concatenation|): > 460 :let listA = [1, 2] 461 :let listA += [3, 4] 462 < 463 When two variables refer to the same List, changing one List in-place will 464 cause the referenced List to be changed in-place: > 465 :let listA = [1, 2] 466 :let listB = listA 467 :let listB += [3, 4] 468 :echo listA 469 [1, 2, 3, 4] 470 < 471 Adding and removing items from a list is done with functions. Here are a few 472 examples: > 473 :call insert(list, 'a') " prepend item 'a' 474 :call insert(list, 'a', 3) " insert item 'a' before list[3] 475 :call add(list, "new") " append String item 476 :call add(list, [1, 2]) " append a List as one new item 477 :call extend(list, [1, 2]) " extend the list with two more items 478 :let i = remove(list, 3) " remove item 3 479 :unlet list[3] " idem 480 :let l = remove(list, 3, -1) " remove items 3 to last item 481 :unlet list[3 : ] " idem 482 :call filter(list, 'v:val !~ "x"') " remove items with an 'x' 483 484 Changing the order of items in a list: > 485 :call sort(list) " sort a list alphabetically 486 :call reverse(list) " reverse the order of items 487 :call uniq(sort(list)) " sort and remove duplicates 488 489 In a Vim9 script or a def method, a new item can be appended to a List by 490 using the list length as the index: > 491 vim9script 492 var l: list<string> 493 l[0] = 'a' 494 l[1] = 'b' 495 < 496 For loop ~ 497 498 The |:for| loop executes commands for each item in a List, Tuple, String or 499 Blob. A variable is set to each item in sequence. Example with a List: > 500 :for item in mylist 501 : call Doit(item) 502 :endfor 503 504 This works like: > 505 :let index = 0 506 :while index < len(mylist) 507 : let item = mylist[index] 508 : :call Doit(item) 509 : let index = index + 1 510 :endwhile 511 512 If all you want to do is modify each item in the list then the |map()| 513 function will be a simpler method than a for loop. 514 515 Just like the |:let| command, |:for| also accepts a list of variables. This 516 requires the argument to be a List of Lists. > 517 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]] 518 : call Doit(lnum, col) 519 :endfor 520 521 This works like a |:let| command is done for each list item. Again, the types 522 must remain the same to avoid an error. 523 524 It is also possible to put remaining items in a List variable: > 525 :for [i, j; rest] in listlist 526 : call Doit(i, j) 527 : if !empty(rest) 528 : echo "remainder: " .. string(rest) 529 : endif 530 :endfor 531 532 For a Tuple one tuple item at a time is used. 533 534 For a Blob one byte at a time is used. 535 536 For a String one character, including any composing characters, is used as a 537 String. Example: > 538 for c in text 539 echo 'This character is ' .. c 540 endfor 541 542 543 List functions ~ 544 *E714* 545 Functions that are useful with a List: > 546 :let r = call(funcname, list) " call a function with argument list 547 :if empty(list) " check if list is empty 548 :let l = len(list) " number of items in list 549 :let big = max(list) " maximum value in list 550 :let small = min(list) " minimum value in list 551 :let xs = count(list, 'x') " count nr times 'x' appears in list 552 :let i = index(list, 'x') " index of first 'x' in list 553 :let lines = getline(1, 10) " get ten text lines from buffer 554 :call append('$', lines) " append text lines in buffer 555 :let list = split("a b c") " create list from items in a string 556 :let string = join(list, ', ') " create string from list items 557 :let s = string(list) " String representation of list 558 :call map(list, '">> " .. v:val') " prepend ">> " to each item 559 560 Don't forget that a combination of features can make things simple. For 561 example, to add up all the numbers in a list: > 562 :exe 'let sum = ' .. join(nrlist, '+') 563 564 1.4 Tuples ~ 565 *tuple* *Tuple* *Tuples* 566 *E1532* *E1533* 567 A Tuple is an ordered sequence of items. An item can be of any type. Items 568 can be accessed by their index number. A Tuple is immutable. 569 570 A Tuple is similar to a List but uses less memory and provides O(1) lookup 571 time for an item. 572 573 Tuple creation ~ 574 *E1526* *E1527* 575 A Tuple is created with a comma-separated sequence of items in parentheses. 576 Examples: > 577 :let mytuple = (1, "two", 3, "four") 578 :let tuple = (5,) 579 :let emptytuple = () 580 581 An item can be any expression. If there is only one item in the tuple, then 582 the item must be followed by a comma. 583 584 Using a Tuple for an item creates a Tuple of Tuples: > 585 :let nesttuple = ((11, 12), (21, 22), (31, 32)) 586 587 588 Tuple index ~ 589 *tuple-index* *E1519* 590 An item in the Tuple can be accessed by putting the index in square brackets 591 after the Tuple. Indexes are zero-based, thus the first item has index zero. 592 > 593 :let item = mytuple[0] " get the first item: 1 594 :let item = mytuple[2] " get the third item: 3 595 596 When the resulting item is a tuple this can be repeated: > 597 :let item = nesttuple[0][1] " get the first tuple, second item: 12 598 < 599 A negative index is counted from the end. Index -1 refers to the last item in 600 the Tuple, -2 to the last but one item, etc. > 601 :let last = mytuple[-1] " get the last item: "four" 602 603 To avoid an error for an invalid index use the |get()| function. When an item 604 is not available it returns zero or the default value you specify: > 605 :echo get(mytuple, idx) 606 :echo get(mytuple, idx, "NONE") 607 608 609 Tuple modification ~ 610 *tuple-modification* 611 A tuple is immutable and items cannot be added or removed from a tuple. But 612 List and Dict items within a tuple can be modified: > 613 :let tuple = (1, [2, 3], {'a': 4}) 614 :let tuple[1][0] = 10 615 :let tuple[2]['a'] = 20 616 617 618 Tuple concatenation ~ 619 *tuple-concatenation* 620 Two tuples can be concatenated with the "+" operator: > 621 :let longtuple = mytuple + (5, 6) 622 :let longtuple = (5, 6) + mytuple 623 To prepend or append an item, turn it into a tuple by putting () around it. 624 The item must be followed by a comma. 625 626 *E1540* 627 Two variadic tuples with same item type can be concatenated but with different 628 item types cannot be concatenated. Examples: > 629 var a: tuple<...list<number>> = (1, 2) 630 var b: tuple<...list<string>> = ('a', 'b') 631 echo a + b # not allowed 632 633 var a: tuple<number, number> = (1, 2) 634 var b: tuple<...list<string>> = ('a', 'b') 635 echo a + b # allowed 636 637 var a: tuple<...list<number>> = (1, 2) 638 var b: tuple<number, number> = (3, 4) 639 echo a + b # not allowed 640 641 var a: tuple<...list<number>> = (1, 2) 642 var b: tuple<number, ...list<number>> = (3, 4) 643 echo a + b # not allowed 644 < 645 Note that a tuple is immutable and items cannot be added or removed from a 646 tuple. 647 648 649 Subtuple ~ 650 *subtuple* 651 A part of the Tuple can be obtained by specifying the first and last index, 652 separated by a colon in square brackets: > 653 :let shorttuple = mytuple[2:-1] " get Tuple (3, "four") 654 655 Omitting the first index is similar to zero. Omitting the last index is 656 similar to -1. > 657 :let endtuple = mytuple[2:] " from item 2 to the end: (3, "four") 658 :let shorttuple = mytuple[2:2] " Tuple with one item: (3,) 659 :let othertuple = mytuple[:] " make a copy of the Tuple 660 661 Notice that the last index is inclusive. If you prefer using an exclusive 662 index, use the |slice()| function. 663 664 If the first index is beyond the last item of the Tuple or the last index is 665 before the first item, the result is an empty tuple. There is no error 666 message. 667 668 If the last index is equal to or greater than the length of the tuple, the 669 length minus one is used: > 670 :let mytuple = (0, 1, 2, 3) 671 :echo mytuple[2:8] " result: (2, 3) 672 673 NOTE: mytuple[s:e] means using the variable "s:e" as index. Watch out for 674 using a single letter variable before the ":". Insert a space when needed: 675 mytuple[s : e]. 676 677 678 Tuple identity ~ 679 *tuple-identity* 680 When variable "aa" is a tuple and you assign it to another variable "bb", both 681 variables refer to the same tuple: > 682 :let aa = (1, 2, 3) 683 :let bb = aa 684 < 685 686 Making a copy of a tuple is done with the |copy()| function. Using [:] also 687 works, as explained above. This creates a shallow copy of the tuple: For 688 example, changing a list item in the tuple will also change the item in the 689 copied tuple: > 690 :let aa = ([1, 'a'], 2, 3) 691 :let bb = copy(aa) 692 :let aa[0][1] = 'aaa' 693 :echo aa 694 < ([1, aaa], 2, 3) > 695 :echo bb 696 < ([1, aaa], 2, 3) 697 698 To make a completely independent tuple, use |deepcopy()|. This also makes a 699 copy of the values in the tuple, recursively. Up to a hundred levels deep. 700 701 The operator "is" can be used to check if two variables refer to the same 702 Tuple. "isnot" does the opposite. In contrast, "==" compares if two tuples 703 have the same value. > 704 :let atuple = (1, 2, 3) 705 :let btuple = (1, 2, 3) 706 :echo atuple is btuple 707 < 0 > 708 :echo atuple == btuple 709 < 1 710 711 Note about comparing tuples: Two tuples are considered equal if they have the 712 same length and all items compare equal, as with using "==". There is one 713 exception: When comparing a number with a string they are considered 714 different. There is no automatic type conversion, as with using "==" on 715 variables. Example: > 716 echo 4 == "4" 717 < 1 > 718 echo (4,) == ("4",) 719 < 0 720 721 Thus comparing Tuples is more strict than comparing numbers and strings. You 722 can compare simple values this way too by putting them in a tuple: > 723 724 :let a = 5 725 :let b = "5" 726 :echo a == b 727 < 1 > 728 :echo (a,) == (b,) 729 < 0 730 731 732 Tuple unpack ~ 733 734 To unpack the items in a tuple to individual variables, put the variables in 735 square brackets, like list items: > 736 :let [var1, var2] = mytuple 737 738 When the number of variables does not match the number of items in the tuple 739 this produces an error. To handle any extra items from the tuple, append ";" 740 and a variable name (which will then be of type tuple): > 741 :let [var1, var2; rest] = mytuple 742 743 This works like: > 744 :let var1 = mytuple[0] 745 :let var2 = mytuple[1] 746 :let rest = mytuple[2:] 747 748 Except that there is no error if there are only two items. "rest" will be an 749 empty tuple then. 750 751 752 Tuple functions ~ 753 *E1536* 754 Functions that are useful with a Tuple: > 755 :let xs = count(tuple, 'x') " count number of 'x's in tuple 756 :if empty(tuple) " check if tuple is empty 757 :let i = index(tuple, 'x') " index of first 'x' in tuple 758 :let l = items(tuple) " list of items in a tuple 759 :let string = join(tuple, ', ') " create string from tuple items 760 :let l = len(tuple) " number of items in tuple 761 :let big = max(tuple) " maximum value in tuple 762 :let small = min(tuple) " minimum value in tuple 763 :let r = repeat(tuple, n) " repeat a tuple n times 764 :let r = reverse(tuple) " reverse a tuple 765 :let s = slice(tuple, n1, n2) " slice a tuple 766 :let s = string(tuple) " String representation of tuple 767 :let l = tuple2list(tuple) " convert a tuple to list 768 :let t = list2tuple(list) " convert a list to tuple 769 < 770 *E1524* 771 A tuple cannot be used with the |map()|, |mapnew()| and |filter()| functions. 772 773 1.5 Dictionaries ~ 774 *dict* *Dict* *Dictionaries* *Dictionary* 775 A Dictionary is an associative array: Each entry has a key and a value. The 776 entry can be located with the key. The entries are stored without a specific 777 ordering. 778 779 780 Dictionary creation ~ 781 *E720* *E721* *E722* *E723* 782 A Dictionary is created with a comma-separated sequence of entries in curly 783 braces. Each entry has a key and a value, separated by a colon. Each key can 784 only appear once. Examples: > 785 :let mydict = {'one': 1, 'two': 2, 'three': 3} 786 :let emptydict = {} 787 < *E713* *E716* *E717* 788 A key is always a String. You can use a Number, it will be converted to a 789 String automatically. Thus the String '4' and the number 4 will find the same 790 entry. Note that the String '04' and the Number 04 are different, since the 791 Number will be converted to the String '4', leading zeros are dropped. The 792 empty string can also be used as a key. 793 794 In |Vim9| script a literal key can be used if it consists only of alphanumeric 795 characters, underscore and dash, see |vim9-literal-dict|. 796 *literal-Dict* *#{}* 797 To avoid having to put quotes around every key the #{} form can be used in 798 legacy script. This does require the key to consist only of ASCII letters, 799 digits, '-' and '_'. Example: > 800 :let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3} 801 Note that 333 here is the string "333". Empty keys are not possible with #{}. 802 In |Vim9| script the #{} form cannot be used because it can be confused with 803 the start of a comment. 804 805 A value can be any expression. Using a Dictionary for a value creates a 806 nested Dictionary: > 807 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}} 808 809 An extra comma after the last entry is ignored. 810 811 812 Accessing entries ~ 813 814 The normal way to access an entry is by putting the key in square brackets: > 815 :let mydict = {'one': 1, 'two': 2, 'three': 3} 816 :let val = mydict["one"] 817 :let mydict["four"] = 4 818 :let val = mydict.one 819 :let mydict.four = 4 820 821 You can add new entries to an existing Dictionary this way, unlike Lists. 822 823 For keys that consist entirely of letters, digits and underscore the following 824 form can be used |expr-entry|: > 825 :let val = mydict.one 826 :let mydict.four = 4 827 828 Since an entry can be any type, also a List and a Dictionary, the indexing and 829 key lookup can be repeated: > 830 :echo dict.key[idx].key 831 832 833 Dictionary to List conversion ~ 834 835 You may want to loop over the entries in a dictionary. For this you need to 836 turn the Dictionary into a List and pass it to |:for|. 837 838 Most often you want to loop over the keys, using the |keys()| function: > 839 :for key in keys(mydict) 840 : echo key .. ': ' .. mydict[key] 841 :endfor 842 843 The List of keys is unsorted. You may want to sort them first: > 844 :for key in sort(keys(mydict)) 845 846 To loop over the values use the |values()| function: > 847 :for v in values(mydict) 848 : echo "value: " .. v 849 :endfor 850 851 If you want both the key and the value use the |items()| function. It returns 852 a List in which each item is a List with two items, the key and the value: > 853 :for [key, value] in items(mydict) 854 : echo key .. ': ' .. value 855 :endfor 856 857 858 Dictionary identity ~ 859 *dict-identity* 860 Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a 861 Dictionary. Otherwise, assignment results in referring to the same 862 Dictionary: > 863 :let onedict = {'a': 1, 'b': 2} 864 :let adict = onedict 865 :let adict['a'] = 11 866 :echo onedict['a'] 867 11 868 869 Two Dictionaries compare equal if all the key-value pairs compare equal. For 870 more info see |list-identity|. 871 872 873 Dictionary modification ~ 874 *dict-modification* 875 To change an already existing entry of a Dictionary, or to add a new entry, 876 use |:let| this way: > 877 :let dict[4] = "four" 878 :let dict['one'] = item 879 880 Removing an entry from a Dictionary is done with |remove()| or |:unlet|. 881 Three ways to remove the entry with key "aaa" from dict: > 882 :let i = remove(dict, 'aaa') 883 :unlet dict.aaa 884 :unlet dict['aaa'] 885 886 Merging a Dictionary with another is done with |extend()|: > 887 :call extend(adict, bdict) 888 This extends adict with all entries from bdict. Duplicate keys cause entries 889 in adict to be overwritten. An optional third argument can change this. 890 Note that the order of entries in a Dictionary is irrelevant, thus don't 891 expect ":echo adict" to show the items from bdict after the older entries in 892 adict. 893 894 Weeding out entries from a Dictionary can be done with |filter()|: > 895 :call filter(dict, 'v:val =~ "x"') 896 This removes all entries from "dict" with a value not matching 'x'. 897 This can also be used to remove all entries: > 898 call filter(dict, 0) 899 900 In some situations it is not allowed to remove or add entries to a Dictionary. 901 Especially when iterating over all the entries. You will get *E1313* or 902 another error in that case. 903 904 905 Dictionary function ~ 906 *Dictionary-function* *self* *E725* *E862* 907 When a function is defined with the "dict" attribute it can be used in a 908 special way with a dictionary. Example: > 909 :function Mylen() dict 910 : return len(self.data) 911 :endfunction 912 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")} 913 :echo mydict.len() 914 915 This is like a method in object oriented programming. The entry in the 916 Dictionary is a |Funcref|. The local variable "self" refers to the dictionary 917 the function was invoked from. When using |Vim9| script you can use classes 918 and objects, see `:class`. 919 920 It is also possible to add a function without the "dict" attribute as a 921 Funcref to a Dictionary, but the "self" variable is not available then. 922 923 *numbered-function* *anonymous-function* 924 To avoid the extra name for the function it can be defined and directly 925 assigned to a Dictionary in this way: > 926 :let mydict = {'data': [0, 1, 2, 3]} 927 :function mydict.len() 928 : return len(self.data) 929 :endfunction 930 :echo mydict.len() 931 932 The function will then get a number and the value of dict.len is a |Funcref| 933 that references this function. The function can only be used through a 934 |Funcref|. It will automatically be deleted when there is no |Funcref| 935 remaining that refers to it. 936 937 It is not necessary to use the "dict" attribute for a numbered function. 938 939 If you get an error for a numbered function, you can find out what it is with 940 a trick. Assuming the function is 42, the command is: > 941 :function g:42 942 943 944 Functions for Dictionaries ~ 945 *E715* 946 Functions that can be used with a Dictionary: > 947 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo" 948 :if empty(dict) " TRUE if dict is empty 949 :let l = len(dict) " number of items in dict 950 :let big = max(dict) " maximum value in dict 951 :let small = min(dict) " minimum value in dict 952 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict 953 :let s = string(dict) " String representation of dict 954 :call map(dict, '">> " .. v:val') " prepend ">> " to each item 955 956 957 1.6 Blobs ~ 958 *blob* *Blob* *Blobs* *E978* 959 A Blob is a binary object. It can be used to read an image from a file and 960 send it over a channel, for example. 961 962 A Blob mostly behaves like a |List| of numbers, where each number has the 963 value of an 8-bit byte, from 0 to 255. 964 965 966 Blob creation ~ 967 968 A Blob can be created with a |blob-literal|: > 969 :let b = 0zFF00ED015DAF 970 Dots can be inserted between bytes (pair of hex characters) for readability, 971 they don't change the value: > 972 :let b = 0zFF00.ED01.5DAF 973 974 A blob can be read from a file with |readfile()| passing the {type} argument 975 set to "B", for example: > 976 :let b = readfile('image.png', 'B') 977 978 A blob can be read from a channel with the |ch_readblob()| function. 979 980 981 Blob index ~ 982 *blob-index* *E979* 983 A byte in the Blob can be accessed by putting the index in square brackets 984 after the Blob. Indexes are zero-based, thus the first byte has index zero. > 985 :let myblob = 0z00112233 986 :let byte = myblob[0] " get the first byte: 0x00 987 :let byte = myblob[2] " get the third byte: 0x22 988 989 A negative index is counted from the end. Index -1 refers to the last byte in 990 the Blob, -2 to the last but one byte, etc. > 991 :let last = myblob[-1] " get the last byte: 0x33 992 993 To avoid an error for an invalid index use the |get()| function. When an item 994 is not available it returns -1 or the default value you specify: > 995 :echo get(myblob, idx) 996 :echo get(myblob, idx, 999) 997 998 999 Blob iteration ~ 1000 1001 The |:for| loop executes commands for each byte of a Blob. The loop variable 1002 is set to each byte in the Blob. Example: > 1003 :for byte in 0z112233 1004 : call Doit(byte) 1005 :endfor 1006 This calls Doit() with 0x11, 0x22 and 0x33. 1007 1008 1009 Blob concatenation ~ 1010 *blob-concatenation* 1011 Two blobs can be concatenated with the "+" operator: > 1012 :let longblob = myblob + 0z4455 1013 :let longblob = 0z4455 + myblob 1014 < 1015 A blob can be concatenated with another one in-place using |:let+=| or 1016 |extend()|: > 1017 :let myblob += 0z6677 1018 :call extend(myblob, 0z6677) 1019 < 1020 See |blob-modification| below for more about changing a blob in-place. 1021 1022 1023 Part of a blob ~ 1024 1025 A part of the Blob can be obtained by specifying the first and last index, 1026 separated by a colon in square brackets: > 1027 :let myblob = 0z00112233 1028 :let shortblob = myblob[1:2] " get 0z1122 1029 :let shortblob = myblob[2:-1] " get 0z2233 1030 1031 Omitting the first index is similar to zero. Omitting the last index is 1032 similar to -1. > 1033 :let endblob = myblob[2:] " from item 2 to the end: 0z2233 1034 :let shortblob = myblob[2:2] " Blob with one byte: 0z22 1035 :let otherblob = myblob[:] " make a copy of the Blob 1036 1037 If the first index is beyond the last byte of the Blob or the second index is 1038 before the first index, the result is an empty Blob. There is no error 1039 message. 1040 1041 If the second index is equal to or greater than the length of the list the 1042 length minus one is used: > 1043 :echo myblob[2:8] " result: 0z2233 1044 1045 1046 Blob modification ~ 1047 *blob-modification* *E1184* 1048 To change a specific byte of a blob use |:let| this way: > 1049 :let blob[4] = 0x44 1050 1051 When the index is just one beyond the end of the Blob, it is appended. Any 1052 higher index is an error. 1053 1054 To change a sequence of bytes the [:] notation can be used: > 1055 let blob[1:3] = 0z445566 1056 The length of the replaced bytes must be exactly the same as the value 1057 provided. *E972* 1058 1059 To change part of a blob you can specify the first and last byte to be 1060 modified. The value must have the same number of bytes in the range: > 1061 :let blob[3:5] = 0z334455 1062 1063 To add items to a Blob in-place, you can use |:let+=| or |extend()| 1064 (|blob-concatenation|): > 1065 :let blobA = 0z1122 1066 :let blobA += 0z3344 1067 :call extend(blobA, 0z5566) 1068 < 1069 When two variables refer to the same Blob, changing one Blob in-place will 1070 cause the referenced Blob to be changed in-place: > 1071 :let blobA = 0z1122 1072 :let blobB = blobA 1073 :let blobB += 0z3344 1074 :echo blobA 1075 0z11223344 1076 < 1077 You can also use the functions |add()|, |remove()| and |insert()|. 1078 1079 1080 Blob identity ~ 1081 1082 Blobs can be compared for equality: > 1083 if blob == 0z001122 1084 And for equal identity: > 1085 if blob is otherblob 1086 < *blob-identity* *E977* 1087 When variable "aa" is a Blob and you assign it to another variable "bb", both 1088 variables refer to the same Blob. Then the "is" operator returns true. 1089 1090 When making a copy using [:] or |copy()| the values are the same, but the 1091 identity is different: > 1092 :let blob = 0z112233 1093 :let blob2 = blob 1094 :echo blob == blob2 1095 < 1 > 1096 :echo blob is blob2 1097 < 1 > 1098 :let blob3 = blob[:] 1099 :echo blob == blob3 1100 < 1 > 1101 :echo blob is blob3 1102 < 0 1103 1104 Making a copy of a Blob is done with the |copy()| function. Using [:] also 1105 works, as explained above. 1106 1107 1108 1.7 More about variables ~ 1109 *more-variables* 1110 If you need to know the type of a variable or expression, use the |type()| 1111 function. 1112 1113 When the '!' flag is included in the 'viminfo' option, global variables that 1114 start with an uppercase letter, and don't contain a lowercase letter, are 1115 stored in the viminfo file |viminfo-file|. 1116 1117 When the 'sessionoptions' option contains "global", global variables that 1118 start with an uppercase letter and contain at least one lowercase letter are 1119 stored in the session file |session-file|. 1120 1121 variable name can be stored where ~ 1122 my_var_6 not 1123 My_Var_6 session file 1124 MY_VAR_6 viminfo file 1125 1126 1127 In legacy script it is possible to form a variable name with curly braces, see 1128 |curly-braces-names|. 1129 1130 ============================================================================== 1131 2. Expression syntax *expression-syntax* 1132 *E1143* 1133 Expression syntax summary, from least to most significant: 1134 1135 |expr1| expr2 1136 expr2 ? expr1 : expr1 if-then-else 1137 1138 |expr2| expr3 1139 expr3 || expr3 ... logical OR 1140 1141 |expr3| expr4 1142 expr4 && expr4 ... logical AND 1143 1144 |expr4| expr5 1145 expr5 == expr5 equal 1146 expr5 != expr5 not equal 1147 expr5 > expr5 greater than 1148 expr5 >= expr5 greater than or equal 1149 expr5 < expr5 smaller than 1150 expr5 <= expr5 smaller than or equal 1151 expr5 =~ expr5 regexp matches 1152 expr5 !~ expr5 regexp doesn't match 1153 1154 expr5 ==? expr5 equal, ignoring case 1155 expr5 ==# expr5 equal, match case 1156 etc. As above, append ? for ignoring case, # for 1157 matching case 1158 1159 expr5 is expr5 same |List|, |Tuple|, |Dictionary| or |Blob| 1160 instance 1161 expr5 isnot expr5 different |List|, |Tuple|, |Dictionary| or 1162 |Blob| instance 1163 1164 |expr5| expr6 1165 expr6 << expr6 bitwise left shift 1166 expr6 >> expr6 bitwise right shift 1167 1168 |expr6| expr7 1169 expr7 + expr7 ... number addition, list or tuple or blob 1170 concatenation 1171 expr7 - expr7 ... number subtraction 1172 expr7 . expr7 ... string concatenation 1173 expr7 .. expr7 ... string concatenation 1174 1175 |expr7| expr8 1176 expr8 * expr8 ... number multiplication 1177 expr8 / expr8 ... number division 1178 expr8 % expr8 ... number modulo 1179 1180 |expr8| expr9 1181 <type>expr9 type check and conversion (|Vim9| only) 1182 1183 |expr9| expr10 1184 ! expr9 logical NOT 1185 - expr9 unary minus 1186 + expr9 unary plus 1187 1188 |expr10| expr11 1189 expr10[expr1] byte of a String or item of a |List| or 1190 |Tuple| 1191 expr10[expr1 : expr1] substring of a String or sublist of a |List| 1192 or a slice of a |Tuple| 1193 expr10.name entry in a |Dictionary| 1194 expr10(expr1, ...) function call with |Funcref| variable 1195 expr10->name(expr1, ...) |method| call 1196 1197 |expr11| number number constant 1198 "string" string constant, backslash is special 1199 'string' string constant, ' is doubled 1200 [expr1, ...] |List| 1201 (expr1, ...) |Tuple| 1202 {expr1: expr1, ...} |Dictionary| 1203 #{key: expr1, ...} legacy |Dictionary| 1204 &option option value 1205 (expr1) nested expression 1206 variable internal variable 1207 va{ria}ble internal variable with curly braces 1208 $VAR environment variable 1209 @r contents of register 'r' 1210 function(expr1, ...) function call 1211 func{ti}on(expr1, ...) function call with curly braces 1212 {args -> expr1} legacy lambda expression 1213 (args) => expr1 Vim9 lambda expression 1214 1215 1216 "..." indicates that the operations in this level can be concatenated. 1217 Example: > 1218 &nu || &list && &shell == "csh" 1219 1220 All expressions within one level are parsed from left to right. 1221 1222 Expression nesting is limited to 1000 levels deep (300 when build with MSVC) 1223 to avoid running out of stack and crashing. *E1169* 1224 1225 1226 expr1 *expr1* *ternary* *falsy-operator* *??* *E109* 1227 ----- 1228 1229 The ternary operator: expr2 ? expr1 : expr1 1230 The falsy operator: expr2 ?? expr1 1231 1232 Ternary operator ~ 1233 1234 In legacy script the expression before the '?' is evaluated to a number. If 1235 it evaluates to |TRUE|, the result is the value of the expression between the 1236 '?' and ':', otherwise the result is the value of the expression after the 1237 ':'. 1238 1239 In |Vim9| script the first expression must evaluate to a boolean, see 1240 |vim9-boolean|. 1241 1242 Example: > 1243 :echo lnum == 1 ? "top" : lnum 1244 1245 Since the first expression is an "expr2", it cannot contain another ?:. The 1246 other two expressions can, thus allow for recursive use of ?:. 1247 Example: > 1248 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum 1249 1250 To keep this readable, using |line-continuation| is suggested: > 1251 :echo lnum == 1 1252 :\ ? "top" 1253 :\ : lnum == 1000 1254 :\ ? "last" 1255 :\ : lnum 1256 1257 You should always put a space before the ':', otherwise it can be mistaken for 1258 use in a variable such as "a:1". 1259 1260 Falsy operator ~ 1261 1262 This is also known as the "null coalescing operator", but that's too 1263 complicated, thus we just call it the falsy operator. 1264 1265 The expression before the '??' is evaluated. If it evaluates to 1266 |truthy|, this is used as the result. Otherwise the expression after the '??' 1267 is evaluated and used as the result. This is most useful to have a default 1268 value for an expression that may result in zero or empty: > 1269 echo theList ?? 'list is empty' 1270 echo GetName() ?? 'unknown' 1271 1272 These are similar, but not equal: > 1273 expr2 ?? expr1 1274 expr2 ? expr2 : expr1 1275 In the second line "expr2" is evaluated twice. And in |Vim9| script the type 1276 of expr2 before "?" must be a boolean. 1277 1278 1279 expr2 and expr3 *expr2* *expr3* 1280 --------------- 1281 1282 expr3 || expr3 .. logical OR *expr-barbar* 1283 expr4 && expr4 .. logical AND *expr-&&* 1284 1285 The "||" and "&&" operators take one argument on each side. 1286 1287 In legacy script the arguments are (converted to) Numbers. 1288 1289 In |Vim9| script the values must be boolean, see |vim9-boolean|. Use "!!" to 1290 convert any type to a boolean. 1291 1292 The result is: 1293 input output ~ 1294 n1 n2 n1 || n2 n1 && n2 ~ 1295 |FALSE| |FALSE| |FALSE| |FALSE| 1296 |FALSE| |TRUE| |TRUE| |FALSE| 1297 |TRUE| |FALSE| |TRUE| |FALSE| 1298 |TRUE| |TRUE| |TRUE| |TRUE| 1299 1300 The operators can be concatenated, for example: > 1301 1302 &nu || &list && &shell == "csh" 1303 1304 Note that "&&" takes precedence over "||", so this has the meaning of: > 1305 1306 &nu || (&list && &shell == "csh") 1307 1308 Once the result is known, the expression "short-circuits", that is, further 1309 arguments are not evaluated. This is like what happens in C. For example: > 1310 1311 let a = 1 1312 echo a || b 1313 1314 This is valid even if there is no variable called "b" because "a" is |TRUE|, 1315 so the result must be |TRUE|. Similarly below: > 1316 1317 echo exists("b") && b == "yes" 1318 1319 This is valid whether "b" has been defined or not. The second clause will 1320 only be evaluated if "b" has been defined. 1321 1322 1323 expr4 *expr4* *E1153* 1324 ----- 1325 1326 expr5 {cmp} expr5 1327 1328 Compare two expr5 expressions. In legacy script the result is a 0 if it 1329 evaluates to false, or 1 if it evaluates to true. In |Vim9| script the result 1330 is |true| or |false|. 1331 1332 *expr-==* *expr-!=* *expr->* *expr->=* 1333 *expr-<* *expr-<=* *expr-=~* *expr-!~* 1334 *expr-==#* *expr-!=#* *expr->#* *expr->=#* 1335 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#* 1336 *expr-==?* *expr-!=?* *expr->?* *expr->=?* 1337 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?* 1338 *expr-is* *expr-isnot* *expr-is#* *expr-isnot#* 1339 *expr-is?* *expr-isnot?* *E1072* 1340 use 'ignorecase' match case ignore case ~ 1341 equal == ==# ==? 1342 not equal != !=# !=? 1343 greater than > ># >? 1344 greater than or equal >= >=# >=? 1345 smaller than < <# <? 1346 smaller than or equal <= <=# <=? 1347 regexp matches =~ =~# =~? 1348 regexp doesn't match !~ !~# !~? 1349 same instance is is# is? 1350 different instance isnot isnot# isnot? 1351 1352 Examples: 1353 "abc" ==# "Abc" evaluates to 0 1354 "abc" ==? "Abc" evaluates to 1 1355 "abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise 1356 NOTE: In |Vim9| script 'ignorecase' is not used. 1357 1358 *E691* *E692* *E1517* *E1518* 1359 A |List| can only be compared with a |List| and only "equal", "not equal", 1360 "is" and "isnot" can be used. This compares the values of the list, 1361 recursively. Ignoring case means case is ignored when comparing item values. 1362 Same applies for a |Tuple|. 1363 1364 *E735* *E736* 1365 A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not 1366 equal", "is" and "isnot" can be used. This compares the key/values of the 1367 |Dictionary| recursively. Ignoring case means case is ignored when comparing 1368 item values. 1369 1370 *E694* 1371 A |Funcref| can only be compared with a |Funcref| and only "equal", "not 1372 equal", "is" and "isnot" can be used. Case is never ignored. Whether 1373 arguments or a Dictionary are bound (with a partial) matters. The 1374 Dictionaries must also be equal (or the same, in case of "is") and the 1375 arguments must be equal (or the same). 1376 1377 To compare Funcrefs to see if they refer to the same function, ignoring bound 1378 Dictionary and arguments, use |get()| to get the function name: > 1379 if get(Part1, 'name') == get(Part2, 'name') 1380 " Part1 and Part2 refer to the same function 1381 < 1382 *E1437* 1383 An |Object| can only be compared with another |Object|, using only the 1384 "equal", "not equal", "is" and "isnot" operators |expr4|. An |enum| is also a 1385 type of |Object|, and the same rules apply. 1386 1387 *E1037* 1388 Using "is" or "isnot" with a |List|, |Tuple|, |Dictionary| or |Blob| checks 1389 whether the expressions are referring to the same |List|, |Tuple|, 1390 |Dictionary| or |Blob| instance. A copy of a |List| or |Tuple| is different 1391 from the original |List| or |Tuple|. When using "is" without a |List|, 1392 |Tuple|, |Dictionary| or |Blob|, it is equivalent to using "equal", using 1393 "isnot" is equivalent to using "not equal". Except that a different type 1394 means the values are different: > 1395 echo 4 == '4' 1396 1 1397 echo 4 is '4' 1398 0 1399 echo 0 is [] 1400 0 1401 "is#"/"isnot#" and "is?"/"isnot?" can be used to match and ignore case. 1402 In |Vim9| script this doesn't work, two strings are never identical. 1403 1404 In legacy script, when comparing a String with a Number, the String is 1405 converted to a Number, and the comparison is done on Numbers. This means 1406 that: > 1407 echo 0 == 'x' 1408 1 1409 because 'x' converted to a Number is zero. However: > 1410 echo [0] == ['x'] 1411 0 1412 Inside a List or Tuple or Dictionary this conversion is not used. 1413 1414 In |Vim9| script, except when comparing a number with a float, the types must 1415 match - see |vim9-comparators|. 1416 1417 When comparing two Strings, this is done with strcmp() or stricmp(). This 1418 results in the mathematical difference (comparing byte values), not 1419 necessarily the alphabetical difference in the local language. 1420 1421 When using the operators with a trailing '#', or the short version and 1422 'ignorecase' is off, the comparing is done with strcmp(): case matters. 1423 1424 When using the operators with a trailing '?', or the short version and 1425 'ignorecase' is set, the comparing is done with stricmp(): case is ignored. 1426 1427 'smartcase' is not used. 1428 1429 The "=~" and "!~" operators match the lefthand argument with the righthand 1430 argument, which is used as a pattern. See |pattern| for what a pattern is. 1431 This matching is always done like 'magic' was set and 'cpoptions' is empty, no 1432 matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts 1433 portable. To avoid backslashes in the regexp pattern to be doubled, use a 1434 single-quote string, see |literal-string|. 1435 Since a string is considered to be a single line, a multi-line pattern 1436 (containing \n, backslash-n) will not match. However, a literal NL character 1437 can be matched like an ordinary character. Examples: 1438 "foo\nbar" =~ "\n" evaluates to 1 1439 "foo\nbar" =~ "\\n" evaluates to 0 1440 1441 1442 expr5 *expr5* *bitwise-shift* 1443 ----- 1444 expr6 << expr6 bitwise left shift *expr-<<* 1445 expr6 >> expr6 bitwise right shift *expr->>* 1446 *E1282* *E1283* 1447 The "<<" and ">>" operators can be used to perform bitwise left or right shift 1448 of the left operand by the number of bits specified by the right operand. The 1449 operands are used as positive numbers. When shifting right with ">>" the 1450 topmost bit (sometimes called the sign bit) is cleared. If the right operand 1451 (shift amount) is more than the maximum number of bits in a number 1452 (|v:numbersize|) the result is zero. 1453 1454 1455 expr6 and expr7 *expr6* *expr7* *E1036* *E1051* 1456 --------------- 1457 *expr-+* 1458 expr7 + expr7 Number addition, |List| or |Tuple| or |Blob| concatenation 1459 expr7 - expr7 Number subtraction *expr--* 1460 expr7 . expr7 String concatenation *expr-.* 1461 expr7 .. expr7 String concatenation *expr-..* 1462 1463 For |Lists| only "+" is possible and then both expr7 must be a list. The 1464 result is a new list with the two lists concatenated. Same for a |Tuple|. 1465 1466 For String concatenation ".." is preferred, since "." is ambiguous, it is also 1467 used for |Dict| member access and floating point numbers. 1468 In |Vim9| script and when |vimscript-version| is 2 or higher, using "." is not 1469 allowed. 1470 1471 In |Vim9| script the arguments of ".." are converted to String for simple 1472 types: Number, Float, Special and Bool. For other types |string()| should be 1473 used. 1474 1475 expr8 * expr8 Number multiplication *expr-star* 1476 expr8 / expr8 Number division *expr-/* 1477 expr8 % expr8 Number modulo *expr-%* 1478 1479 In legacy script, for all operators except "." and "..", Strings are converted 1480 to Numbers. 1481 1482 For bitwise operators see |and()|, |or()| and |xor()|. 1483 1484 Note the difference between "+" and ".." in legacy script: 1485 "123" + "456" = 579 1486 "123" .. "456" = "123456" 1487 1488 Since '..' has the same precedence as '+' and '-', you need to read: > 1489 1 .. 90 + 90.0 1490 As: > 1491 (1 .. 90) + 90.0 1492 That works in legacy script, since the String "190" is automatically converted 1493 to the Number 190, which can be added to the Float 90.0. However: > 1494 1 .. 90 * 90.0 1495 Should be read as: > 1496 1 .. (90 * 90.0) 1497 Since '..' has lower precedence than '*'. This does NOT work, since this 1498 attempts to concatenate a Float and a String. 1499 1500 When dividing a Number by zero the result depends on the value: 1501 0 / 0 = -0x80000000 (like NaN for Float) 1502 >0 / 0 = 0x7fffffff (like positive infinity) 1503 <0 / 0 = -0x7fffffff (like negative infinity) 1504 (before Vim 7.2 it was always 0x7fffffff) 1505 In |Vim9| script dividing a number by zero is an error. *E1154* 1506 1507 When 64-bit Number support is enabled: 1508 0 / 0 = -0x8000000000000000 (like NaN for Float) 1509 >0 / 0 = 0x7fffffffffffffff (like positive infinity) 1510 <0 / 0 = -0x7fffffffffffffff (like negative infinity) 1511 1512 When the righthand side of '%' is zero, the result is 0. 1513 1514 None of these work for |Funcref|s. 1515 1516 ".", ".." and "%" do not work for Float. *E804* *E1035* 1517 1518 1519 expr8 *expr8* 1520 ----- 1521 <type>expr9 1522 1523 This is only available in |Vim9| script, see |type-casting|. 1524 1525 1526 expr9 *expr9* 1527 ----- 1528 ! expr9 logical NOT *expr-!* 1529 - expr9 unary minus *expr-unary--* 1530 + expr9 unary plus *expr-unary-+* 1531 1532 For '!' |TRUE| becomes |FALSE|, |FALSE| becomes |TRUE| (one). 1533 For '-' the sign of the number is changed. 1534 For '+' the number is unchanged. Note: "++" has no effect. 1535 1536 In legacy script a String will be converted to a Number first. Note that if 1537 the string does not start with a digit you likely don't get what you expect. 1538 1539 In |Vim9| script an error is given when "-" or "+" is used and the type is not 1540 a number. 1541 1542 In |Vim9| script "!" can be used for any type and the result is always a 1543 boolean. Use "!!" to convert any type to a boolean, according to whether the 1544 value is |falsy|. 1545 1546 These three can be repeated and mixed. Examples: 1547 !-1 == 0 1548 !!8 == 1 1549 --9 == 9 1550 1551 1552 expr10 *expr10* 1553 ------ 1554 This expression is either |expr11| or a sequence of the alternatives below, 1555 in any order. E.g., these are all possible: 1556 expr10[expr1].name 1557 expr10.name[expr1] 1558 expr10(expr1, ...)[expr1].name 1559 expr10->(expr1, ...)[expr1] 1560 Evaluation is always from left to right. 1561 1562 *expr-[]* *E111* 1563 expr10[expr1] item of String or |List| or |Tuple| 1564 *E909* *subscript* *E1062* 1565 In legacy Vim script: 1566 If expr10 is a Number or String this results in a String that contains the 1567 expr1'th single byte from expr10. expr10 is used as a String (a number is 1568 automatically converted to a String), expr1 as a Number. This doesn't 1569 recognize multibyte encodings, see `byteidx()` for an alternative, or use 1570 `split()` to turn the string into a list of characters. Example, to get the 1571 byte under the cursor: > 1572 :let c = getline(".")[col(".") - 1] 1573 1574 In |Vim9| script: 1575 - If expr10 is a String this results in a String that contains the expr1'th 1576 single character (including any composing characters) from expr10. To use 1577 byte indexes use |strpart()|. 1578 - Index zero gives the first character (including any composing character). 1579 Careful: text column numbers start with one! 1580 - If the length of the String is less than the index, the result is an empty 1581 String. A negative index always results in an empty string (reason: 1582 backward compatibility). Use [-1 :] to get the last character (including 1583 any composing character). 1584 - A negative index is used like with a list: count from the end. 1585 - Attempting to assign to or modify a string with an index within a `:def` 1586 function gives |E1148|. 1587 1588 If expr10 is a |List| then it results the item at index expr1. See 1589 |list-index| for possible index values. If the index is out of range this 1590 results in an error. Example: > 1591 :let item = mylist[-1] " get last item 1592 1593 Generally, if a |List| index is equal to or higher than the length of the 1594 |List|, or more negative than the length of the |List|, this results in an 1595 error. 1596 1597 A |Tuple| index is similar to a |List| index as explained above. 1598 1599 1600 expr10[expr1a : expr1b] substring or |sublist| *expr-[:]* *substring* 1601 1602 If expr10 is a String this results in the substring with the bytes or 1603 characters from expr1a to and including expr1b. expr10 is used as a String, 1604 expr1a and expr1b are used as a Number. 1605 1606 In legacy Vim script the indexes are byte indexes. This doesn't recognize 1607 multibyte encodings, see |byteidx()| for computing the indexes. If expr10 is 1608 a Number it is first converted to a String. 1609 1610 In Vim9 script the indexes are character indexes and include composing 1611 characters. To use byte indexes use |strpart()|. To use character indexes 1612 without including composing characters use |strcharpart()|. 1613 1614 The item at index expr1b is included, it is inclusive. For an exclusive index 1615 use the |slice()| function. 1616 1617 If expr1a is omitted zero is used. If expr1b is omitted the length of the 1618 string minus one is used. 1619 1620 A negative number can be used to measure from the end of the string. -1 is 1621 the last character, -2 the last but one, etc. 1622 1623 If an index goes out of range for the string characters are omitted. If 1624 expr1b is smaller than expr1a the result is an empty string. 1625 1626 Examples: > 1627 :let c = name[-1:] " last byte of a string 1628 :let c = name[0:-1] " the whole string 1629 :let c = name[-2:-2] " last but one byte of a string 1630 :let s = line(".")[4:] " from the fifth byte to the end 1631 :let s = s[:-3] " remove last two bytes 1632 < 1633 *slice* 1634 If expr10 is a |List| this results in a new |List| with the items indicated by 1635 the indexes expr1a and expr1b. This works like with a String, as explained 1636 just above. Also see |sublist| below. Examples: > 1637 :let l = mylist[:3] " first four items 1638 :let l = mylist[4:4] " List with one item 1639 :let l = mylist[:] " shallow copy of a List 1640 A |Tuple| slice is similar to a |List| slice. 1641 1642 If expr10 is a |Blob| this results in a new |Blob| with the bytes in the 1643 indexes expr1a and expr1b, inclusive. Examples: > 1644 :let b = 0zDEADBEEF 1645 :let bs = b[1:2] " 0zADBE 1646 :let bs = b[:] " copy of 0zDEADBEEF 1647 1648 Using expr10[expr1] or expr10[expr1a : expr1b] on a |Funcref| results in an 1649 error. 1650 1651 Watch out for confusion between a namespace and a variable followed by a colon 1652 for a sublist: > 1653 mylist[n:] " uses variable n 1654 mylist[s:] " uses namespace s:, error! 1655 1656 1657 expr10.name entry in a |Dictionary| *expr-entry* 1658 *E1203* *E1229* 1659 If expr10 is a |Dictionary| and it is followed by a dot, then the following 1660 name will be used as a key in the |Dictionary|. This is just like: 1661 expr10[name]. 1662 1663 The name must consist of alphanumeric characters, just like a variable name, 1664 but it may start with a number. Curly braces cannot be used. 1665 1666 There must not be white space before or after the dot. 1667 1668 Examples: > 1669 :let dict = {"one": 1, 2: "two"} 1670 :echo dict.one " shows "1" 1671 :echo dict.2 " shows "two" 1672 :echo dict .2 " error because of space before the dot 1673 1674 Note that the dot is also used for String concatenation. To avoid confusion 1675 always put spaces around the dot for String concatenation. 1676 1677 1678 expr10(expr1, ...) |Funcref| function call *E1085* 1679 1680 When expr10 is a |Funcref| type variable, invoke the function it refers to. 1681 1682 1683 expr10->name([args]) method call *method* *->* 1684 expr10->{lambda}([args]) 1685 *E260* *E276* *E1265* 1686 For methods that are also available as global functions this is the same as: > 1687 name(expr10 [, args]) 1688 There can also be methods specifically for the type of "expr10". 1689 1690 This allows for chaining, passing the value that one method returns to the 1691 next method: > 1692 mylist->filter(filterexpr)->map(mapexpr)->sort()->join() 1693 < 1694 Example of using a lambda: > 1695 GetPercentage()->{x -> x * 100}()->printf('%d%%') 1696 < 1697 When using -> the |expr9| operators will be applied first, thus: > 1698 -1.234->string() 1699 Is equivalent to: > 1700 (-1.234)->string() 1701 And NOT: > 1702 -(1.234->string()) 1703 1704 What comes after "->" can be a name, a simple expression (not containing any 1705 parenthesis), or any expression in parentheses: > 1706 base->name(args) 1707 base->some.name(args) 1708 base->alist[idx](args) 1709 base->(getFuncRef())(args) 1710 Note that in the last call the base is passed to the function resulting from 1711 "(getFuncRef())", inserted before "args". *E1275* 1712 1713 *E274* 1714 "->name(" must not contain white space. There can be white space before the 1715 "->" and after the "(", thus you can split the lines like this: > 1716 mylist 1717 \ ->filter(filterexpr) 1718 \ ->map(mapexpr) 1719 \ ->sort() 1720 \ ->join() 1721 1722 When using the lambda form there must be no white space between the } and the 1723 (. 1724 1725 1726 *expr11* 1727 number 1728 ------ 1729 number number constant *expr-number* 1730 1731 *0x* *hex-number* *0o* *octal-number* 1732 *0b* *binary-number* 1733 Integer numbers can be written in multiple forms: 1734 1735 {N} decimal 1736 0x{N} or 0X{N} hexadecimal 1737 0o{N} or 0O{N} octal 1738 0{N} octal (decimal in |scriptversion-4| and |Vim9|) 1739 0b{N} or 0B{N} binary 1740 1741 {N} is a sequence of decimal digits (0-9), hexadecimal digits (0-9, a-f and 1742 A-F), octal digits (0-7) or binary digits (0 or 1). 1743 1744 Assuming 64 bit numbers are used (see |v:numbersize|) an unsigned number is 1745 truncated to 0x7fffffffffffffff or 9223372036854775807. You can use -1 to get 1746 0xffffffffffffffff. 1747 1748 In |scriptversion-4| and in |Vim9| script, single quotes may appear between 1749 digits to improve readability; these are ignored. 1750 1751 A leading "+" or "-" is not part of an integer literal. E.g., -123 is an 1752 expression, the unary operator |expr-unary--| applied to the number 123. 1753 1754 Examples: 1755 0xDEAD 1756 57005 1757 0b1101111010101101 1758 0o157255 1759 0xBE'EF |scriptversion-4| and |Vim9| script 1760 48'879 |scriptversion-4| and |Vim9| script 1761 0o137'357 |scriptversion-4| and |Vim9| script 1762 0b1011'1110'1110'1111 |scriptversion-4| and |Vim9| script 1763 1764 *floating-point-format* 1765 Floating point numbers can be written in two forms: 1766 1767 {N}.{M} 1768 {N}.{M}[eE][-+]{exp} 1769 1770 {N} and {M} are sequences of decimal digits. In |scriptversion-1| (the 1771 default) {N} and {M} must be present. In |scriptversion-2| or higher and in 1772 |Vim9| script {N} is optional. 1773 {exp} is the exponent, power of 10. 1774 Only a decimal point is accepted, not a comma. No matter what the current 1775 locale is. 1776 1777 In |scriptversion-4| and in |Vim9| script, single quotes may appear between the 1778 digits in {N} to improve readability; these are ignored. 1779 1780 A leading "+" or "-" is not part of a floating point literal. E.g., -1.0e-3 1781 is an expression, the unary operator |expr-unary--| applied to the float 1782 1.0e-3. The "-" in the exponent is part of the literal. 1783 1784 Examples: 1785 123.456 1786 0.0001 1787 55.0 1788 0.123 1789 1.234e03 1790 1.0E-6 1791 3.1416e+88 1792 1793 .123 |scriptversion-2| or higher and |Vim9| script 1794 123'456.0 |scriptversion-4| and |Vim9| script 1795 1796 These are INVALID: 1797 3. empty {M} 1798 1e40 missing .{M} 1799 1800 Rationale: 1801 Before floating point was introduced, the text "123.456" was interpreted as 1802 the two numbers "123" and "456", both converted to a string and concatenated, 1803 resulting in the string "123456". Since this was considered pointless, and we 1804 could not find it intentionally being used in Vim scripts, this backwards 1805 incompatibility was accepted in favor of being able to use the normal notation 1806 for floating point numbers. 1807 1808 *float-pi* *float-e* 1809 A few useful values to copy&paste: > 1810 :let pi = 3.14159265359 1811 :let e = 2.71828182846 1812 Or, if you don't want to write them in as floating-point literals, you can 1813 also use functions, like the following: > 1814 :let pi = acos(-1.0) 1815 :let e = exp(1.0) 1816 < 1817 *floating-point-precision* 1818 The precision and range of floating points numbers depends on what "double" 1819 means in the library Vim was compiled with. There is no way to change this at 1820 runtime. 1821 1822 The default for displaying a |Float| is to use 6 decimal places, like using 1823 printf("%g", f). You can select something else when using the |printf()| 1824 function. Example: > 1825 :echo printf('%.15e', atan(1)) 1826 < 7.853981633974483e-01 1827 1828 1829 1830 string *string* *String* *expr-string* *E114* 1831 ------ 1832 "string" string constant *expr-quote* 1833 1834 Note that double quotes are used. 1835 1836 A string constant accepts these special characters: 1837 \... three-digit octal number (e.g., "\316") 1838 \.. two-digit octal number (must be followed by non-digit) 1839 \. one-digit octal number (must be followed by non-digit) 1840 \x.. byte specified with two hex numbers (e.g., "\x1f") 1841 \x. byte specified with one hex number (must be followed by non-hex char) 1842 \X.. same as \x.. 1843 \X. same as \x. 1844 \u.... character specified with up to 4 hex numbers, stored according to the 1845 current value of 'encoding' (e.g., "\u02a4") 1846 \U.... same as \u but allows up to 8 hex numbers. 1847 \b backspace <BS> 1848 \e escape <Esc> 1849 \f formfeed 0x0C 1850 \n newline <NL> 1851 \r return <CR> 1852 \t tab <Tab> 1853 \\ backslash 1854 \" double quote 1855 \<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W. This is for use 1856 in mappings, the 0x80 byte is escaped. 1857 To use the double quote character it must be escaped: "<M-\">". 1858 Don't use <Char-xxxx> to get a UTF-8 character, use \uxxxx as 1859 mentioned above. 1860 \<*xxx> Like \<xxx> but prepends a modifier instead of including it in the 1861 character. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is 1862 four bytes: 3 for the CTRL modifier and then character "W". 1863 1864 Note that "\xff" is stored as the byte 255, which may be invalid in some 1865 encodings. Use "\u00ff" to store character 255 according to the current value 1866 of 'encoding'. 1867 1868 Note that "\000" and "\x00" force the end of the string. 1869 1870 1871 blob-literal *blob-literal* *E973* 1872 ------------ 1873 1874 Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes. 1875 The sequence must be an even number of hex characters. Example: > 1876 :let b = 0zFF00ED015DAF 1877 1878 1879 literal-string *literal-string* *E115* 1880 --------------- 1881 'string' string constant *expr-'* 1882 1883 Note that single quotes are used. 1884 1885 This string is taken as it is. No backslashes are removed or have a special 1886 meaning. The only exception is that two quotes stand for one quote. 1887 1888 Single quoted strings are useful for patterns, so that backslashes do not need 1889 to be doubled. These two commands are equivalent: > 1890 if a =~ "\\s*" 1891 if a =~ '\s*' 1892 1893 1894 interpolated-string *$quote* *interpolated-string* 1895 -------------------- 1896 $"string" interpolated string constant *expr-$quote* 1897 $'string' interpolated literal string constant *expr-$'* 1898 1899 Interpolated strings are an extension of the |string| and |literal-string|, 1900 allowing the inclusion of Vim script expressions (see |expr1|). Any 1901 expression returning a value can be enclosed between curly braces. The value 1902 is converted to a string. All the text and results of the expressions 1903 are concatenated to make a new string. 1904 *E1278* *E1279* 1905 To include an opening brace '{' or closing brace '}' in the string content 1906 double it. For double quoted strings using a backslash also works. A single 1907 closing brace '}' will result in an error. 1908 1909 Examples: > 1910 let your_name = input("What's your name? ") 1911 < What's your name? Peter ~ 1912 > 1913 echo 1914 echo $"Hello, {your_name}!" 1915 < Hello, Peter! ~ 1916 > 1917 echo $"The square root of {{9}} is {sqrt(9)}" 1918 < The square root of {9} is 3.0 ~ 1919 1920 *string-offset-encoding* 1921 A string consists of multiple characters. How the characters are stored 1922 depends on 'encoding'. Most common is UTF-8, which uses one byte for ASCII 1923 characters, two bytes for other latin characters and more bytes for other 1924 characters. 1925 1926 A string offset can count characters or bytes. Other programs may use 1927 UTF-16 encoding (16-bit words) and an offset of UTF-16 words. Some functions 1928 use byte offsets, usually for UTF-8 encoding. Other functions use character 1929 offsets, in which case the encoding doesn't matter. 1930 1931 The different offsets for the string "a©😊" are below: 1932 1933 UTF-8 offsets: 1934 [0]: 61, [1]: C2, [2]: A9, [3]: F0, [4]: 9F, [5]: 98, [6]: 8A 1935 UTF-16 offsets: 1936 [0]: 0061, [1]: 00A9, [2]: D83D, [3]: DE0A 1937 UTF-32 (character) offsets: 1938 [0]: 00000061, [1]: 000000A9, [2]: 0001F60A 1939 1940 You can use the "g8" and "ga" commands on a character to see the 1941 decimal/hex/octal values. 1942 1943 The functions |byteidx()|, |utf16idx()| and |charidx()| can be used to convert 1944 between these indices. The functions |strlen()|, |strutf16len()| and 1945 |strcharlen()| return the number of bytes, UTF-16 code units and characters in 1946 a string respectively. 1947 1948 option *expr-option* *E112* *E113* 1949 ------ 1950 &option option value, local value if possible 1951 &g:option global option value 1952 &l:option local option value 1953 1954 Examples: > 1955 echo "tabstop is " .. &tabstop 1956 if &insertmode 1957 1958 Any option name can be used here. See |options|. When using the local value 1959 and there is no buffer-local or window-local value, the global value is used 1960 anyway. 1961 1962 1963 register *expr-register* *@r* 1964 -------- 1965 @r contents of register 'r' 1966 1967 The result is the contents of the named register, as a single string. 1968 Newlines are inserted where required. To get the contents of the unnamed 1969 register use @" or @@. See |registers| for an explanation of the available 1970 registers. 1971 1972 When using the '=' register you get the expression itself, not what it 1973 evaluates to. Use |eval()| to evaluate it. 1974 1975 1976 nesting *expr-nesting* *E110* 1977 ------- 1978 (expr1) nested expression 1979 1980 1981 environment variable *expr-env* 1982 -------------------- 1983 $VAR environment variable 1984 1985 The String value of any environment variable. When it is not defined, the 1986 result is an empty string. 1987 1988 The functions `getenv()` and `setenv()` can also be used and work for 1989 environment variables with non-alphanumeric names. 1990 The function `environ()` can be used to get a Dict with all environment 1991 variables. 1992 1993 1994 *expr-env-expand* 1995 Note that there is a difference between using $VAR directly and using 1996 expand("$VAR"). Using it directly will only expand environment variables that 1997 are known inside the current Vim session. Using expand() will first try using 1998 the environment variables known inside the current Vim session. If that 1999 fails, a shell will be used to expand the variable. This can be slow, but it 2000 does expand all variables that the shell knows about. Example: > 2001 :echo $shell 2002 :echo expand("$shell") 2003 The first one probably doesn't echo anything, the second echoes the $shell 2004 variable (if your shell supports it). 2005 2006 2007 internal variable *expr-variable* *E1015* *E1089* 2008 ----------------- 2009 variable internal variable 2010 See below |internal-variables|. 2011 2012 2013 function call *expr-function* *E116* *E118* *E119* *E120* 2014 ------------- 2015 function(expr1, ...) function call 2016 See below |functions|. 2017 2018 2019 lambda expression *expr-lambda* *lambda* 2020 ----------------- 2021 {args -> expr1} legacy lambda expression *E451* 2022 (args) => expr1 |Vim9| lambda expression 2023 2024 A lambda expression creates a new unnamed function which returns the result of 2025 evaluating |expr1|. Lambda expressions differ from |user-functions| in 2026 the following ways: 2027 2028 1. The body of the lambda expression is an |expr1| and not a sequence of |Ex| 2029 commands. 2030 2. The prefix "a:" should not be used for arguments. E.g.: 2031 >vim 2032 let F = {arg1, arg2 -> arg1 - arg2} 2033 echo F(5, 2) 2034 " 3 2035 < 2036 The arguments are optional. Example: 2037 >vim 2038 let F = {-> 'error function'} 2039 echo F('ignored') 2040 " error function 2041 < 2042 The |Vim9| lambda does not only use a different syntax, it also adds type 2043 checking and can be split over multiple lines, see |vim9-lambda|. 2044 2045 *closure* 2046 Lambda expressions can access outer scope variables and arguments. This is 2047 often called a closure. Example where "i" and "a:arg" are used in a lambda 2048 while they already exist in the function scope. They remain valid even after 2049 the function returns: 2050 >vim 2051 function Foo(arg) 2052 let i = 3 2053 return {x -> x + i - a:arg} 2054 endfunction 2055 let Bar = Foo(4) 2056 echo Bar(6) 2057 " 5 2058 < 2059 Note that the variables must exist in the outer scope before the lambda is 2060 defined for this to work. See also |:func-closure|. For Vim9 script 2061 closures, see |vim9-closure|. 2062 2063 Lambda and closure support can be checked with: > 2064 if has('lambda') 2065 2066 Examples, using legacy Vim script and Vim9 script, for using a lambda 2067 expression with |sort()|, |map()| and |filter()|: 2068 >vim 2069 echo sort([3, 2, 1, 4], {a, b -> a - b}) | " [1, 2, 3, 4] 2070 vim9cmd echo [3, 2, 1, 4]->sort((a, b) => a - b) # [1, 2, 3, 4] 2071 2072 echo map([1, 2, 3], {idx, val -> val + 1}) | " [2, 3, 4] 2073 vim9cmd echo [1, 2, 3]->map((_, val) => val + 1) # [2, 3, 4] 2074 2075 echo filter([1, 2, 3], {idx, val -> val > 1}) | " [2, 3] 2076 vim9cmd echo [1, 2, 3]->filter((_, val) => val > 1) # [2, 3] 2077 2078 The lambda expression is also useful for Channel, Job and timer: 2079 >vim 2080 echowindow "Handler calling..." 2081 let b:count = 0 2082 let timer = timer_start(1000, 2083 \ {-> execute("let b:count += 1 | " .. 2084 \ "echowindow 'Handler called ' .. b:count", "")}, 2085 \ {'repeat': 3}) 2086 " Handler called 1 2087 " Handler called 2 2088 " Handler called 3 2089 < 2090 Note that it is possible to cause memory to be used and not freed if the 2091 closure is referenced by the context it depends on: > 2092 function Function() 2093 let x = 0 2094 let F = {-> x} 2095 endfunction 2096 The closure uses "x" from the function scope, and "F" in that same scope 2097 refers to the closure. This cycle results in the memory not being freed. 2098 Recommendation: don't do this. 2099 2100 Notice how execute() is used to execute an Ex command. That's ugly though. 2101 In Vim9 script you can use a command block, see |inline-function|. 2102 2103 Although you can use the loop variable of a `for` command, it must still exist 2104 when the closure is called, otherwise you get an error. *E1302* 2105 2106 Lambda expressions have internal names like '<lambda>42'. If you get an error 2107 for a lambda expression, you can find what it is with the following command: > 2108 :function <lambda>42 2109 See also: |numbered-function| 2110 2111 ============================================================================== 2112 3. Internal variable *internal-variables* *E461* *E1001* 2113 2114 An internal variable name can be made up of letters, digits and '_'. But it 2115 cannot start with a digit. In legacy script it is also possible to use curly 2116 braces, see |curly-braces-names|. 2117 2118 In legacy script an internal variable is created with the ":let" command 2119 |:let|. An internal variable is explicitly destroyed with the ":unlet" 2120 command |:unlet|. 2121 Using a name that is not an internal variable or refers to a variable that has 2122 been destroyed results in an error. 2123 2124 In |Vim9| script `:let` is not used and variables work differently, see |:var|. 2125 2126 *variable-scope* 2127 There are several name spaces for variables. Which one is to be used is 2128 specified by what is prepended: 2129 2130 (nothing) In a function: local to the function; 2131 in a legacy script: global; 2132 in a |Vim9| script: local to the script 2133 |buffer-variable| b: Local to the current buffer. 2134 |window-variable| w: Local to the current window. 2135 |tabpage-variable| t: Local to the current tab page. 2136 |global-variable| g: Global. 2137 |local-variable| l: Local to a function (only in a legacy function) 2138 |script-variable| s: Local to a |:source|'ed Vim script. 2139 |function-argument| a: Function argument (only in a legacy function). 2140 |vim-variable| v: Global, predefined by Vim. 2141 2142 The scope name by itself can be used as a |Dictionary|. For example, to 2143 delete all script-local variables: > 2144 :for k in keys(s:) 2145 : unlet s:[k] 2146 :endfor 2147 2148 Note: in Vim9 script variables can also be local to a block of commands, see 2149 |vim9-scopes|. 2150 *buffer-variable* *b:var* *b:* 2151 A variable name that is preceded with "b:" is local to the current buffer. 2152 Thus you can have several "b:foo" variables, one for each buffer. 2153 This kind of variable is deleted when the buffer is wiped out or deleted with 2154 |:bdelete|. 2155 2156 One local buffer variable is predefined: 2157 *b:changedtick* *changetick* 2158 b:changedtick The total number of changes to the current buffer. It is 2159 incremented for each change. An undo command is also a change 2160 in this case. Resetting 'modified' when writing the buffer is 2161 also counted. 2162 This can be used to perform an action only when the buffer has 2163 changed. Example: > 2164 :if my_changedtick != b:changedtick 2165 : let my_changedtick = b:changedtick 2166 : call My_Update() 2167 :endif 2168 < You cannot change or delete the b:changedtick variable. 2169 If you need more information about the change see 2170 |listener_add()|. 2171 2172 *window-variable* *w:var* *w:* 2173 A variable name that is preceded with "w:" is local to the current window. It 2174 is deleted when the window is closed. 2175 2176 *tabpage-variable* *t:var* *t:* 2177 A variable name that is preceded with "t:" is local to the current tab page, 2178 It is deleted when the tab page is closed. {not available when compiled 2179 without the |+windows| feature} 2180 2181 *global-variable* *g:var* *g:* 2182 Inside functions and in |Vim9| script global variables are accessed with "g:". 2183 Omitting this will access a variable local to a function or script. "g:" 2184 can also be used in any other place if you like. 2185 2186 *local-variable* *l:var* *l:* 2187 Inside functions local variables are accessed without prepending anything. 2188 But you can also prepend "l:" if you like. However, without prepending "l:" 2189 you may run into reserved variable names. For example "count". By itself it 2190 refers to "v:count". Using "l:count" you can have a local variable with the 2191 same name. 2192 2193 *script-variable* *s:var* 2194 In a legacy Vim script variables starting with "s:" can be used. They cannot 2195 be accessed from outside of the scripts, thus are local to the script. 2196 In |Vim9| script the "s:" prefix can be omitted, variables are script-local by 2197 default. 2198 2199 They can be used in: 2200 - commands executed while the script is sourced 2201 - functions defined in the script 2202 - autocommands defined in the script 2203 - functions and autocommands defined in functions and autocommands which were 2204 defined in the script (recursively) 2205 - user defined commands defined in the script 2206 Thus not in: 2207 - other scripts sourced from this one 2208 - mappings 2209 - menus 2210 - etc. 2211 2212 Script variables can be used to avoid conflicts with global variable names. 2213 Take this example: > 2214 2215 let s:counter = 0 2216 function MyCounter() 2217 let s:counter = s:counter + 1 2218 echo s:counter 2219 endfunction 2220 command Tick call MyCounter() 2221 2222 You can now invoke "Tick" from any script, and the "s:counter" variable in 2223 that script will not be changed, only the "s:counter" in the script where 2224 "Tick" was defined is used. 2225 2226 Another example that does the same: > 2227 2228 let s:counter = 0 2229 command Tick let s:counter = s:counter + 1 | echo s:counter 2230 2231 When calling a function and invoking a user-defined command, the context for 2232 script variables is set to the script where the function or command was 2233 defined. 2234 2235 The script variables are also available when a function is defined inside a 2236 function that is defined in a script. Example: > 2237 2238 let s:counter = 0 2239 function StartCounting(incr) 2240 if a:incr 2241 function MyCounter() 2242 let s:counter = s:counter + 1 2243 endfunction 2244 else 2245 function MyCounter() 2246 let s:counter = s:counter - 1 2247 endfunction 2248 endif 2249 endfunction 2250 2251 This defines the MyCounter() function either for counting up or counting down 2252 when calling StartCounting(). It doesn't matter from where StartCounting() is 2253 called, the s:counter variable will be accessible in MyCounter(). 2254 2255 When the same script is sourced again it will use the same script variables. 2256 They will remain valid as long as Vim is running. This can be used to 2257 maintain a counter: > 2258 2259 if !exists("s:counter") 2260 let s:counter = 1 2261 echo "script executed for the first time" 2262 else 2263 let s:counter = s:counter + 1 2264 echo "script executed " .. s:counter .. " times now" 2265 endif 2266 2267 Note that this means that filetype plugins don't get a different set of script 2268 variables for each buffer. Use local buffer variables instead |b:var|. 2269 2270 2271 PREDEFINED VIM VARIABLES *vim-variable* *v:var* *v:* 2272 *E963* *E1063* 2273 Most variables are read-only, when a variable can be set by the user, it will 2274 be mentioned at the variable description below. The type cannot be changed. 2275 2276 *v:argv* *argv-variable* 2277 v:argv The command line arguments Vim was invoked with. This is a 2278 list of strings. The first item is the Vim command. 2279 See |v:progpath| for the command with full path. 2280 2281 *v:beval_col* *beval_col-variable* 2282 v:beval_col The number of the column, over which the mouse pointer is. 2283 This is the byte index in the |v:beval_lnum| line. 2284 Only valid while evaluating the 'balloonexpr' option. 2285 2286 *v:beval_bufnr* *beval_bufnr-variable* 2287 v:beval_bufnr The number of the buffer, over which the mouse pointer is. 2288 Only valid while evaluating the 'balloonexpr' option. 2289 2290 *v:beval_lnum* *beval_lnum-variable* 2291 v:beval_lnum The number of the line, over which the mouse pointer is. Only 2292 valid while evaluating the 'balloonexpr' option. 2293 2294 *v:beval_text* *beval_text-variable* 2295 v:beval_text The text under or after the mouse pointer. Usually a word as 2296 it is useful for debugging a C program. 'iskeyword' applies, 2297 but a dot and "->" before the position is included. When on a 2298 ']' the text before it is used, including the matching '[' and 2299 word before it. When on a Visual area within one line the 2300 highlighted text is used. Also see |<cexpr>|. 2301 Only valid while evaluating the 'balloonexpr' option. 2302 2303 *v:beval_winnr* *beval_winnr-variable* 2304 v:beval_winnr The number of the window, over which the mouse pointer is. 2305 Only valid while evaluating the 'balloonexpr' option. The 2306 first window has number zero (unlike most other places where a 2307 window gets a number). 2308 2309 *v:beval_winid* *beval_winid-variable* 2310 v:beval_winid The |window-ID| of the window, over which the mouse pointer 2311 is. Otherwise like v:beval_winnr. 2312 2313 *v:char* *char-variable* 2314 v:char Argument for evaluating 'formatexpr' and used for the typed 2315 character when using <expr> in an abbreviation |:map-<expr>|. 2316 It is also used by the |InsertCharPre|, |InsertEnter|, 2317 |KeyInputPre|, |CmdlineLeave| and |CmdlineLeavePre| events. 2318 2319 *v:charconvert_from* *charconvert_from-variable* 2320 v:charconvert_from 2321 The name of the character encoding of a file to be converted. 2322 Only valid while evaluating the 'charconvert' option. 2323 2324 *v:charconvert_to* *charconvert_to-variable* 2325 v:charconvert_to 2326 The name of the character encoding of a file after conversion. 2327 Only valid while evaluating the 'charconvert' option. 2328 2329 *v:clipmethod* 2330 v:clipmethod The current method of accessing the clipboard that is being 2331 used. Can either have the value of: 2332 wayland The Wayland protocol is being used. 2333 x11 X11 selections are being used. 2334 none The above methods are unavailable or 2335 cannot be used. 2336 If it is set to a value not in the above list, then a 2337 clipboard provider with the given name is being used for the 2338 clipboard functionality. See 'clipmethod' for more details. 2339 2340 *v:clipproviders* 2341 v:clipproviders 2342 A dictionary containing clipboard providers, see 2343 |clipboard-providers| for more information. 2344 2345 *v:cmdarg* *cmdarg-variable* 2346 v:cmdarg This variable is used for two purposes: 2347 1. The extra arguments given to a file read/write command. 2348 Currently these are "++enc=" and "++ff=". This variable is 2349 set before an autocommand event for a file read/write 2350 command is triggered. There is a leading space to make it 2351 possible to append this variable directly after the 2352 read/write command. Note: The "+cmd" argument isn't 2353 included here, because it will be executed anyway. 2354 2. When printing a PostScript file with ":hardcopy" this is 2355 the argument for the ":hardcopy" command. This can be used 2356 in 'printexpr'. 2357 2358 *v:cmdbang* *cmdbang-variable* 2359 v:cmdbang Set like v:cmdarg for a file read/write command. When a "!" 2360 was used the value is 1, otherwise it is 0. Note that this 2361 can only be used in autocommands. For user commands |<bang>| 2362 can be used. 2363 2364 *v:collate* *collate-variable* 2365 v:collate The current locale setting for collation order of the runtime 2366 environment. This allows Vim scripts to be aware of the 2367 current locale encoding. Technical: it's the value of 2368 LC_COLLATE. When not using a locale the value is "C". 2369 This variable can not be set directly, use the |:language| 2370 command. 2371 See |multi-lang|. 2372 2373 *v:colornames* 2374 v:colornames A dictionary that maps color names to hex color strings. 2375 These color names can be used with the |highlight-guifg|, 2376 |highlight-guibg|, and |highlight-guisp| parameters. 2377 2378 The key values in the dictionary (the color names) should be 2379 lower cased, because Vim looks up a color by its lower case 2380 name. 2381 2382 Updating an entry in v:colornames has no immediate effect on 2383 the syntax highlighting. The highlight commands (probably in 2384 a colorscheme script) need to be re-evaluated in order to use 2385 the updated color values. For example: > 2386 2387 :let v:colornames['fuscia'] = '#cf3ab4' 2388 :let v:colornames['mauve'] = '#915f6d' 2389 :highlight Normal guifg=fuscia guibg=mauve 2390 < 2391 This cannot be used to override the |cterm-colors| but it can 2392 be used to override other colors. For example, the X11 colors 2393 defined in the `colors/lists/default.vim` (previously defined 2394 in |rgb.txt|). When defining new color names in a plugin, the 2395 recommended practice is to set a color entry only when it does 2396 not already exist. For example: > 2397 2398 :call extend(v:colornames, { 2399 \ 'fuscia': '#cf3ab4', 2400 \ 'mauve': '#915f6d, 2401 \ }, 'keep') 2402 < 2403 Using |extend()| with the 'keep' option updates each color only 2404 if it did not exist in |v:colornames|. Doing so allows the 2405 user to choose the precise color value for a common name 2406 by setting it in their |.vimrc|. 2407 2408 It is possible to remove entries from this dictionary but 2409 doing so is NOT recommended, because it is disruptive to 2410 other scripts. It is also unlikely to achieve the desired 2411 result because the |:colorscheme| and |:highlight| commands 2412 will both automatically load all `colors/lists/default.vim` 2413 color scripts. 2414 2415 You can make changes to that file, but make sure to add new 2416 keys instead of updating existing ones, otherwise Vim will 2417 skip loading the file (thinking it hasn't been changed). 2418 2419 *v:completed_item* *completed_item-variable* 2420 v:completed_item 2421 |Dictionary| containing the |complete-items| for the most 2422 recently completed word after |CompleteDone|. The 2423 |Dictionary| is empty if the completion failed. 2424 Note: Plugins can modify the value to emulate the builtin 2425 |CompleteDone| event behavior. 2426 2427 *v:count* *count-variable* 2428 v:count The count given for the last Normal mode command. Can be used 2429 to get the count before a mapping. Read-only. Example: > 2430 :map _x :<C-U>echo "the count is " .. v:count<CR> 2431 < Note: The <C-U> is required to remove the line range that you 2432 get when typing ':' after a count. 2433 When there are two counts, as in "3d2w", they are multiplied, 2434 just like what happens in the command, "d6w" for the example. 2435 Also used for evaluating the 'formatexpr' option. 2436 "count" also works, for backwards compatibility, unless 2437 |scriptversion| is 3 or higher. 2438 2439 *v:count1* *count1-variable* 2440 v:count1 Just like "v:count", but defaults to one when no count is 2441 used. 2442 2443 *v:ctype* *ctype-variable* 2444 v:ctype The current locale setting for characters of the runtime 2445 environment. This allows Vim scripts to be aware of the 2446 current locale encoding. Technical: it's the value of 2447 LC_CTYPE. When not using a locale the value is "C". 2448 This variable can not be set directly, use the |:language| 2449 command. 2450 See |multi-lang|. 2451 2452 *v:dying* *dying-variable* 2453 v:dying Normally zero. When a deadly signal is caught it's set to 2454 one. When multiple signals are caught the number increases. 2455 Can be used in an autocommand to check if Vim didn't 2456 terminate normally. {only works on Unix} 2457 Example: > 2458 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif 2459 < Note: if another deadly signal is caught when v:dying is one, 2460 VimLeave autocommands will not be executed. 2461 2462 *v:exiting* *exiting-variable* 2463 v:exiting Vim exit code. Normally zero, non-zero when something went 2464 wrong. The value is v:null before invoking the |VimLeavePre| 2465 and |VimLeave| autocmds. See |:q|, |:x| and |:cquit|. 2466 Example: > 2467 :au VimLeave * echo "Exit value is " .. v:exiting 2468 < 2469 *v:echospace* *echospace-variable* 2470 v:echospace Number of screen cells that can be used for an `:echo` message 2471 in the last screen line before causing the |hit-enter-prompt|. 2472 Depends on 'showcmd', 'ruler' and 'columns'. You need to 2473 check 'cmdheight' for whether there are full-width lines 2474 available above the last line. 2475 2476 *v:errmsg* *errmsg-variable* 2477 v:errmsg Last error message that occurred (not necessarily displayed). 2478 It's allowed to set this variable. Example: > 2479 :let v:errmsg = "" 2480 :silent! next 2481 :if v:errmsg != "" 2482 : ... handle error 2483 < "errmsg" also works, for backwards compatibility, unless 2484 |scriptversion| is 3 or higher. 2485 2486 *v:errors* *errors-variable* *assert-return* 2487 v:errors Errors found by assert functions, such as |assert_true()|. 2488 This is a list of strings. 2489 The assert functions append an item when an assert fails. 2490 The return value indicates this: a one is returned if an item 2491 was added to v:errors, otherwise zero is returned. 2492 To remove old results make it empty: > 2493 :let v:errors = [] 2494 < If v:errors is set to anything but a list it is made an empty 2495 list by the assert function. 2496 2497 *v:event* *event-variable* 2498 v:event Dictionary containing information about the current 2499 |autocommand|. See the specific event for what it puts in 2500 this dictionary. 2501 The dictionary is emptied when the |autocommand| finishes, 2502 please refer to |dict-identity| for how to get an independent 2503 copy of it. Use |deepcopy()| if you want to keep the 2504 information after the event triggers. Example: > 2505 au TextYankPost * let g:foo = deepcopy(v:event) 2506 < 2507 *v:exception* *exception-variable* 2508 v:exception The value of the exception most recently caught and not 2509 finished. See also |v:stacktrace|, |v:throwpoint|, and 2510 |throw-variables|. 2511 Example: > 2512 :try 2513 : throw "oops" 2514 :catch /.*/ 2515 : echo "caught " .. v:exception 2516 :endtry 2517 < Output: "caught oops". 2518 2519 *v:false* *false-variable* 2520 v:false A Number with value zero. Used to put "false" in JSON. See 2521 |json_encode()|. 2522 When used as a string this evaluates to "v:false". > 2523 echo v:false 2524 < v:false ~ 2525 That is so that eval() can parse the string back to the same 2526 value. Read-only. 2527 In |Vim9| script "false" can be used which has a boolean type. 2528 2529 *v:fcs_reason* *fcs_reason-variable* 2530 v:fcs_reason The reason why the |FileChangedShell| event was triggered. 2531 Can be used in an autocommand to decide what to do and/or what 2532 to set v:fcs_choice to. Possible values: 2533 deleted file no longer exists 2534 conflict file contents, mode or timestamp was 2535 changed and buffer is modified 2536 changed file contents has changed 2537 mode mode of file changed 2538 time only file timestamp changed 2539 2540 *v:fcs_choice* *fcs_choice-variable* 2541 v:fcs_choice What should happen after a |FileChangedShell| event was 2542 triggered. Can be used in an autocommand to tell Vim what to 2543 do with the affected buffer: 2544 reload Reload the buffer (does not work if 2545 the file was deleted). 2546 edit Reload the buffer and detect the 2547 values for options such as 2548 'fileformat', 'fileencoding', 'binary' 2549 (does not work if the file was 2550 deleted). 2551 ask Ask the user what to do, as if there 2552 was no autocommand. Except that when 2553 only the timestamp changed nothing 2554 will happen. 2555 <empty> Nothing, the autocommand should do 2556 everything that needs to be done. 2557 The default is empty. If another (invalid) value is used then 2558 Vim behaves like it is empty, there is no warning message. 2559 2560 *v:fname* *fname-variable* 2561 v:fname When evaluating 'includeexpr': the file name that was 2562 detected. Empty otherwise. 2563 2564 *v:fname_in* *fname_in-variable* 2565 v:fname_in The name of the input file. Valid while evaluating: 2566 option used for ~ 2567 'charconvert' file to be converted 2568 'diffexpr' original file 2569 'patchexpr' original file 2570 'printexpr' file to be printed 2571 And set to the swap file name for |SwapExists|. 2572 2573 *v:fname_out* *fname_out-variable* 2574 v:fname_out The name of the output file. Only valid while 2575 evaluating: 2576 option used for ~ 2577 'charconvert' resulting converted file (*) 2578 'diffexpr' output of diff 2579 'patchexpr' resulting patched file 2580 (*) When doing conversion for a write command (e.g., ":w 2581 file") it will be equal to v:fname_in. When doing conversion 2582 for a read command (e.g., ":e file") it will be a temporary 2583 file and different from v:fname_in. 2584 2585 *v:fname_new* *fname_new-variable* 2586 v:fname_new The name of the new version of the file. Only valid while 2587 evaluating 'diffexpr'. 2588 2589 *v:fname_diff* *fname_diff-variable* 2590 v:fname_diff The name of the diff (patch) file. Only valid while 2591 evaluating 'patchexpr'. 2592 2593 *v:folddashes* *folddashes-variable* 2594 v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed 2595 fold. 2596 Read-only in the |sandbox|. |fold-foldtext| 2597 2598 *v:foldlevel* *foldlevel-variable* 2599 v:foldlevel Used for 'foldtext': foldlevel of closed fold. 2600 Read-only in the |sandbox|. |fold-foldtext| 2601 2602 *v:foldend* *foldend-variable* 2603 v:foldend Used for 'foldtext': last line of closed fold. 2604 Read-only in the |sandbox|. |fold-foldtext| 2605 2606 *v:foldstart* *foldstart-variable* 2607 v:foldstart Used for 'foldtext': first line of closed fold. 2608 Read-only in the |sandbox|. |fold-foldtext| 2609 2610 *v:hlsearch* *hlsearch-variable* 2611 v:hlsearch Variable that indicates whether search highlighting is on. 2612 Setting it makes sense only if 'hlsearch' is enabled which 2613 requires |+extra_search|. Setting this variable to zero acts 2614 like the |:nohlsearch| command, setting it to one acts like > 2615 let &hlsearch = &hlsearch 2616 < Note that the value is restored when returning from a 2617 function. |function-search-undo|. 2618 2619 *v:imagebackend* 2620 v:imagebackend Indicates the current image backend being used, see 2621 'imageprotocol'. It may have one of the following values: 2622 "none" no image backend being used 2623 "gui" GUI specific image backend being used 2624 "kitty" kitty graphics protocol being used 2625 "sixel" sixel graphics being used 2626 2627 *v:insertmode* *insertmode-variable* 2628 v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand 2629 events. Values: 2630 i Insert mode 2631 r Replace mode 2632 v Virtual Replace mode 2633 2634 *v:key* *key-variable* 2635 v:key Key of the current item of a |Dictionary|. Only valid while 2636 evaluating the expression used with |map()| and |filter()|. 2637 Read-only. 2638 2639 *v:lang* *lang-variable* 2640 v:lang The current locale setting for messages of the runtime 2641 environment. This allows Vim scripts to be aware of the 2642 current language. Technical: it's the value of LC_MESSAGES. 2643 The value is system dependent. 2644 This variable can not be set directly, use the |:language| 2645 command. 2646 It can be different from |v:ctype| when messages are desired 2647 in a different language than what is used for character 2648 encoding. See |multi-lang|. 2649 2650 *v:lc_time* *lc_time-variable* 2651 v:lc_time The current locale setting for time messages of the runtime 2652 environment. This allows Vim scripts to be aware of the 2653 current language. Technical: it's the value of LC_TIME. 2654 This variable can not be set directly, use the |:language| 2655 command. See |multi-lang|. 2656 2657 *v:lnum* *lnum-variable* 2658 v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and 2659 'indentexpr' expressions, tab page number for 'guitablabel' 2660 and 'guitabtooltip'. Only valid while one of these 2661 expressions is being evaluated. Read-only when in the 2662 |sandbox|. 2663 2664 *v:maxcol* *maxcol-variable* 2665 v:maxcol Maximum line length. Depending on where it is used it can be 2666 screen columns, characters or bytes. The value currently is 2667 2147483647 on all systems. 2668 2669 *v:mouse_win* *mouse_win-variable* 2670 v:mouse_win Window number for a mouse click obtained with |getchar()|. 2671 First window has number 1, like with |winnr()|. The value is 2672 zero when there was no mouse button click. 2673 2674 *v:mouse_winid* *mouse_winid-variable* 2675 v:mouse_winid Window ID for a mouse click obtained with |getchar()|. 2676 The value is zero when there was no mouse button click. 2677 2678 *v:mouse_lnum* *mouse_lnum-variable* 2679 v:mouse_lnum Line number for a mouse click obtained with |getchar()|. 2680 This is the text line number, not the screen line number. The 2681 value is zero when there was no mouse button click. 2682 2683 *v:mouse_col* *mouse_col-variable* 2684 v:mouse_col Column number for a mouse click obtained with |getchar()|. 2685 This is the screen column number, like with |virtcol()|. The 2686 value is zero when there was no mouse button click. 2687 2688 *v:none* *none-variable* *None* 2689 v:none An empty String. Used to put an empty item in JSON. See 2690 |json_encode()|. 2691 This can also be used as a function argument to use the 2692 default value, see |none-function_argument|. 2693 When used as a number this evaluates to zero. 2694 When used as a string this evaluates to "v:none". > 2695 echo v:none 2696 < v:none ~ 2697 That is so that eval() can parse the string back to the same 2698 value. Read-only. 2699 Note that using `== v:none` and `!= v:none` will often give 2700 an error. Instead, use `is v:none` and `isnot v:none` . 2701 2702 *v:null* *null-variable* 2703 v:null An empty String. Used to put "null" in JSON. See 2704 |json_encode()|. 2705 When used as a number this evaluates to zero. 2706 When used as a string this evaluates to "v:null". > 2707 echo v:null 2708 < v:null ~ 2709 That is so that eval() can parse the string back to the same 2710 value. Read-only. 2711 In |Vim9| script `null` can be used without "v:". 2712 In some places `v:null` and `null` can be used for a List, 2713 Dict, Job, etc. that is not set. That is slightly different 2714 than an empty List, Dict, etc. 2715 2716 *v:numbermax* *numbermax-variable* 2717 v:numbermax Maximum value of a number. 2718 2719 *v:numbermin* *numbermin-variable* 2720 v:numbermin Minimum value of a number (negative). 2721 2722 *v:numbersize* *numbersize-variable* 2723 v:numbersize Number of bits in a Number. This is normally 64, but on some 2724 systems it may be 32. 2725 2726 *v:oldfiles* *oldfiles-variable* 2727 v:oldfiles List of file names that is loaded from the |viminfo| file on 2728 startup. These are the files that Vim remembers marks for. 2729 The length of the List is limited by the ' argument of the 2730 'viminfo' option (default is 100). 2731 When the |viminfo| file is not used the List is empty. 2732 Also see |:oldfiles| and |c_#<|. 2733 The List can be modified, but this has no effect on what is 2734 stored in the |viminfo| file later. If you use values other 2735 than String this will cause trouble. 2736 {only when compiled with the |+viminfo| feature} 2737 2738 *v:option_new* 2739 v:option_new New value of the option. Valid while executing an |OptionSet| 2740 autocommand. 2741 *v:option_old* 2742 v:option_old Old value of the option. Valid while executing an |OptionSet| 2743 autocommand. Depending on the command used for setting and 2744 the kind of option this is either the local old value or the 2745 global old value. 2746 *v:option_oldlocal* 2747 v:option_oldlocal 2748 Old local value of the option. Valid while executing an 2749 |OptionSet| autocommand. 2750 *v:option_oldglobal* 2751 v:option_oldglobal 2752 Old global value of the option. Valid while executing an 2753 |OptionSet| autocommand. 2754 *v:option_type* 2755 v:option_type Scope of the set command. Valid while executing an 2756 |OptionSet| autocommand. Can be either "global" or "local" 2757 *v:option_command* 2758 v:option_command 2759 Command used to set the option. Valid while executing an 2760 |OptionSet| autocommand. 2761 value option was set via ~ 2762 "setlocal" |:setlocal| or ":let l:xxx" 2763 "setglobal" |:setglobal| or ":let g:xxx" 2764 "set" |:set| or |:let| 2765 "modeline" |modeline| 2766 *v:operator* *operator-variable* 2767 v:operator The last operator given in Normal mode. This is a single 2768 character except for commands starting with <g> or <z>, 2769 in which case it is two characters. Best used alongside 2770 |v:prevcount| and |v:register|. Useful if you want to cancel 2771 Operator-pending mode and then use the operator, e.g.: > 2772 :omap O <Esc>:call MyMotion(v:operator)<CR> 2773 < The value remains set until another operator is entered, thus 2774 don't expect it to be empty. 2775 v:operator is not set for |:delete|, |:yank| or other Ex 2776 commands. 2777 Read-only. 2778 2779 *v:prevcount* *prevcount-variable* 2780 v:prevcount The count given for the last but one Normal mode command. 2781 This is the v:count value of the previous command. Useful if 2782 you want to cancel Visual or Operator-pending mode and then 2783 use the count, e.g.: > 2784 :vmap % <Esc>:call MyFilter(v:prevcount)<CR> 2785 < Read-only. 2786 2787 *v:profiling* *profiling-variable* 2788 v:profiling Normally zero. Set to one after using ":profile start". 2789 See |profiling|. 2790 2791 *v:progname* *progname-variable* 2792 v:progname Contains the name (with path removed) with which Vim was 2793 invoked. Allows you to do special initialisations for |view|, 2794 |evim| etc., or any other name you might symlink to Vim. 2795 Read-only. 2796 2797 *v:progpath* *progpath-variable* 2798 v:progpath Contains the command with which Vim was invoked, in a form 2799 that when passed to the shell will run the same Vim executable 2800 as the current one (if $PATH remains unchanged). 2801 Useful if you want to message a Vim server using a 2802 |--remote-expr|. 2803 To get the full path use: > 2804 echo exepath(v:progpath) 2805 < If the command has a relative path it will be expanded to the 2806 full path, so that it still works after `:cd`. Thus starting 2807 "./vim" results in "/home/user/path/to/vim/src/vim". 2808 On Linux and other systems it will always be the full path. 2809 On Mac it may just be "vim" and using exepath() as mentioned 2810 above should be used to get the full path. 2811 On MS-Windows the executable may be called "vim.exe", but the 2812 ".exe" is not added to v:progpath. 2813 Read-only. 2814 2815 *v:python3_version* *python3-version-variable* 2816 v:python3_version 2817 Version of Python 3 that Vim was built against. When 2818 Python is loaded dynamically (|python-dynamic|), this version 2819 should exactly match the Python library up to the minor 2820 version (e.g. 3.10.2 and 3.10.3 are compatible as the minor 2821 version is "10", whereas 3.9.4 and 3.10.3 are not compatible). 2822 When |python-stable-abi| is used, this will be the minimum 2823 Python version that you can use instead. (e.g. if 2824 v:python3_version indicates 3.9, you can use 3.9, 3.10, or 2825 anything above). 2826 2827 This number is encoded as a hex number following Python ABI 2828 versioning conventions. Do the following to have a 2829 human-readable full version in hex: > 2830 echo printf("%08X", v:python3_version) 2831 < You can obtain only the minor version by doing: > 2832 echo and(v:python3_version>>16,0xff) 2833 < Read-only. 2834 2835 *v:register* *register-variable* 2836 v:register The name of the register in effect for the current normal mode 2837 command (regardless of whether that command actually used a 2838 register). Or for the currently executing normal mode mapping 2839 (use this in custom commands that take a register). 2840 If none is supplied it is the default register '"', unless 2841 'clipboard' contains "unnamed" or "unnamedplus", then it is 2842 '*' or '+'. 2843 Also see |getreg()| and |setreg()| 2844 2845 *v:scrollstart* *scrollstart-variable* 2846 v:scrollstart String describing the script or function that caused the 2847 screen to scroll up. It's only set when it is empty, thus the 2848 first reason is remembered. It is set to "Unknown" for a 2849 typed command. 2850 This can be used to find out why your script causes the 2851 hit-enter prompt. 2852 2853 *v:servername* *servername-variable* 2854 v:servername The resulting registered |client-server-name| if any. 2855 Read-only. 2856 2857 2858 v:searchforward *v:searchforward* *searchforward-variable* 2859 Search direction: 1 after a forward search, 0 after a 2860 backward search. It is reset to forward when directly setting 2861 the last search pattern, see |quote/|. 2862 Note that the value is restored when returning from a 2863 function. |function-search-undo|. 2864 Read-write. 2865 2866 *v:shell_error* *shell_error-variable* 2867 v:shell_error Result of the last shell command. When non-zero, the last 2868 shell command had an error. When zero, there was no problem. 2869 This only works when the shell returns the error code to Vim. 2870 The value -1 is often used when the command could not be 2871 executed. Read-only. 2872 Example: > 2873 :!mv foo bar 2874 :if v:shell_error 2875 : echo 'could not rename "foo" to "bar"!' 2876 :endif 2877 < "shell_error" also works, for backwards compatibility, unless 2878 |scriptversion| is 3 or higher. 2879 2880 *v:sizeofint* *sizeofint-variable* 2881 v:sizeofint Number of bytes in an int. Depends on how Vim was compiled. 2882 This is only useful for deciding whether a test will give the 2883 expected result. 2884 2885 *v:sizeoflong* *sizeoflong-variable* 2886 v:sizeoflong Number of bytes in a long. Depends on how Vim was compiled. 2887 This is only useful for deciding whether a test will give the 2888 expected result. 2889 2890 *v:sizeofpointer* *sizeofpointer-variable* 2891 v:sizeofpointer Number of bytes in a pointer. Depends on how Vim was 2892 compiled. This is only useful for deciding whether a test 2893 will give the expected result. 2894 2895 *v:stacktrace* *stacktrace-variable* 2896 v:stacktrace The stack trace of the exception most recently caught and 2897 not finished. Refer to |getstacktrace()| for the structure of 2898 stack trace. See also |v:exception|, |v:throwpoint|, and 2899 |throw-variables|. 2900 2901 *v:statusmsg* *statusmsg-variable* 2902 v:statusmsg Last given status message. It's allowed to set this variable. 2903 2904 *v:swapname* *swapname-variable* 2905 v:swapname Only valid when executing |SwapExists| autocommands: Name of 2906 the swap file found. Read-only. 2907 2908 *v:swapchoice* *swapchoice-variable* 2909 v:swapchoice |SwapExists| autocommands can set this to the selected choice 2910 for handling an existing swap file: 2911 'o' Open read-only 2912 'e' Edit anyway 2913 'r' Recover 2914 'd' Delete swapfile 2915 'q' Quit 2916 'a' Abort 2917 The value should be a single-character string. An empty value 2918 results in the user being asked, as would happen when there is 2919 no SwapExists autocommand. The default is empty. 2920 2921 *v:swapcommand* *swapcommand-variable* 2922 v:swapcommand Normal mode command to be executed after a file has been 2923 opened. Can be used for a |SwapExists| autocommand to have 2924 another Vim open the file and jump to the right place. For 2925 example, when jumping to a tag the value is ":tag tagname\r". 2926 For ":edit +cmd file" the value is ":cmd\r". 2927 2928 *v:t_TYPE* *v:t_bool* *t_bool-variable* 2929 v:t_bool Value of |Boolean| type. Read-only. See: |type()| 2930 *v:t_channel* *t_channel-variable* 2931 v:t_channel Value of |Channel| type. Read-only. See: |type()| 2932 *v:t_dict* *t_dict-variable* 2933 v:t_dict Value of |Dictionary| type. Read-only. See: |type()| 2934 *v:t_float* *t_float-variable* 2935 v:t_float Value of |Float| type. Read-only. See: |type()| 2936 *v:t_func* *t_func-variable* 2937 v:t_func Value of |Funcref| type. Read-only. See: |type()| 2938 *v:t_job* *t_job-variable* 2939 v:t_job Value of |Job| type. Read-only. See: |type()| 2940 *v:t_list* *t_list-variable* 2941 v:t_list Value of |List| type. Read-only. See: |type()| 2942 *v:t_none* *t_none-variable* 2943 v:t_none Value of |None| type. Read-only. See: |type()| 2944 *v:t_number* *t_number-variable* 2945 v:t_number Value of |Number| type. Read-only. See: |type()| 2946 *v:t_string* *t_string-variable* 2947 v:t_string Value of |String| type. Read-only. See: |type()| 2948 *v:t_blob* *t_blob-variable* 2949 v:t_blob Value of |Blob| type. Read-only. See: |type()| 2950 *v:t_class* *t_class-variable* 2951 v:t_class Value of |class| type. Read-only. See: |type()| 2952 *v:t_object* *t_object-variable* 2953 v:t_object Value of |object| type. Read-only. See: |type()| 2954 *v:t_typealias* *t_typealias-variable* 2955 v:t_typealias Value of |typealias| type. Read-only. See: |type()| 2956 *v:t_enum* *t_enum-variable* 2957 v:t_enum Value of |enum| type. Read-only. See: |type()| 2958 *v:t_enumvalue* *t_enumvalue-variable* 2959 v:t_enumvalue Value of |enumvalue| type. Read-only. See: |type()| 2960 *v:t_tuple* *t_tuple-variable* 2961 v:t_tuple Value of |Tuple| type. Read-only. See: |type()| 2962 2963 *v:termresponse* *termresponse-variable* 2964 v:termresponse The escape sequence returned by the terminal for the |t_RV| 2965 termcap entry. It is set when Vim receives an escape sequence 2966 that starts with ESC [ or CSI, then '>' or '?' and ends in a 2967 'c', with only digits and ';' in between. 2968 When this variable is set, the TermResponse autocommand event 2969 is fired, so that you can react to the response from the 2970 terminal. The TermResponseAll event is also fired, with 2971 <amatch> set to "version". You can use |terminalprops()| to 2972 see what Vim figured out about the terminal. 2973 The response from a new xterm is: "<Esc>[> Pp ; Pv ; Pc c". 2974 Pp is the terminal type: 0 for vt100 and 1 for vt220. Pv is 2975 the patch level (since this was introduced in patch 95, it's 2976 always 95 or higher). Pc is always zero. 2977 If Pv is 141 or higher then Vim will try to request terminal 2978 codes. This only works with xterm |xterm-codes|. 2979 {only when compiled with |+termresponse| feature} 2980 2981 *v:termblinkresp* *termblinkresp-variable* 2982 v:termblinkresp The escape sequence returned by the terminal for the |t_RC| 2983 termcap entry. This is used to find out whether the terminal 2984 cursor is blinking. This is used by |term_getcursor()|. When 2985 this variable is set, the TermResponseAll autocommand event is 2986 fired, with <amatch> set to "cursorblink". 2987 2988 *v:termstyleresp* *termstyleresp-variable* 2989 v:termstyleresp The escape sequence returned by the terminal for the |t_RS| 2990 termcap entry. This is used to find out what the shape of the 2991 cursor is. This is used by |term_getcursor()|. When this 2992 variable is set, the TermResponseAll autocommand event is 2993 fired, with <amatch> set to "cursorshape". 2994 2995 *v:termrbgresp* *termrbgresp-variable* 2996 v:termrbgresp The escape sequence returned by the terminal for the |t_RB| 2997 termcap entry. This is used to find out what the terminal 2998 background color is; see 'background'. When this variable is 2999 set, the TermResponseAll autocommand event is fired, with 3000 <amatch> set to "background". 3001 3002 *v:termrfgresp* *termrfgresp-variable* 3003 v:termrfgresp The escape sequence returned by the terminal for the |t_RF| 3004 termcap entry. This is used to find out what the terminal 3005 foreground color is. When this variable is set, the 3006 TermResponseAll autocommand event is fired, with <amatch> set 3007 to "foreground". 3008 3009 *v:termu7resp* *termu7resp-variable* 3010 v:termu7resp The escape sequence returned by the terminal for the |t_u7| 3011 termcap entry. This is used to find out what the terminal 3012 does with ambiguous width characters, see 'ambiwidth'. When 3013 this variable is set, the TermResponseAll autocommand event is 3014 fired, with <amatch> set to "ambiguouswidth". 3015 3016 *v:termda1* *termda1-variable* 3017 v:termda1 The escape sequence returned by a primary device attributes 3018 (DA1) query from the terminal. When this variable is set, the 3019 TermResponseAll autocommand event is fired, with <amatch> set 3020 to "da1". Can be used to detect OSC 52 support in a terminal. 3021 3022 *v:termosc* *termosc-variable* 3023 v:termosc The escape sequence of the most recent OSC response received 3024 from the terminal. When this variable is set, the 3025 |TermResponseAll| autocommand event is fired, with <amatch> 3026 set to "osc". 3027 3028 *v:testing* *testing-variable* 3029 v:testing Must be set before using `test_garbagecollect_now()`. 3030 Also, when set certain error messages won't be shown for 2 3031 seconds. (e.g. "'dictionary' option is empty") 3032 3033 *v:this_session* *this_session-variable* 3034 v:this_session Full filename of the last loaded or saved session file. See 3035 |:mksession|. It is allowed to set this variable. When no 3036 session file has been saved, this variable is empty. 3037 "this_session" also works, for backwards compatibility, unless 3038 |scriptversion| is 3 or higher 3039 3040 *v:throwpoint* *throwpoint-variable* 3041 v:throwpoint The point where the exception most recently caught and not 3042 finished was thrown. Not set when commands are typed. See 3043 also |v:exception|, |v:stacktrace|, and |throw-variables|. 3044 Example: > 3045 :try 3046 : throw "oops" 3047 :catch /.*/ 3048 : echo "Exception from" v:throwpoint 3049 :endtry 3050 < Output: "Exception from test.vim, line 2" 3051 3052 *v:true* *true-variable* 3053 v:true A Number with value one. Used to put "true" in JSON. See 3054 |json_encode()|. 3055 When used as a string this evaluates to "v:true". > 3056 echo v:true 3057 < v:true ~ 3058 That is so that eval() can parse the string back to the same 3059 value. Read-only. 3060 In |Vim9| script "true" can be used which has a boolean type. 3061 *v:val* *val-variable* 3062 v:val Value of the current item of a |List| or |Dictionary|. Only 3063 valid while evaluating the expression used with |map()| and 3064 |filter()|. Read-only. 3065 3066 *v:version* *version-variable* 3067 v:version Version number of Vim: Major version number times 100 plus 3068 minor version number. Version 5.0 is 500. Version 5.1 3069 is 501. Read-only. "version" also works, for backwards 3070 compatibility, unless |scriptversion| is 3 or higher. 3071 Use |has()| to check if a certain patch was included, e.g.: > 3072 if has("patch-7.4.123") 3073 < Note that patch numbers are specific to the version, thus both 3074 version 5.0 and 5.1 may have a patch 123, but these are 3075 completely different. 3076 3077 *v:versionlong* *versionlong-variable* 3078 v:versionlong Like v:version, but also including the patchlevel in the last 3079 four digits. Version 8.1 with patch 123 has value 8010123. 3080 This can be used like this: > 3081 if v:versionlong >= 8010123 3082 < However, if there are gaps in the list of patches included 3083 this will not work well. This can happen if a recent patch 3084 was included into an older version, e.g. for a security fix. 3085 Use the has() function to make sure the patch is actually 3086 included. 3087 3088 *v:vim_did_enter* *vim_did_enter-variable* 3089 v:vim_did_enter Zero until most of startup is done. It is set to one just 3090 before |VimEnter| autocommands are triggered. 3091 3092 *v:vim_did_init* *vim_did_init-variable* 3093 v:vim_did_init Zero until initialization is done. It is set to one just 3094 after |vimrc| is sourced and before |load-plugins|. 3095 3096 *v:warningmsg* *warningmsg-variable* 3097 v:warningmsg Last given warning message. It's allowed to set this 3098 variable. 3099 3100 *v:wayland_display* *wayland_display-variable* 3101 v:wayland_display 3102 The name of the Wayland display that Vim is connected to. 3103 Equivalent to the $WAYLAND_DISPLAY environment variable. 3104 If this is empty, then Vim is not connected to any display. 3105 3106 *v:windowid* *windowid-variable* 3107 v:windowid When any X11 based GUI is running or when running in a 3108 terminal and Vim connects to the X server (|-X|) this will be 3109 set to the window ID. 3110 When an MS-Windows GUI is running this will be set to the 3111 window handle. 3112 Otherwise the value is zero. 3113 Note: for windows inside Vim use |winnr()| or |win_getid()|, 3114 see |window-ID|. 3115 3116 ============================================================================== 3117 4. Builtin Functions *functions* 3118 3119 See |function-list| for a list grouped by what the function is used for. 3120 3121 The alphabetic list of all builtin functions and details are in a separate 3122 help file: |builtin-functions|. 3123 3124 ============================================================================== 3125 5. Defining functions *user-functions* 3126 3127 New functions can be defined. These can be called just like builtin 3128 functions. The function takes arguments, executes a sequence of Ex commands 3129 and can return a value. 3130 3131 You can find most information about defining functions in |userfunc.txt|. 3132 For Vim9 functions, which execute much faster, support type checking and more, 3133 see |vim9.txt|. 3134 3135 ============================================================================== 3136 6. Curly braces names *curly-braces-names* 3137 3138 In most places where you can use a variable, you can use a "curly braces name" 3139 variable. This is a regular variable name with one or more expressions 3140 wrapped in braces {} like this: > 3141 my_{adjective}_variable 3142 3143 This only works in legacy Vim script, not in |Vim9| script. 3144 3145 When Vim encounters this, it evaluates the expression inside the braces, puts 3146 that in place of the expression, and re-interprets the whole as a variable 3147 name. So in the above example, if the variable "adjective" was set to 3148 "noisy", then the reference would be to "my_noisy_variable", whereas if 3149 "adjective" was set to "quiet", then it would be to "my_quiet_variable". 3150 3151 One application for this is to create a set of variables governed by an option 3152 value. An example with the 'background' option: 3153 >vim 3154 let my_light_msg = 'Do you like your light background?' 3155 let my_dark_msg = 'Do you like your dark background?' 3156 echo my_{&background}_msg 3157 < 3158 You can use multiple brace pairs: > 3159 echo my_{adverb}_{adjective}_message 3160 ...or even nest them: > 3161 echo my_{ad{end_of_word}}_message 3162 where "end_of_word" is either "verb" or "jective". 3163 3164 However, the expression inside the braces must evaluate to a valid single 3165 variable name. So, the following example's expansion is invalid because 3166 "ca + bd" is not a valid single variable name: > 3167 >vim 3168 let foo='a + b' 3169 echo c{foo}d 3170 " E121: Undefined variable: ca + bd 3171 < 3172 Curly braces also cannot be used with a |register-variable|. For example: 3173 >vim 3174 let i = 'a' 3175 let @{i} = false |" E15: invalid expression 3176 < 3177 *curly-braces-function-names* 3178 You can call and define functions by an evaluated name in a similar way as 3179 with a variable. This only works in legacy Vim script, not in |Vim9| script. 3180 Example: 3181 >vim 3182 let low_line = '_' 3183 function F_curly() 3184 return 'F{low_line}curly() is a working curly-braces-function-name' 3185 endfunction 3186 echo F{low_line}curly() 3187 < 3188 3189 ============================================================================== 3190 7. Commands *expression-commands* 3191 3192 Note: in |Vim9| script `:let` is not used. `:var` is used for variable 3193 declarations and assignments do not use a command. |vim9-declaration| 3194 3195 :let {var-name} = {expr1} *:let* *E18* 3196 Set internal variable {var-name} to the result of the 3197 expression {expr1}. The variable will get the type 3198 from the {expr}. If {var-name} didn't exist yet, it 3199 is created. 3200 3201 :let {var-name}[{idx}] = {expr1} *E689* *E1141* 3202 Set a list item to the result of the expression 3203 {expr1}. {var-name} must refer to a list and {idx} 3204 must be a valid index in that list. For nested list 3205 the index can be repeated. 3206 This cannot be used to add an item to a |List|. 3207 This cannot be used to set a byte in a String. You 3208 can do that like this: > 3209 :let var = var[0:2] .. 'X' .. var[4:] 3210 < When {var-name} is a |Blob| then {idx} can be the 3211 length of the blob, in which case one byte is 3212 appended. 3213 3214 *E711* *E719* *E1165* *E1166* *E1183* 3215 :let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710* 3216 Set a sequence of items in a |List| to the result of 3217 the expression {expr1}, which must be a list with the 3218 correct number of items. 3219 {idx1} can be omitted, zero is used instead. 3220 {idx2} can be omitted, meaning the end of the list. 3221 When the selected range of items is partly past the 3222 end of the list, items will be added. 3223 3224 *:let+=* *:let-=* *:letstar=* *:let/=* *:let%=* 3225 *:let.=* *:let..=* *E734* *E985* *E1019* 3226 :let {var} += {expr1} Like ":let {var} = {var} + {expr1}". 3227 :let {var} -= {expr1} Like ":let {var} = {var} - {expr1}". 3228 :let {var} *= {expr1} Like ":let {var} = {var} * {expr1}". 3229 :let {var} /= {expr1} Like ":let {var} = {var} / {expr1}". 3230 :let {var} %= {expr1} Like ":let {var} = {var} % {expr1}". 3231 :let {var} .= {expr1} Like ":let {var} = {var} . {expr1}". 3232 :let {var} ..= {expr1} Like ":let {var} = {var} .. {expr1}". 3233 These fail if {var} was not set yet and when the type 3234 of {var} and {expr1} don't fit the operator. 3235 `+=` modifies a |List| or a |Blob| in-place instead of 3236 creating a new one. 3237 `.=` is not supported with Vim script version 2 and 3238 later, see |vimscript-version|. 3239 3240 3241 :let ${env-name} = {expr1} *:let-environment* *:let-$* 3242 Set environment variable {env-name} to the result of 3243 the expression {expr1}. The type is always String. 3244 3245 On some systems making an environment variable empty 3246 causes it to be deleted. Many systems do not make a 3247 difference between an environment variable that is not 3248 set and an environment variable that is empty. 3249 3250 :let ${env-name} .= {expr1} 3251 :let ${env-name} ..= {expr1} 3252 Append {expr1} to the environment variable {env-name}. 3253 If the environment variable didn't exist yet this 3254 works like "=". 3255 `.=` is not supported with Vim script version 2 and 3256 later, see |vimscript-version|. 3257 3258 :let @{reg-name} = {expr1} *:let-register* *:let-@* 3259 Write the result of the expression {expr1} in register 3260 {reg-name}. {reg-name} must be a single letter, and 3261 must be the name of a writable register (see 3262 |registers|). "@@" can be used for the unnamed 3263 register, "@/" for the search pattern. 3264 If the result of {expr1} ends in a <CR> or <NL>, the 3265 register will be linewise, otherwise it will be set to 3266 characterwise. 3267 This can be used to clear the last search pattern: > 3268 :let @/ = "" 3269 < This is different from searching for an empty string, 3270 that would match everywhere. 3271 3272 :let @{reg-name} .= {expr1} 3273 :let @{reg-name} ..= {expr1} 3274 Append {expr1} to register {reg-name}. If the 3275 register was empty it's like setting it to {expr1}. 3276 `.=` is not supported with Vim script version 2 and 3277 later, see |vimscript-version|. 3278 3279 :let &{option-name} = {expr1} *:let-option* *:let-&* 3280 Set option {option-name} to the result of the 3281 expression {expr1}. A String or Number value is 3282 always converted to the type of the option. 3283 For an option local to a window or buffer the effect 3284 is just like using the |:set| command: both the local 3285 value and the global value are changed. 3286 Example: > 3287 :let &path = &path .. ',/usr/local/include' 3288 < This also works for terminal codes in the form t_xx. 3289 But only for alphanumerical names. Example: > 3290 :let &t_k1 = "\<Esc>[234;" 3291 < When the code does not exist yet it will be created as 3292 a terminal key code, there is no error. 3293 3294 :let &{option-name} .= {expr1} 3295 :let &{option-name} ..= {expr1} 3296 For a string option: Append {expr1} to the value. 3297 Does not insert a comma like |:set+=|. 3298 `.=` is not supported with Vim script version 2 and 3299 later, see |vimscript-version|. 3300 3301 :let &{option-name} += {expr1} 3302 :let &{option-name} -= {expr1} 3303 For a number or boolean option: Add or subtract 3304 {expr1}. 3305 3306 :let &l:{option-name} = {expr1} 3307 :let &l:{option-name} += {expr1} 3308 :let &l:{option-name} -= {expr1} 3309 :let &l:{option-name} .= {expr1} 3310 :let &l:{option-name} ..= {expr1} 3311 Like above, but only set the local value of an option 3312 (if there is one). Works like |:setlocal|. 3313 `.=` is not supported with Vim script version 2 and 3314 later, see |vimscript-version|. 3315 3316 :let &g:{option-name} = {expr1} 3317 :let &g:{option-name} += {expr1} 3318 :let &g:{option-name} -= {expr1} 3319 :let &g:{option-name} .= {expr1} 3320 :let &g:{option-name} ..= {expr1} 3321 Like above, but only set the global value of an option 3322 (if there is one). Works like |:setglobal|. 3323 `.=` is not supported with Vim script version 2 and 3324 later, see |vimscript-version|. 3325 3326 *E1093* *E1537* *E1538* *E1535* 3327 :let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688* 3328 {expr1} must evaluate to a |List| or a |Tuple|. The 3329 first item in the list or tuple is assigned to 3330 {name1}, the second item to {name2}, etc. 3331 The number of names must match the number of items in 3332 the |List| or |Tuple|. 3333 Each name can be one of the items of the ":let" 3334 command as mentioned above. 3335 Example: > 3336 :let [s, item] = GetItem(s) 3337 < Detail: {expr1} is evaluated first, then the 3338 assignments are done in sequence. This matters if 3339 {name2} depends on {name1}. Example: > 3340 :let x = [0, 1] 3341 :let i = 0 3342 :let [i, x[i]] = [1, 2] 3343 :echo x 3344 < The result is [0, 2]. 3345 3346 :let [{name1}, {name2}, ...] += {expr1} 3347 :let [{name1}, {name2}, ...] -= {expr1} 3348 :let [{name1}, {name2}, ...] *= {expr1} 3349 :let [{name1}, {name2}, ...] /= {expr1} 3350 :let [{name1}, {name2}, ...] %= {expr1} 3351 :let [{name1}, {name2}, ...] .= {expr1} 3352 :let [{name1}, {name2}, ...] ..= {expr1} 3353 Like above, but add, subtract, multiply, divide, 3354 modulo, or append the value for each |List| or |Tuple| 3355 item. 3356 `.=` is not supported with Vim script version 2 and 3357 later, see |vimscript-version|. 3358 3359 :let [{name}, ..., ; {lastname}] = {expr1} *E452* 3360 Like |:let-unpack| above, but the |List| or |Tuple| 3361 may have more items than there are names. A list or a 3362 tuple of the remaining items is assigned to 3363 {lastname}. If there are no remaining items, 3364 {lastname} is set to an empty list or tuple. 3365 Example: > 3366 :let [a, b; rest] = ["aval", "bval", 3, 4] 3367 :let [a, b; rest] = ("aval", "bval", 3, 4) 3368 < 3369 :let [{name}, ..., ; {lastname}] += {expr1} 3370 :let [{name}, ..., ; {lastname}] -= {expr1} 3371 :let [{name}, ..., ; {lastname}] .= {expr1} 3372 :let [{name}, ..., ; {lastname}] ..= {expr1} 3373 Like above, but add/subtract/append the value for each 3374 |List| item. 3375 `.=` is not supported with Vim script version 2 and 3376 later, see |vimscript-version|. 3377 3378 *:let=<<* *:let-heredoc* 3379 *E990* *E991* *E172* *E221* *E1145* 3380 :let {var-name} =<< [trim] [eval] {endmarker} 3381 text... 3382 text... 3383 {endmarker} 3384 Set internal variable {var-name} to a |List| 3385 containing the lines of text bounded by the string 3386 {endmarker}. 3387 3388 If "eval" is not specified, then each line of text is 3389 used as a |literal-string|, except that single quotes 3390 does not need to be doubled. 3391 If "eval" is specified, then any Vim expression in the 3392 form {expr} is evaluated and the result replaces the 3393 expression, like with |interpolated-string|. 3394 Example where $HOME is expanded: > 3395 let lines =<< trim eval END 3396 some text 3397 See the file {$HOME}/.vimrc 3398 more text 3399 END 3400 < There can be multiple Vim expressions in a single line 3401 but an expression cannot span multiple lines. If any 3402 expression evaluation fails, then the assignment 3403 fails. 3404 3405 {endmarker} must not contain white space. 3406 {endmarker} cannot start with a lower case character. 3407 The last line should end only with the {endmarker} 3408 string without any other character. Watch out for 3409 white space after {endmarker}! 3410 3411 Without "trim" any white space characters in the lines 3412 of text are preserved. If "trim" is specified before 3413 {endmarker}, then indentation is stripped so you can 3414 do: > 3415 let text =<< trim END 3416 if ok 3417 echo 'done' 3418 endif 3419 END 3420 < Results in: ["if ok", " echo 'done'", "endif"] 3421 The end marker must line up with "let" and the 3422 indentation of the first line is removed from all the 3423 text lines. 3424 Specifically: all the leading indentation exactly 3425 matching the leading indentation of the first 3426 non-empty text line is stripped from the input lines. 3427 All leading indentation exactly matching the leading 3428 indentation before `let` is stripped from the line 3429 containing {endmarker}. Note that the difference 3430 between space and tab matters here. 3431 3432 If {var-name} didn't exist yet, it is created. 3433 Cannot be followed by another command, but can be 3434 followed by a comment. 3435 3436 To avoid line continuation to be applied, consider 3437 adding 'C' to 'cpoptions': > 3438 set cpo+=C 3439 let var =<< END 3440 \ leading backslash 3441 END 3442 set cpo-=C 3443 < 3444 Examples: > 3445 let var1 =<< END 3446 Sample text 1 3447 Sample text 2 3448 Sample text 3 3449 END 3450 3451 let data =<< trim DATA 3452 1 2 3 4 3453 5 6 7 8 3454 DATA 3455 3456 let code =<< trim eval CODE 3457 let v = {10 + 20} 3458 let h = "{$HOME}" 3459 let s = "{Str1()} abc {Str2()}" 3460 let n = {MyFunc(3, 4)} 3461 CODE 3462 < 3463 *E121* 3464 :let {var-name} ... List the value of variable {var-name}. Multiple 3465 variable names may be given. Special names recognized 3466 here: *E738* 3467 g: global variables 3468 b: local buffer variables 3469 w: local window variables 3470 t: local tab page variables 3471 s: script-local variables 3472 l: local function variables 3473 v: Vim variables. 3474 This does not work in Vim9 script. |vim9-declaration| 3475 3476 :let List the values of all variables. The type of the 3477 variable is indicated before the value: 3478 <nothing> String 3479 # Number 3480 * Funcref 3481 This does not work in Vim9 script. |vim9-declaration| 3482 3483 :unl[et][!] {name} ... *:unlet* *:unl* *E108* *E795* *E1081* 3484 Remove the internal variable {name}. Several variable 3485 names can be given, they are all removed. The name 3486 may also be a |List| or |Dictionary| item. 3487 With [!] no error message is given for non-existing 3488 variables. 3489 One or more items from a |List| can be removed: > 3490 :unlet list[3] " remove fourth item 3491 :unlet list[3:] " remove fourth item to last 3492 < One item from a |Dictionary| can be removed at a time: 3493 > 3494 :unlet dict['two'] 3495 :unlet dict.two 3496 < This is especially useful to clean up used global 3497 variables and script-local variables (these are not 3498 deleted when the script ends). Function-local 3499 variables are automatically deleted when the function 3500 ends. 3501 In |Vim9| script variables declared in a function or 3502 script cannot be removed. 3503 3504 :unl[et] ${env-name} ... *:unlet-environment* *:unlet-$* 3505 Remove environment variable {env-name}. 3506 Can mix {name} and ${env-name} in one :unlet command. 3507 No error message is given for a non-existing 3508 variable, also without !. 3509 If the system does not support deleting an environment 3510 variable, it is made empty. 3511 3512 *:cons* *:const* *E1018* 3513 :cons[t] {var-name} = {expr1} 3514 :cons[t] [{name1}, {name2}, ...] = {expr1} 3515 :cons[t] [{name}, ..., ; {lastname}] = {expr1} 3516 :cons[t] {var-name} =<< [trim] [eval] {endmarker} 3517 text... 3518 text... 3519 {endmarker} 3520 Similar to |:let|, but additionally lock the variable 3521 after setting the value. This is the same as locking 3522 the variable with |:lockvar| just after |:let|, thus: > 3523 :const x = 1 3524 < is equivalent to: > 3525 :let x = 1 3526 :lockvar! x 3527 < NOTE: in Vim9 script `:const` works differently, see 3528 |vim9-declaration| and |vim9-const|. 3529 This is useful if you want to make sure the variable 3530 is not modified. If the value is a List or Dictionary 3531 literal then the items also cannot be changed: > 3532 const ll = [1, 2, 3] 3533 let ll[1] = 5 " Error! 3534 < Nested references are not locked: > 3535 let lvar = ['a'] 3536 const lconst = [0, lvar] 3537 let lconst[0] = 2 " Error! 3538 let lconst[1][0] = 'b' " OK 3539 < *E995* 3540 It is an error to specify an existing variable with 3541 |:const|. > 3542 :let x = 1 3543 :const x = 1 " Error! 3544 < *E996* 3545 Note that environment variables, option values and 3546 register values cannot be used here, since they cannot 3547 be locked. 3548 3549 :cons[t] 3550 :cons[t] {var-name} 3551 If no argument is given or only {var-name} is given, 3552 the behavior is the same as |:let|. 3553 3554 :lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv* 3555 Lock the internal variable {name}. Locking means that 3556 it can no longer be changed (until it is unlocked). 3557 A locked variable can be deleted: > 3558 :lockvar v 3559 :let v = 'asdf' " fails! 3560 :unlet v " works 3561 < *E741* *E940* *E1118* *E1119* *E1120* *E1121* *E1122* 3562 If you try to change a locked variable you get an 3563 error message: "E741: Value is locked: {name}". 3564 If you try to lock or unlock a built-in variable you 3565 get an error message: "E940: Cannot lock or unlock 3566 variable {name}". 3567 3568 [depth] is relevant when locking a |List|, a |Tuple| 3569 or a |Dictionary|. It specifies how deep the locking 3570 goes: 3571 0 Lock the variable {name} but not its 3572 value. 3573 1 Lock the |List| or |Tuple| or 3574 |Dictionary| itself, cannot add or 3575 remove items, but can still change 3576 their values. 3577 2 Also lock the values, cannot change 3578 the items. If an item is a |List| or 3579 |Tuple| or |Dictionary|, cannot add or 3580 remove items, but can still change the 3581 values. 3582 3 Like 2 but for the |List| / |Tuple| / 3583 |Dictionary| in the |List| / |Tuple| / 3584 |Dictionary|, one level deeper. 3585 The default [depth] is 2, thus when {name} is a 3586 |List|, a |Tuple| or a |Dictionary| the values cannot 3587 be changed. 3588 3589 Example with [depth] 0: > 3590 let mylist = [1, 2, 3] 3591 lockvar 0 mylist 3592 let mylist[0] = 77 " OK 3593 call add(mylist, 4) " OK 3594 let mylist = [7, 8, 9] " Error! 3595 < *E743* 3596 For unlimited depth use [!] and omit [depth]. 3597 However, there is a maximum depth of 100 to catch 3598 loops. 3599 3600 Note that when two variables refer to the same |List| 3601 and you lock one of them, the |List| will also be 3602 locked when used through the other variable. 3603 Example: > 3604 :let l = [0, 1, 2, 3] 3605 :let cl = l 3606 :lockvar l 3607 :let cl[1] = 99 " won't work! 3608 < You may want to make a copy of a list to avoid this. 3609 See |deepcopy()|. 3610 3611 *E1391* *E1392* 3612 Locking and unlocking object and class variables is 3613 currently NOT supported. 3614 3615 3616 :unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo* *E1246* 3617 Unlock the internal variable {name}. Does the 3618 opposite of |:lockvar|. 3619 3620 If {name} does not exist: 3621 - In |Vim9| script an error is given. 3622 - In legacy script this is silently ignored. 3623 3624 :if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580* 3625 :en[dif] Execute the commands until the next matching `:else` 3626 or `:endif` if {expr1} evaluates to non-zero. 3627 Although the short forms work, it is recommended to 3628 always use `:endif` to avoid confusion and to make 3629 auto-indenting work properly. 3630 3631 From Vim version 4.5 until 5.0, every Ex command in 3632 between the `:if` and `:endif` is ignored. These two 3633 commands were just to allow for future expansions in a 3634 backward compatible way. Nesting was allowed. Note 3635 that any `:else` or `:elseif` was ignored, the `else` 3636 part was not executed either. 3637 3638 You can use this to remain compatible with older 3639 versions: > 3640 :if version >= 500 3641 : version-5-specific-commands 3642 :endif 3643 < The commands still need to be parsed to find the 3644 `endif`. Sometimes an older Vim has a problem with a 3645 new command. For example, `:silent` is recognized as 3646 a `:substitute` command. In that case `:execute` can 3647 avoid problems: > 3648 :if version >= 600 3649 : execute "silent 1,$delete" 3650 :endif 3651 < 3652 In |Vim9| script `:endif` cannot be shortened, to 3653 improve script readability. 3654 NOTE: The `:append` and `:insert` commands don't work 3655 properly in between `:if` and `:endif`. 3656 3657 *:else* *:el* *E581* *E583* 3658 :el[se] Execute the commands until the next matching `:else` 3659 or `:endif` if they previously were not being 3660 executed. 3661 In |Vim9| script `:else` cannot be shortened, to 3662 improve script readability. 3663 3664 *:elseif* *:elsei* *E582* *E584* 3665 :elsei[f] {expr1} Short for `:else` `:if`, with the addition that there 3666 is no extra `:endif`. 3667 In |Vim9| script `:elseif` cannot be shortened, to 3668 improve script readability. 3669 3670 :wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw* 3671 *E170* *E585* *E588* *E733* 3672 :endw[hile] Repeat the commands between `:while` and `:endwhile`, 3673 as long as {expr1} evaluates to non-zero. 3674 When an error is detected from a command inside the 3675 loop, execution continues after the `endwhile`. 3676 Example: > 3677 :let lnum = 1 3678 :while lnum <= line("$") 3679 :call FixLine(lnum) 3680 :let lnum = lnum + 1 3681 :endwhile 3682 < 3683 In |Vim9| script `:while` and `:endwhile` cannot be 3684 shortened, to improve script readability. 3685 NOTE: The `:append` and `:insert` commands don't work 3686 properly inside a `:while` and `:for` loop. 3687 3688 :for {var} in {object} *:for* *E690* *E732* 3689 :endfo[r] *:endfo* *:endfor* 3690 Repeat the commands between `:for` and `:endfor` for 3691 each item in {object}. {object} can be a |List|, 3692 a |Tuple|, a |Blob| or a |String|. *E1177* 3693 3694 Variable {var} is set to the value of each item. 3695 In |Vim9| script the loop variable must not have been 3696 declared yet, unless when it is a 3697 global/window/tab/buffer variable. 3698 3699 When an error is detected for a command inside the 3700 loop, execution continues after the `endfor`. 3701 Changing {object} inside the loop affects what items 3702 are used. Make a copy if this is unwanted: > 3703 :for item in copy(mylist) 3704 < 3705 When {object} is a |List| and not making a copy, in 3706 legacy script Vim stores a reference to the next item 3707 in the |List| before executing the commands with the 3708 current item. Thus the current item can be removed 3709 without effect. Removing any later item means it will 3710 not be found. Thus the following example works (an 3711 inefficient way to make a |List| empty): > 3712 for item in mylist 3713 call remove(mylist, 0) 3714 endfor 3715 < Note that reordering the |List| (e.g., with sort() or 3716 reverse()) may have unexpected effects. 3717 In |Vim9| script the index is used. If an item before 3718 the current one is deleted the next item will be 3719 skipped. 3720 3721 When {object} is a |Blob|, Vim always makes a copy to 3722 iterate over. Unlike with |List|, modifying the 3723 |Blob| does not affect the iteration. 3724 3725 When {object} is a |String| each item is a string with 3726 one character, plus any combining characters. 3727 3728 In |Vim9| script `:endfor` cannot be shortened, to 3729 improve script readability. 3730 3731 :for [{var1}, {var2}, ...] in {listlist} 3732 :endfo[r] *E1140* 3733 Like `:for` above, but each item in {listlist} must be 3734 a list, of which each item is assigned to {var1}, 3735 {var2}, etc. Example: > 3736 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]] 3737 :echo getline(lnum)[col] 3738 :endfor 3739 < 3740 *:continue* *:con* *E586* 3741 :con[tinue] When used inside a `:while` or `:for` loop, jumps back 3742 to the start of the loop. 3743 If it is used after a `:try` inside the loop but 3744 before the matching `:finally` (if present), the 3745 commands following the `:finally` up to the matching 3746 `:endtry` are executed first. This process applies to 3747 all nested `:try`s inside the loop. The outermost 3748 `:endtry` then jumps back to the start of the loop. 3749 3750 In |Vim9| script `:continue` cannot be shortened, to 3751 improve script readability. 3752 3753 *:break* *:brea* *E587* 3754 :brea[k] When used inside a `:while` or `:for` loop, skips to 3755 the command after the matching `:endwhile` or 3756 `:endfor`. 3757 If it is used after a `:try` inside the loop but 3758 before the matching `:finally` (if present), the 3759 commands following the `:finally` up to the matching 3760 `:endtry` are executed first. This process applies to 3761 all nested `:try`s inside the loop. The outermost 3762 `:endtry` then jumps to the command after the loop. 3763 3764 In |Vim9| script `:break` cannot be shortened, to 3765 improve script readability. 3766 3767 :try *:try* *:endt* *:endtry* 3768 *E600* *E601* *E602* *E1032* 3769 :endt[ry] Change the error handling for the commands between 3770 `:try` and `:endtry` including everything being 3771 executed across `:source` commands, function calls, 3772 or autocommand invocations. 3773 3774 When an error or interrupt is detected and there is 3775 a `:finally` command following, execution continues 3776 after the `:finally`. Otherwise, or when the 3777 `:endtry` is reached thereafter, the next 3778 (dynamically) surrounding `:try` is checked for 3779 a corresponding `:finally` etc. Then the script 3780 processing is terminated. Whether a function 3781 definition has an "abort" argument does not matter. 3782 Example: > 3783 try | call Unknown() | finally | echomsg "cleanup" | endtry 3784 echomsg "not reached" 3785 < 3786 Moreover, an error or interrupt (dynamically) inside 3787 `:try` and `:endtry` is converted to an exception. It 3788 can be caught as if it were thrown by a `:throw` 3789 command (see `:catch`). In this case, the script 3790 processing is not terminated. 3791 3792 The value "Vim:Interrupt" is used for an interrupt 3793 exception. An error in a Vim command is converted 3794 to a value of the form "Vim({command}):{errmsg}", 3795 other errors are converted to a value of the form 3796 "Vim:{errmsg}". {command} is the full command name, 3797 and {errmsg} is the message that is displayed if the 3798 error exception is not caught, always beginning with 3799 the error number. 3800 Examples: > 3801 try | sleep 100 | catch /^Vim:Interrupt$/ | endtry 3802 try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry 3803 < 3804 In |Vim9| script `:endtry` cannot be shortened, to 3805 improve script readability. 3806 3807 *:cat* *:catch* 3808 *E603* *E604* *E605* *E654* *E1033* 3809 :cat[ch] [/{pattern}/] The following commands until the next `:catch`, 3810 `:finally`, or `:endtry` that belongs to the same 3811 `:try` as the `:catch` are executed when an exception 3812 matching {pattern} is being thrown and has not yet 3813 been caught by a previous `:catch`. Otherwise, these 3814 commands are skipped. 3815 Pattern can start with "Vim({cmd})" to indicate an 3816 exception that occurred when executing the Ex command 3817 {cmd}. When {pattern} is omitted all errors are 3818 caught. Examples: > 3819 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C) 3820 :catch /^Vim\%((\S\+)\)\=:E/ " catch all Vim errors 3821 :catch /^Vim\%((\S\+)\)\=:/ " catch errors and interrupts 3822 :catch /^Vim(write):/ " catch all errors in :write 3823 :catch /^Vim(!):/ " catch all errors in :! 3824 :catch /^Vim\%((\S\+)\)\=:E123:/ " catch error E123 3825 :catch /my-exception/ " catch user exception 3826 :catch /.*/ " catch everything 3827 :catch " same as /.*/ 3828 < 3829 Another character can be used instead of / around the 3830 {pattern}, so long as it does not have a special 3831 meaning (e.g., '|' or '"') and doesn't occur inside 3832 {pattern}. *E1067* 3833 Information about the exception is available in 3834 |v:exception|. Also see |throw-variables|. 3835 NOTE: It is not reliable to ":catch" the TEXT of 3836 an error message because it may vary in different 3837 locales. 3838 In |Vim9| script `:catch` cannot be shortened, to 3839 improve script readability. 3840 3841 *:fina* *:finally* *E606* *E607* 3842 :fina[lly] The following commands until the matching `:endtry` 3843 are executed whenever the part between the matching 3844 `:try` and the `:finally` is left: either by falling 3845 through to the `:finally` or by a `:continue`, 3846 `:break`, `:finish`, or `:return`, or by an error or 3847 interrupt or exception (see `:throw`). 3848 3849 In |Vim9| script `:finally` cannot be shortened, to 3850 improve script readability and avoid confusion with 3851 `:final`. 3852 3853 *:th* *:throw* *E608* *E1129* 3854 :th[row] {expr1} The {expr1} is evaluated and thrown as an exception. 3855 If the ":throw" is used after a `:try` but before the 3856 first corresponding `:catch`, commands are skipped 3857 until the first `:catch` matching {expr1} is reached. 3858 If there is no such `:catch` or if the ":throw" is 3859 used after a `:catch` but before the `:finally`, the 3860 commands following the `:finally` (if present) up to 3861 the matching `:endtry` are executed. If the `:throw` 3862 is after the `:finally`, commands up to the `:endtry` 3863 are skipped. At the ":endtry", this process applies 3864 again for the next dynamically surrounding `:try` 3865 (which may be found in a calling function or sourcing 3866 script), until a matching `:catch` has been found. 3867 If the exception is not caught, the command processing 3868 is terminated. 3869 Example: > 3870 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry 3871 < Note that "catch" may need to be on a separate line 3872 for when an error causes the parsing to skip the whole 3873 line and not see the "|" that separates the commands. 3874 3875 In |Vim9| script `:throw` cannot be shortened, to 3876 improve script readability. 3877 3878 *:ec* *:echo* 3879 :ec[ho] {expr1} ... Echoes each {expr1}, with a space in between. The 3880 first {expr1} starts on a new line. 3881 Also see |:comment|. 3882 Use "\n" to start a new line. Use "\r" to move the 3883 cursor to the first column. 3884 Uses the highlighting set by the `:echohl` command. 3885 Cannot be followed by a comment. 3886 Example: > 3887 :echo "the value of 'shell' is" &shell 3888 < *:echo-redraw* 3889 A later redraw may make the message disappear again. 3890 And since Vim mostly postpones redrawing until it's 3891 finished with a sequence of commands this happens 3892 quite often. To avoid that a command from before the 3893 `:echo` causes a redraw afterwards (redraws are often 3894 postponed until you type something), force a redraw 3895 with the `:redraw` command. Example: > 3896 :new | redraw | echo "there is a new window" 3897 < 3898 *:echon* 3899 :echon {expr1} ... Echoes each {expr1}, without anything added. Also see 3900 |:comment|. 3901 Uses the highlighting set by the `:echohl` command. 3902 Cannot be followed by a comment. 3903 Example: > 3904 :echon "the value of 'shell' is " &shell 3905 < 3906 Note the difference between using `:echo`, which is a 3907 Vim command, and `:!echo`, which is an external shell 3908 command: > 3909 :!echo % --> filename 3910 < The arguments of ":!" are expanded, see |:_%|. > 3911 :!echo "%" --> filename or "filename" 3912 < Like the previous example. Whether you see the double 3913 quotes or not depends on your 'shell'. > 3914 :echo % --> nothing 3915 < The '%' is an illegal character in an expression. > 3916 :echo "%" --> % 3917 < This just echoes the '%' character. > 3918 :echo expand("%") --> filename 3919 < This calls the expand() function to expand the '%'. 3920 3921 *:echoh* *:echohl* 3922 :echoh[l] {name} Use the highlight group {name} for the following 3923 `:echo`, `:echon` and `:echomsg` commands. Also used 3924 for the `input()` prompt. Example: > 3925 :echohl WarningMsg | echo "Don't panic!" | echohl None 3926 < Don't forget to set the group back to "None", 3927 otherwise all following echo's will be highlighted. 3928 3929 *:echom* *:echomsg* 3930 :echom[sg] {expr1} ... Echo the expression(s) as a true message, saving the 3931 message in the |message-history|. 3932 Spaces are placed between the arguments as with the 3933 `:echo` command. But unprintable characters are 3934 displayed, not interpreted. 3935 The parsing works slightly different from `:echo`, 3936 more like `:execute`. All the expressions are first 3937 evaluated and concatenated before echoing anything. 3938 If expressions does not evaluate to a Number or 3939 String, string() is used to turn it into a string. 3940 Uses the highlighting set by the `:echohl` command. 3941 Example: > 3942 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see." 3943 < See |:echo-redraw| to avoid the message disappearing 3944 when the screen is redrawn. 3945 3946 *:echow* *:echowin* *:echowindow* 3947 :[N]echow[indow] {expr1} ... 3948 Like |:echomsg| but when the messages popup window is 3949 available the message is displayed there. This means 3950 it will show for three seconds and avoid a 3951 |hit-enter| prompt. If you want to hide it before 3952 that, press Esc in Normal mode (when it would 3953 otherwise beep). If it disappears too soon you can 3954 use `:messages` to see the text. 3955 When [N] is given then the window will show up for 3956 this number of seconds. The last `:echowindow` with a 3957 count matters, it is used once only. 3958 The message window is available when Vim was compiled 3959 with the +timer and the +popupwin features. 3960 3961 *:echoe* *:echoerr* 3962 :echoe[rr] {expr1} ... Echo the expression(s) as an error message, saving the 3963 message in the |message-history|. When used in a 3964 script or function the line number will be added. 3965 Spaces are placed between the arguments as with the 3966 `:echomsg` command. When used inside a try 3967 conditional, the message is raised as an error 3968 exception instead 3969 (see |try-echoerr|). 3970 Example: > 3971 :echoerr "This script just failed!" 3972 < If you just want a highlighted message use `:echohl`. 3973 And to get a beep: > 3974 :exe "normal \<Esc>" 3975 3976 :echoc[onsole] {expr1} ... *:echoc* *:echoconsole* 3977 Intended for testing: works like `:echomsg` but when 3978 running in the GUI and started from a terminal write 3979 the text to stdout. 3980 3981 *:eval* 3982 :eval {expr} Evaluate {expr} and discard the result. Example: > 3983 :eval Getlist()->Filter()->append('$') 3984 3985 < The expression is supposed to have a side effect, 3986 since the resulting value is not used. In the example 3987 the `append()` call appends the List with text to the 3988 buffer. This is similar to `:call` but works with any 3989 expression. 3990 In |Vim9| script an expression without an effect will 3991 result in error *E1207* . This should help noticing 3992 mistakes. 3993 3994 The command can be shortened to `:ev` or `:eva`, but 3995 these are hard to recognize and therefore not to be 3996 used. 3997 3998 The command cannot be followed by "|" and another 3999 command, since "|" is seen as part of the expression. 4000 4001 4002 *:exe* *:execute* 4003 :exe[cute] {expr1} ... Executes the string that results from the evaluation 4004 of {expr1} as an Ex command. 4005 Multiple arguments are concatenated, with a space in 4006 between. To avoid the extra space use the ".." 4007 operator to concatenate strings into one argument. 4008 {expr1} is used as the processed command, command line 4009 editing keys are not recognized. 4010 Cannot be followed by a comment. 4011 Examples: > 4012 :execute "buffer" nextbuf 4013 :execute "normal" count .. "w" 4014 < 4015 ":execute" can be used to append a command to commands 4016 that don't accept a '|'. Example: > 4017 :execute '!ls' | echo "theend" 4018 4019 < ":execute" is also a nice way to avoid having to type 4020 control characters in a Vim script for a ":normal" 4021 command: > 4022 :execute "normal ixxx\<Esc>" 4023 < This has an <Esc> character, see |expr-string|. 4024 4025 Be careful to correctly escape special characters in 4026 file names. The |fnameescape()| function can be used 4027 for Vim commands, |shellescape()| for |:!| commands. 4028 Examples: > 4029 :execute "e " .. fnameescape(filename) 4030 :execute "!ls " .. shellescape(filename, 1) 4031 < 4032 Note: The executed string may be any command-line, but 4033 starting or ending "if", "while" and "for" does not 4034 always work, because when commands are skipped the 4035 ":execute" is not evaluated and Vim loses track of 4036 where blocks start and end. Also "break" and 4037 "continue" should not be inside ":execute". 4038 This example does not work, because the ":execute" is 4039 not evaluated and Vim does not see the "while", and 4040 gives an error for finding an ":endwhile": > 4041 :if 0 4042 : execute 'while i > 5' 4043 : echo "test" 4044 : endwhile 4045 :endif 4046 < 4047 It is allowed to have a "while" or "if" command 4048 completely in the executed string: > 4049 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile' 4050 < 4051 4052 *:exe-comment* 4053 ":execute", ":echo" and ":echon" cannot be followed by 4054 a comment directly, because they see the '"' as the 4055 start of a string. But, you can use '|' followed by a 4056 comment. Example: > 4057 :echo "foo" | "this is a comment 4058 4059 ============================================================================== 4060 8. Exception handling *exception-handling* 4061 4062 The Vim script language comprises an exception handling feature. This section 4063 explains how it can be used in a Vim script. 4064 4065 Exceptions may be raised by Vim on an error or on interrupt, see 4066 |catch-errors| and |catch-interrupt|. You can also explicitly throw an 4067 exception by using the ":throw" command, see |throw-catch|. 4068 4069 4070 TRY CONDITIONALS *try-conditionals* 4071 4072 Exceptions can be caught or can cause cleanup code to be executed. You can 4073 use a try conditional to specify catch clauses (that catch exceptions) and/or 4074 a finally clause (to be executed for cleanup). 4075 A try conditional begins with a |:try| command and ends at the matching 4076 |:endtry| command. In between, you can use a |:catch| command to start 4077 a catch clause, or a |:finally| command to start a finally clause. There may 4078 be none or multiple catch clauses, but there is at most one finally clause, 4079 which must not be followed by any catch clauses. The lines before the catch 4080 clauses and the finally clause is called a try block. > 4081 4082 :try 4083 : ... 4084 : ... TRY BLOCK 4085 : ... 4086 :catch /{pattern}/ 4087 : ... 4088 : ... CATCH CLAUSE 4089 : ... 4090 :catch /{pattern}/ 4091 : ... 4092 : ... CATCH CLAUSE 4093 : ... 4094 :finally 4095 : ... 4096 : ... FINALLY CLAUSE 4097 : ... 4098 :endtry 4099 4100 The try conditional allows to watch code for exceptions and to take the 4101 appropriate actions. Exceptions from the try block may be caught. Exceptions 4102 from the try block and also the catch clauses may cause cleanup actions. 4103 When no exception is thrown during execution of the try block, the control 4104 is transferred to the finally clause, if present. After its execution, the 4105 script continues with the line following the ":endtry". 4106 When an exception occurs during execution of the try block, the remaining 4107 lines in the try block are skipped. The exception is matched against the 4108 patterns specified as arguments to the ":catch" commands. The catch clause 4109 after the first matching ":catch" is taken, other catch clauses are not 4110 executed. The catch clause ends when the next ":catch", ":finally", or 4111 ":endtry" command is reached - whatever is first. Then, the finally clause 4112 (if present) is executed. When the ":endtry" is reached, the script execution 4113 continues in the following line as usual. 4114 When an exception that does not match any of the patterns specified by the 4115 ":catch" commands is thrown in the try block, the exception is not caught by 4116 that try conditional and none of the catch clauses is executed. Only the 4117 finally clause, if present, is taken. The exception pends during execution of 4118 the finally clause. It is resumed at the ":endtry", so that commands after 4119 the ":endtry" are not executed and the exception might be caught elsewhere, 4120 see |try-nesting|. 4121 When during execution of a catch clause another exception is thrown, the 4122 remaining lines in that catch clause are not executed. The new exception is 4123 not matched against the patterns in any of the ":catch" commands of the same 4124 try conditional and none of its catch clauses is taken. If there is, however, 4125 a finally clause, it is executed, and the exception pends during its 4126 execution. The commands following the ":endtry" are not executed. The new 4127 exception might, however, be caught elsewhere, see |try-nesting|. 4128 When during execution of the finally clause (if present) an exception is 4129 thrown, the remaining lines in the finally clause are skipped. If the finally 4130 clause has been taken because of an exception from the try block or one of the 4131 catch clauses, the original (pending) exception is discarded. The commands 4132 following the ":endtry" are not executed, and the exception from the finally 4133 clause is propagated and can be caught elsewhere, see |try-nesting|. 4134 4135 The finally clause is also executed, when a ":break" or ":continue" for 4136 a ":while" loop enclosing the complete try conditional is executed from the 4137 try block or a catch clause. Or when a ":return" or ":finish" is executed 4138 from the try block or a catch clause of a try conditional in a function or 4139 sourced script, respectively. The ":break", ":continue", ":return", or 4140 ":finish" pends during execution of the finally clause and is resumed when the 4141 ":endtry" is reached. It is, however, discarded when an exception is thrown 4142 from the finally clause. 4143 When a ":break" or ":continue" for a ":while" loop enclosing the complete 4144 try conditional or when a ":return" or ":finish" is encountered in the finally 4145 clause, the rest of the finally clause is skipped, and the ":break", 4146 ":continue", ":return" or ":finish" is executed as usual. If the finally 4147 clause has been taken because of an exception or an earlier ":break", 4148 ":continue", ":return", or ":finish" from the try block or a catch clause, 4149 this pending exception or command is discarded. 4150 4151 For examples see |throw-catch| and |try-finally|. 4152 4153 4154 NESTING OF TRY CONDITIONALS *try-nesting* 4155 4156 Try conditionals can be nested arbitrarily. That is, a complete try 4157 conditional can be put into the try block, a catch clause, or the finally 4158 clause of another try conditional. If the inner try conditional does not 4159 catch an exception thrown in its try block or throws a new exception from one 4160 of its catch clauses or its finally clause, the outer try conditional is 4161 checked according to the rules above. If the inner try conditional is in the 4162 try block of the outer try conditional, its catch clauses are checked, but 4163 otherwise only the finally clause is executed. It does not matter for 4164 nesting, whether the inner try conditional is directly contained in the outer 4165 one, or whether the outer one sources a script or calls a function containing 4166 the inner try conditional. 4167 4168 When none of the active try conditionals catches an exception, just their 4169 finally clauses are executed. Thereafter, the script processing terminates. 4170 An error message is displayed in case of an uncaught exception explicitly 4171 thrown by a ":throw" command. For uncaught error and interrupt exceptions 4172 implicitly raised by Vim, the error message(s) or interrupt message are shown 4173 as usual. 4174 4175 For examples see |throw-catch|. 4176 4177 4178 EXAMINING EXCEPTION HANDLING CODE *except-examine* 4179 4180 Exception handling code can get tricky. If you are in doubt what happens, set 4181 'verbose' to 13 or use the ":13verbose" command modifier when sourcing your 4182 script file. Then you see when an exception is thrown, discarded, caught, or 4183 finished. When using a verbosity level of at least 14, things pending in 4184 a finally clause are also shown. This information is also given in debug mode 4185 (see |debug-scripts|). 4186 4187 4188 THROWING AND CATCHING EXCEPTIONS *throw-catch* 4189 4190 You can throw any number or string as an exception. Use the |:throw| command 4191 and pass the value to be thrown as argument: > 4192 :throw 4711 4193 :throw "string" 4194 < *throw-expression* 4195 You can also specify an expression argument. The expression is then evaluated 4196 first, and the result is thrown: > 4197 :throw 4705 + strlen("string") 4198 :throw strpart("strings", 0, 6) 4199 4200 An exception might be thrown during evaluation of the argument of the ":throw" 4201 command. Unless it is caught there, the expression evaluation is abandoned. 4202 The ":throw" command then does not throw a new exception. 4203 Example: > 4204 4205 :function! Foo(arg) 4206 : try 4207 : throw a:arg 4208 : catch /foo/ 4209 : endtry 4210 : return 1 4211 :endfunction 4212 : 4213 :function! Bar() 4214 : echo "in Bar" 4215 : return 4710 4216 :endfunction 4217 : 4218 :throw Foo("arrgh") + Bar() 4219 4220 This throws "arrgh", and "in Bar" is not displayed since Bar() is not 4221 executed. > 4222 :throw Foo("foo") + Bar() 4223 however displays "in Bar" and throws 4711. 4224 4225 Any other command that takes an expression as argument might also be 4226 abandoned by an (uncaught) exception during the expression evaluation. The 4227 exception is then propagated to the caller of the command. 4228 Example: > 4229 4230 :if Foo("arrgh") 4231 : echo "then" 4232 :else 4233 : echo "else" 4234 :endif 4235 4236 Here neither of "then" or "else" is displayed. 4237 4238 *catch-order* 4239 Exceptions can be caught by a try conditional with one or more |:catch| 4240 commands, see |try-conditionals|. The values to be caught by each ":catch" 4241 command can be specified as a pattern argument. The subsequent catch clause 4242 gets executed when a matching exception is caught. 4243 Example: > 4244 4245 :function! Foo(value) 4246 : try 4247 : throw a:value 4248 : catch /^\d\+$/ 4249 : echo "Number thrown" 4250 : catch /.*/ 4251 : echo "String thrown" 4252 : endtry 4253 :endfunction 4254 : 4255 :call Foo(0x1267) 4256 :call Foo('string') 4257 4258 The first call to Foo() displays "Number thrown", the second "String thrown". 4259 An exception is matched against the ":catch" commands in the order they are 4260 specified. Only the first match counts. So you should place the more 4261 specific ":catch" first. The following order does not make sense: > 4262 4263 : catch /.*/ 4264 : echo "String thrown" 4265 : catch /^\d\+$/ 4266 : echo "Number thrown" 4267 4268 The first ":catch" here matches always, so that the second catch clause is 4269 never taken. 4270 4271 *throw-variables* 4272 If you catch an exception by a general pattern, you may access the exact value 4273 in the variable |v:exception|: > 4274 4275 : catch /^\d\+$/ 4276 : echo "Number thrown. Value is" v:exception 4277 4278 You may also be interested where an exception was thrown. This is stored in 4279 |v:throwpoint|. And you can obtain the stack trace from |v:stacktrace|. 4280 Note that "v:exception", "v:stacktrace" and "v:throwpoint" are valid for the 4281 exception most recently caught as long it is not finished. 4282 Example: > 4283 4284 :function! Caught() 4285 : if v:exception != "" 4286 : echo 'Caught "' .. v:exception .. '" in ' .. v:throwpoint 4287 : else 4288 : echo 'Nothing caught' 4289 : endif 4290 :endfunction 4291 : 4292 :function! Foo() 4293 : try 4294 : try 4295 : try 4296 : throw 4711 4297 : finally 4298 : call Caught() 4299 : endtry 4300 : catch /.*/ 4301 : call Caught() 4302 : throw "oops" 4303 : endtry 4304 : catch /.*/ 4305 : call Caught() 4306 : finally 4307 : call Caught() 4308 : endtry 4309 :endfunction 4310 : 4311 :call Foo() 4312 4313 This displays > 4314 4315 Nothing caught 4316 Caught "4711" in function Foo, line 4 4317 Caught "oops" in function Foo, line 10 4318 Nothing caught 4319 4320 A practical Vim9 script example: The following command, "LineNumber", 4321 displays the line number in the script or function where it has been used: 4322 >vim9 4323 vim9script 4324 def Thrower(): void 4325 echo "In Thrower()" 4326 throw 'This line is the throwpoint.' 4327 enddef 4328 const TLN: func = (): string => # TLN is 'Thrown Line Number' 4329 substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "") 4330 command! LineNumber { 4331 try 4332 Thrower() 4333 catch 4334 echo $"Error on line {TLN()}" 4335 endtry 4336 } 4337 # Echoes "In Thrower()" then "Error on line 2": 4338 LineNumber 4339 < *try-nested* 4340 An exception that is not caught by a try conditional can be caught by 4341 a surrounding try conditional: > 4342 4343 :try 4344 : try 4345 : throw "foo" 4346 : catch /foobar/ 4347 : echo "foobar" 4348 : finally 4349 : echo "inner finally" 4350 : endtry 4351 :catch /foo/ 4352 : echo "foo" 4353 :endtry 4354 4355 The inner try conditional does not catch the exception, just its finally 4356 clause is executed. The exception is then caught by the outer try 4357 conditional. The example displays "inner finally" and then "foo". 4358 4359 *throw-from-catch* 4360 You can catch an exception and throw a new one to be caught elsewhere from the 4361 catch clause: > 4362 4363 :function! Foo() 4364 : throw "foo" 4365 :endfunction 4366 : 4367 :function! Bar() 4368 : try 4369 : call Foo() 4370 : catch /foo/ 4371 : echo "Caught foo, throw bar" 4372 : throw "bar" 4373 : endtry 4374 :endfunction 4375 : 4376 :try 4377 : call Bar() 4378 :catch /.*/ 4379 : echo "Caught" v:exception 4380 :endtry 4381 4382 This displays "Caught foo, throw bar" and then "Caught bar". 4383 4384 *rethrow* 4385 There is no real rethrow in the Vim script language, but you may throw 4386 "v:exception" instead: > 4387 4388 :function! Bar() 4389 : try 4390 : call Foo() 4391 : catch /.*/ 4392 : echo "Rethrow" v:exception 4393 : throw v:exception 4394 : endtry 4395 :endfunction 4396 < *try-echoerr* 4397 Note that this method cannot be used to "rethrow" Vim error or interrupt 4398 exceptions, because it is not possible to fake Vim internal exceptions. 4399 Trying so causes an error exception. You should throw your own exception 4400 denoting the situation. If you want to cause a Vim error exception containing 4401 the original error exception value, you can use the |:echoerr| command: > 4402 4403 :try 4404 : try 4405 : asdf 4406 : catch /.*/ 4407 : echoerr v:exception 4408 : endtry 4409 :catch /.*/ 4410 : echo v:exception 4411 :endtry 4412 4413 This code displays 4414 4415 Vim(echoerr):Vim:E492: Not an editor command: asdf ~ 4416 4417 4418 CLEANUP CODE *try-finally* 4419 4420 Scripts often change global settings and restore them at their end. If the 4421 user however interrupts the script by pressing CTRL-C, the settings remain in 4422 an inconsistent state. The same may happen to you in the development phase of 4423 a script when an error occurs or you explicitly throw an exception without 4424 catching it. You can solve these problems by using a try conditional with 4425 a finally clause for restoring the settings. Its execution is guaranteed on 4426 normal control flow, on error, on an explicit ":throw", and on interrupt. 4427 (Note that errors and interrupts from inside the try conditional are converted 4428 to exceptions. When not caught, they terminate the script after the finally 4429 clause has been executed.) 4430 Example: > 4431 4432 :try 4433 : let s:saved_ts = &ts 4434 : set ts=17 4435 : 4436 : " Do the hard work here. 4437 : 4438 :finally 4439 : let &ts = s:saved_ts 4440 : unlet s:saved_ts 4441 :endtry 4442 4443 This method should be used locally whenever a function or part of a script 4444 changes global settings which need to be restored on failure or normal exit of 4445 that function or script part. 4446 4447 *break-finally* 4448 Cleanup code works also when the try block or a catch clause is left by 4449 a ":continue", ":break", ":return", or ":finish". 4450 Example: > 4451 4452 :let first = 1 4453 :while 1 4454 : try 4455 : if first 4456 : echo "first" 4457 : let first = 0 4458 : continue 4459 : else 4460 : throw "second" 4461 : endif 4462 : catch /.*/ 4463 : echo v:exception 4464 : break 4465 : finally 4466 : echo "cleanup" 4467 : endtry 4468 : echo "still in while" 4469 :endwhile 4470 :echo "end" 4471 4472 This displays "first", "cleanup", "second", "cleanup", and "end". > 4473 4474 :function! Foo() 4475 : try 4476 : return 4711 4477 : finally 4478 : echo "cleanup\n" 4479 : endtry 4480 : echo "Foo still active" 4481 :endfunction 4482 : 4483 :echo Foo() "returned by Foo" 4484 4485 This displays "cleanup" and "4711 returned by Foo". You don't need to add an 4486 extra ":return" in the finally clause. (Above all, this would override the 4487 return value.) 4488 4489 *except-from-finally* 4490 Using either of ":continue", ":break", ":return", ":finish", or ":throw" in 4491 a finally clause is possible, but not recommended since it abandons the 4492 cleanup actions for the try conditional. But, of course, interrupt and error 4493 exceptions might get raised from a finally clause. 4494 Example where an error in the finally clause stops an interrupt from 4495 working correctly: > 4496 4497 :try 4498 : try 4499 : echo "Press CTRL-C for interrupt" 4500 : while 1 4501 : endwhile 4502 : finally 4503 : unlet novar 4504 : endtry 4505 :catch /novar/ 4506 :endtry 4507 :echo "Script still running" 4508 :sleep 1 4509 4510 If you need to put commands that could fail into a finally clause, you should 4511 think about catching or ignoring the errors in these commands, see 4512 |catch-errors| and |ignore-errors|. 4513 4514 4515 CATCHING ERRORS *catch-errors* 4516 4517 If you want to catch specific errors, you just have to put the code to be 4518 watched in a try block and add a catch clause for the error message. The 4519 presence of the try conditional causes all errors to be converted to an 4520 exception. No message is displayed and |v:errmsg| is not set then. To find 4521 the right pattern for the ":catch" command, you have to know how the format of 4522 the error exception is. 4523 Error exceptions have the following format: > 4524 4525 Vim({cmdname}):{errmsg} 4526 or > 4527 Vim:{errmsg} 4528 4529 {cmdname} is the name of the command that failed; the second form is used when 4530 the command name is not known. {errmsg} is the error message usually produced 4531 when the error occurs outside try conditionals. It always begins with 4532 a capital "E", followed by a two or three-digit error number, a colon, and 4533 a space. 4534 4535 Examples: 4536 4537 The command > 4538 :unlet novar 4539 normally produces the error message > 4540 E108: No such variable: "novar" 4541 which is converted inside try conditionals to an exception > 4542 Vim(unlet):E108: No such variable: "novar" 4543 4544 The command > 4545 :dwim 4546 normally produces the error message > 4547 E492: Not an editor command: dwim 4548 which is converted inside try conditionals to an exception > 4549 Vim:E492: Not an editor command: dwim 4550 4551 You can catch all ":unlet" errors by a > 4552 :catch /^Vim(unlet):/ 4553 or all errors for misspelled command names by a > 4554 :catch /^Vim:E492:/ 4555 4556 Some error messages may be produced by different commands: > 4557 :function nofunc 4558 and > 4559 :delfunction nofunc 4560 both produce the error message > 4561 E128: Function name must start with a capital: nofunc 4562 which is converted inside try conditionals to an exception > 4563 Vim(function):E128: Function name must start with a capital: nofunc 4564 or > 4565 Vim(delfunction):E128: Function name must start with a capital: nofunc 4566 respectively. You can catch the error by its number independently on the 4567 command that caused it if you use the following pattern: > 4568 :catch /^Vim(\a\+):E128:/ 4569 4570 Some commands like > 4571 :let x = novar 4572 produce multiple error messages, here: > 4573 E121: Undefined variable: novar 4574 E15: Invalid expression: novar 4575 Only the first is used for the exception value, since it is the most specific 4576 one (see |except-several-errors|). So you can catch it by > 4577 :catch /^Vim(\a\+):E121:/ 4578 4579 You can catch all errors related to the name "nofunc" by > 4580 :catch /\<nofunc\>/ 4581 4582 You can catch all Vim errors in the ":write" and ":read" commands by > 4583 :catch /^Vim(\(write\|read\)):E\d\+:/ 4584 4585 You can catch all Vim errors by the pattern > 4586 :catch /^Vim\((\a\+)\)\=:E\d\+:/ 4587 < 4588 *catch-text* 4589 NOTE: You should never catch the error message text itself: > 4590 :catch /No such variable/ 4591 only works in the English locale, but not when the user has selected 4592 a different language by the |:language| command. It is however helpful to 4593 cite the message text in a comment: > 4594 :catch /^Vim(\a\+):E108:/ " No such variable 4595 4596 4597 IGNORING ERRORS *ignore-errors* 4598 4599 You can ignore errors in a specific Vim command by catching them locally: > 4600 4601 :try 4602 : write 4603 :catch 4604 :endtry 4605 4606 But you are strongly recommended NOT to use this simple form, since it could 4607 catch more than you want. With the ":write" command, some autocommands could 4608 be executed and cause errors not related to writing, for instance: > 4609 4610 :au BufWritePre * unlet novar 4611 4612 There could even be such errors you are not responsible for as a script 4613 writer: a user of your script might have defined such autocommands. You would 4614 then hide the error from the user. 4615 It is much better to use > 4616 4617 :try 4618 : write 4619 :catch /^Vim(write):/ 4620 :endtry 4621 4622 which only catches real write errors. So catch only what you'd like to ignore 4623 intentionally. 4624 4625 For a single command that does not cause execution of autocommands, you could 4626 even suppress the conversion of errors to exceptions by the ":silent!" 4627 command: > 4628 :silent! nunmap k 4629 This works also when a try conditional is active. 4630 4631 4632 CATCHING INTERRUPTS *catch-interrupt* 4633 4634 When there are active try conditionals, an interrupt (CTRL-C) is converted to 4635 the exception "Vim:Interrupt". You can catch it like every exception. The 4636 script is not terminated, then. 4637 Example: > 4638 4639 :function! TASK1() 4640 : sleep 10 4641 :endfunction 4642 4643 :function! TASK2() 4644 : sleep 20 4645 :endfunction 4646 4647 :while 1 4648 : let command = input("Type a command: ") 4649 : try 4650 : if command == "" 4651 : continue 4652 : elseif command == "END" 4653 : break 4654 : elseif command == "TASK1" 4655 : call TASK1() 4656 : elseif command == "TASK2" 4657 : call TASK2() 4658 : else 4659 : echo "\nIllegal command:" command 4660 : continue 4661 : endif 4662 : catch /^Vim:Interrupt$/ 4663 : echo "\nCommand interrupted" 4664 : " Caught the interrupt. Continue with next prompt. 4665 : endtry 4666 :endwhile 4667 4668 You can interrupt a task here by pressing CTRL-C; the script then asks for 4669 a new command. If you press CTRL-C at the prompt, the script is terminated. 4670 4671 For testing what happens when CTRL-C would be pressed on a specific line in 4672 your script, use the debug mode and execute the |>quit| or |>interrupt| 4673 command on that line. See |debug-scripts|. 4674 4675 4676 CATCHING ALL *catch-all* 4677 4678 The commands > 4679 4680 :catch /.*/ 4681 :catch // 4682 :catch 4683 4684 catch everything, error exceptions, interrupt exceptions and exceptions 4685 explicitly thrown by the |:throw| command. This is useful at the top level of 4686 a script in order to catch unexpected things. 4687 Example: > 4688 4689 :try 4690 : 4691 : " do the hard work here 4692 : 4693 :catch /MyException/ 4694 : 4695 : " handle known problem 4696 : 4697 :catch /^Vim:Interrupt$/ 4698 : echo "Script interrupted" 4699 :catch /.*/ 4700 : echo "Internal error (" .. v:exception .. ")" 4701 : echo " - occurred at " .. v:throwpoint 4702 :endtry 4703 :" end of script 4704 4705 Note: Catching all might catch more things than you want. Thus, you are 4706 strongly encouraged to catch only for problems that you can really handle by 4707 specifying a pattern argument to the ":catch". 4708 Example: Catching all could make it nearly impossible to interrupt a script 4709 by pressing CTRL-C: > 4710 4711 :while 1 4712 : try 4713 : sleep 1 4714 : catch 4715 : endtry 4716 :endwhile 4717 4718 4719 EXCEPTIONS AND AUTOCOMMANDS *except-autocmd* 4720 4721 Exceptions may be used during execution of autocommands. Example: > 4722 4723 :autocmd User x try 4724 :autocmd User x throw "Oops!" 4725 :autocmd User x catch 4726 :autocmd User x echo v:exception 4727 :autocmd User x endtry 4728 :autocmd User x throw "Arrgh!" 4729 :autocmd User x echo "Should not be displayed" 4730 : 4731 :try 4732 : doautocmd User x 4733 :catch 4734 : echo v:exception 4735 :endtry 4736 4737 This displays "Oops!" and "Arrgh!". 4738 4739 *except-autocmd-Pre* 4740 For some commands, autocommands get executed before the main action of the 4741 command takes place. If an exception is thrown and not caught in the sequence 4742 of autocommands, the sequence and the command that caused its execution are 4743 abandoned and the exception is propagated to the caller of the command. 4744 Example: > 4745 4746 :autocmd BufWritePre * throw "FAIL" 4747 :autocmd BufWritePre * echo "Should not be displayed" 4748 : 4749 :try 4750 : write 4751 :catch 4752 : echo "Caught:" v:exception "from" v:throwpoint 4753 :endtry 4754 4755 Here, the ":write" command does not write the file currently being edited (as 4756 you can see by checking 'modified'), since the exception from the BufWritePre 4757 autocommand abandons the ":write". The exception is then caught and the 4758 script displays: > 4759 4760 Caught: FAIL from BufWrite Auto commands for "*" 4761 < 4762 *except-autocmd-Post* 4763 For some commands, autocommands get executed after the main action of the 4764 command has taken place. If this main action fails and the command is inside 4765 an active try conditional, the autocommands are skipped and an error exception 4766 is thrown that can be caught by the caller of the command. 4767 Example: > 4768 4769 :autocmd BufWritePost * echo "File successfully written!" 4770 : 4771 :try 4772 : write /i/m/p/o/s/s/i/b/l/e 4773 :catch 4774 : echo v:exception 4775 :endtry 4776 4777 This just displays: > 4778 4779 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e) 4780 4781 If you really need to execute the autocommands even when the main action 4782 fails, trigger the event from the catch clause. 4783 Example: > 4784 4785 :autocmd BufWritePre * set noreadonly 4786 :autocmd BufWritePost * set readonly 4787 : 4788 :try 4789 : write /i/m/p/o/s/s/i/b/l/e 4790 :catch 4791 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e 4792 :endtry 4793 < 4794 You can also use ":silent!": > 4795 4796 :let x = "ok" 4797 :let v:errmsg = "" 4798 :autocmd BufWritePost * if v:errmsg != "" 4799 :autocmd BufWritePost * let x = "after fail" 4800 :autocmd BufWritePost * endif 4801 :try 4802 : silent! write /i/m/p/o/s/s/i/b/l/e 4803 :catch 4804 :endtry 4805 :echo x 4806 4807 This displays "after fail". 4808 4809 If the main action of the command does not fail, exceptions from the 4810 autocommands will be catchable by the caller of the command: > 4811 4812 :autocmd BufWritePost * throw ":-(" 4813 :autocmd BufWritePost * echo "Should not be displayed" 4814 : 4815 :try 4816 : write 4817 :catch 4818 : echo v:exception 4819 :endtry 4820 < 4821 *except-autocmd-Cmd* 4822 For some commands, the normal action can be replaced by a sequence of 4823 autocommands. Exceptions from that sequence will be catchable by the caller 4824 of the command. 4825 Example: For the ":write" command, the caller cannot know whether the file 4826 had actually been written when the exception occurred. You need to tell it in 4827 some way. > 4828 4829 :if !exists("cnt") 4830 : let cnt = 0 4831 : 4832 : autocmd BufWriteCmd * if &modified 4833 : autocmd BufWriteCmd * let cnt = cnt + 1 4834 : autocmd BufWriteCmd * if cnt % 3 == 2 4835 : autocmd BufWriteCmd * throw "BufWriteCmdError" 4836 : autocmd BufWriteCmd * endif 4837 : autocmd BufWriteCmd * write | set nomodified 4838 : autocmd BufWriteCmd * if cnt % 3 == 0 4839 : autocmd BufWriteCmd * throw "BufWriteCmdError" 4840 : autocmd BufWriteCmd * endif 4841 : autocmd BufWriteCmd * echo "File successfully written!" 4842 : autocmd BufWriteCmd * endif 4843 :endif 4844 : 4845 :try 4846 : write 4847 :catch /^BufWriteCmdError$/ 4848 : if &modified 4849 : echo "Error on writing (file contents not changed)" 4850 : else 4851 : echo "Error after writing" 4852 : endif 4853 :catch /^Vim(write):/ 4854 : echo "Error on writing" 4855 :endtry 4856 4857 When this script is sourced several times after making changes, it displays 4858 first > 4859 File successfully written! 4860 then > 4861 Error on writing (file contents not changed) 4862 then > 4863 Error after writing 4864 etc. 4865 4866 *except-autocmd-ill* 4867 You cannot spread a try conditional over autocommands for different events. 4868 The following code is ill-formed: > 4869 4870 :autocmd BufWritePre * try 4871 : 4872 :autocmd BufWritePost * catch 4873 :autocmd BufWritePost * echo v:exception 4874 :autocmd BufWritePost * endtry 4875 : 4876 :write 4877 4878 4879 EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param* 4880 4881 Some programming languages allow to use hierarchies of exception classes or to 4882 pass additional information with the object of an exception class. You can do 4883 similar things in Vim. 4884 In order to throw an exception from a hierarchy, just throw the complete 4885 class name with the components separated by a colon, for instance throw the 4886 string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library. 4887 When you want to pass additional information with your exception class, add 4888 it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)" 4889 for an error when writing "myfile". 4890 With the appropriate patterns in the ":catch" command, you can catch for 4891 base classes or derived classes of your hierarchy. Additional information in 4892 parentheses can be cut out from |v:exception| with the ":substitute" command. 4893 Example: > 4894 4895 :function! CheckRange(a, func) 4896 : if a:a < 0 4897 : throw "EXCEPT:MATHERR:RANGE(" .. a:func .. ")" 4898 : endif 4899 :endfunction 4900 : 4901 :function! Add(a, b) 4902 : call CheckRange(a:a, "Add") 4903 : call CheckRange(a:b, "Add") 4904 : let c = a:a + a:b 4905 : if c < 0 4906 : throw "EXCEPT:MATHERR:OVERFLOW" 4907 : endif 4908 : return c 4909 :endfunction 4910 : 4911 :function! Div(a, b) 4912 : call CheckRange(a:a, "Div") 4913 : call CheckRange(a:b, "Div") 4914 : if (a:b == 0) 4915 : throw "EXCEPT:MATHERR:ZERODIV" 4916 : endif 4917 : return a:a / a:b 4918 :endfunction 4919 : 4920 :function! Write(file) 4921 : try 4922 : execute "write" fnameescape(a:file) 4923 : catch /^Vim(write):/ 4924 : throw "EXCEPT:IO(" .. getcwd() .. ", " .. a:file .. "):WRITEERR" 4925 : endtry 4926 :endfunction 4927 : 4928 :try 4929 : 4930 : " something with arithmetic and I/O 4931 : 4932 :catch /^EXCEPT:MATHERR:RANGE/ 4933 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "") 4934 : echo "Range error in" function 4935 : 4936 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV 4937 : echo "Math error" 4938 : 4939 :catch /^EXCEPT:IO/ 4940 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "") 4941 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "") 4942 : if file !~ '^/' 4943 : let file = dir .. "/" .. file 4944 : endif 4945 : echo 'I/O error for "' .. file .. '"' 4946 : 4947 :catch /^EXCEPT/ 4948 : echo "Unspecified error" 4949 : 4950 :endtry 4951 4952 The exceptions raised by Vim itself (on error or when pressing CTRL-C) use 4953 a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself 4954 exceptions with the "Vim" prefix; they are reserved for Vim. 4955 Vim error exceptions are parameterized with the name of the command that 4956 failed, if known. See |catch-errors|. 4957 4958 4959 PECULIARITIES 4960 *except-compat* 4961 The exception handling concept requires that the command sequence causing the 4962 exception is aborted immediately and control is transferred to finally clauses 4963 and/or a catch clause. 4964 4965 In the Vim script language there are cases where scripts and functions 4966 continue after an error: in functions without the "abort" flag or in a command 4967 after ":silent!", control flow goes to the following line, and outside 4968 functions, control flow goes to the line following the outermost ":endwhile" 4969 or ":endif". On the other hand, errors should be catchable as exceptions 4970 (thus, requiring the immediate abortion). 4971 4972 This problem has been solved by converting errors to exceptions and using 4973 immediate abortion (if not suppressed by ":silent!") only when a try 4974 conditional is active. This is no restriction since an (error) exception can 4975 be caught only from an active try conditional. If you want an immediate 4976 termination without catching the error, just use a try conditional without 4977 catch clause. (You can cause cleanup code being executed before termination 4978 by specifying a finally clause.) 4979 4980 When no try conditional is active, the usual abortion and continuation 4981 behavior is used instead of immediate abortion. This ensures compatibility of 4982 scripts written for Vim 6.1 and earlier. 4983 4984 However, when sourcing an existing script that does not use exception handling 4985 commands (or when calling one of its functions) from inside an active try 4986 conditional of a new script, you might change the control flow of the existing 4987 script on error. You get the immediate abortion on error and can catch the 4988 error in the new script. If however the sourced script suppresses error 4989 messages by using the ":silent!" command (checking for errors by testing 4990 |v:errmsg| if appropriate), its execution path is not changed. The error is 4991 not converted to an exception. (See |:silent|.) So the only remaining cause 4992 where this happens is for scripts that don't care about errors and produce 4993 error messages. You probably won't want to use such code from your new 4994 scripts. 4995 4996 *except-syntax-err* 4997 Syntax errors in the exception handling commands are never caught by any of 4998 the ":catch" commands of the try conditional they belong to. Its finally 4999 clauses, however, is executed. 5000 Example: > 5001 5002 :try 5003 : try 5004 : throw 4711 5005 : catch /\(/ 5006 : echo "in catch with syntax error" 5007 : catch 5008 : echo "inner catch-all" 5009 : finally 5010 : echo "inner finally" 5011 : endtry 5012 :catch 5013 : echo 'outer catch-all caught "' .. v:exception .. '"' 5014 : finally 5015 : echo "outer finally" 5016 :endtry 5017 5018 This displays: > 5019 inner finally 5020 outer catch-all caught "Vim(catch):E54: Unmatched \(" 5021 outer finally 5022 The original exception is discarded and an error exception is raised, instead. 5023 5024 *except-single-line* 5025 The ":try", ":catch", ":finally", and ":endtry" commands can be put on 5026 a single line, but then syntax errors may make it difficult to recognize the 5027 "catch" line, thus you better avoid this. 5028 Example: > 5029 :try | unlet! foo # | catch | endtry 5030 raises an error exception for the trailing characters after the ":unlet!" 5031 argument, but does not see the ":catch" and ":endtry" commands, so that the 5032 error exception is discarded and the "E488: Trailing characters" message gets 5033 displayed. 5034 5035 *except-several-errors* 5036 When several errors appear in a single command, the first error message is 5037 usually the most specific one and therefore converted to the error exception. 5038 Example: > 5039 echo novar 5040 causes > 5041 E121: Undefined variable: novar 5042 E15: Invalid expression: novar 5043 The value of the error exception inside try conditionals is: > 5044 Vim(echo):E121: Undefined variable: novar 5045 < *except-syntax-error* 5046 But when a syntax error is detected after a normal error in the same command, 5047 the syntax error is used for the exception being thrown. 5048 Example: > 5049 unlet novar # 5050 causes > 5051 E108: No such variable: "novar" 5052 E488: Trailing characters 5053 The value of the error exception inside try conditionals is: > 5054 Vim(unlet):E488: Trailing characters 5055 This is done because the syntax error might change the execution path in a way 5056 not intended by the user. Example: > 5057 try 5058 try | unlet novar # | catch | echo v:exception | endtry 5059 catch /.*/ 5060 echo "outer catch:" v:exception 5061 endtry 5062 This displays "outer catch: Vim(unlet):E488: Trailing characters", and then 5063 a "E600: Missing :endtry" error message is given, see |except-single-line|. 5064 5065 ============================================================================== 5066 9. Examples *eval-examples* 5067 5068 Printing in Binary ~ 5069 > 5070 :" The function Nr2Bin() returns the binary string representation of a number. 5071 :func Nr2Bin(nr) 5072 : let n = a:nr 5073 : let r = "" 5074 : while n 5075 : let r = '01'[n % 2] .. r 5076 : let n = n / 2 5077 : endwhile 5078 : return r 5079 :endfunc 5080 5081 :" The function String2Bin() converts each character in a string to a 5082 :" binary string, separated with dashes. 5083 :func String2Bin(str) 5084 : let out = '' 5085 : for ix in range(strlen(a:str)) 5086 : let out = out .. '-' .. Nr2Bin(char2nr(a:str[ix])) 5087 : endfor 5088 : return out[1:] 5089 :endfunc 5090 5091 Example of its use: > 5092 :echo Nr2Bin(32) 5093 result: "100000" > 5094 :echo String2Bin("32") 5095 result: "110011-110010" 5096 5097 5098 Sorting lines ~ 5099 5100 This example sorts lines with a specific compare function. > 5101 5102 :func SortBuffer() 5103 : let lines = getline(1, '$') 5104 : call sort(lines, function("Strcmp")) 5105 : call setline(1, lines) 5106 :endfunction 5107 5108 As a one-liner: > 5109 :call setline(1, sort(getline(1, '$'), function("Strcmp"))) 5110 5111 5112 scanf() replacement ~ 5113 *sscanf* 5114 There is no sscanf() function in Vim. If you need to extract parts from a 5115 line, you can use matchstr() and substitute() to do it. This example shows 5116 how to get the file name, line number and column number out of a line like 5117 "foobar.txt, 123, 45". > 5118 :" Set up the match bit 5119 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)' 5120 :"get the part matching the whole expression 5121 :let l = matchstr(line, mx) 5122 :"get each item out of the match 5123 :let file = substitute(l, mx, '\1', '') 5124 :let lnum = substitute(l, mx, '\2', '') 5125 :let col = substitute(l, mx, '\3', '') 5126 5127 The input is in the variable "line", the results in the variables "file", 5128 "lnum" and "col". (idea from Michael Geddes) 5129 5130 5131 Getting the scriptnames in a Dictionary ~ 5132 *scriptnames-dictionary* 5133 The `:scriptnames` command can be used to get a list of all script files that 5134 have been sourced. There is also the `getscriptinfo()` function, but the 5135 information returned is not exactly the same. If you need to use the list, 5136 this Vim9 script can be used as a base. It builds a dictionary with each 5137 script's `<SNR>` and filepath: 5138 >vim9 5139 vim9script 5140 # Build a scripts dictionary, indexed by SNR, and return it. 5141 def Scripts(scripts: dict<string> = {}): dict<string> 5142 for info in getscriptinfo() 5143 if scripts->has_key(info.sid) 5144 continue 5145 endif 5146 scripts[info.sid] = info.name 5147 endfor 5148 return scripts 5149 enddef 5150 # Example usage: echo the SNRs of the loaded vimrc and gvimrc (if any) 5151 echo Scripts()->filter((_, v) => v =~ '\v[._]g?vimrc') 5152 < 5153 5154 ============================================================================== 5155 10. Vim script versions *vimscript-version* *vimscript-versions* 5156 *scriptversion* 5157 Over time many features have been added to Vim script. This includes Ex 5158 commands, functions, variable types, etc. Each individual feature can be 5159 checked with the |has()| and |exists()| functions. 5160 5161 Sometimes old syntax of functionality gets in the way of making Vim better. 5162 When support is taken away this will break older Vim scripts. To make this 5163 explicit the |:scriptversion| command can be used. When a Vim script is not 5164 compatible with older versions of Vim this will give an explicit error, 5165 instead of failing in mysterious ways. 5166 5167 When using a legacy function, defined with `:function`, in |Vim9| script then 5168 scriptversion 4 is used. 5169 5170 *scriptversion-1* > 5171 :scriptversion 1 5172 < This is the original Vim script, same as not using a |:scriptversion| 5173 command. Can be used to go back to old syntax for a range of lines. 5174 Test for support with: > 5175 has('vimscript-1') 5176 5177 < *scriptversion-2* > 5178 :scriptversion 2 5179 < String concatenation with "." is not supported, use ".." instead. 5180 This avoids the ambiguity using "." for Dict member access and 5181 floating point numbers. Now ".5" means the number 0.5. 5182 5183 *scriptversion-3* > 5184 :scriptversion 3 5185 < All |vim-variable|s must be prefixed by "v:". E.g. "version" doesn't 5186 work as |v:version| anymore, it can be used as a normal variable. 5187 Same for some obvious names as "count" and others. 5188 5189 Test for support with: > 5190 has('vimscript-3') 5191 < 5192 *scriptversion-4* > 5193 :scriptversion 4 5194 < Numbers with a leading zero are not recognized as octal. "0o" or "0O" 5195 is still recognized as octal. With the 5196 previous version you get: > 5197 echo 017 " displays 15 (octal) 5198 echo 0o17 " displays 15 (octal) 5199 echo 018 " displays 18 (decimal) 5200 < with script version 4: > 5201 echo 017 " displays 17 (decimal) 5202 echo 0o17 " displays 15 (octal) 5203 echo 018 " displays 18 (decimal) 5204 < Also, it is possible to use single quotes inside numbers to make them 5205 easier to read: > 5206 echo 1'000'000 5207 < The quotes must be surrounded by digits. 5208 5209 Test for support with: > 5210 has('vimscript-4') 5211 5212 ============================================================================== 5213 11. No +eval feature *no-eval-feature* 5214 5215 When the |+eval| feature was disabled at compile time, none of the expression 5216 evaluation commands are available. To prevent this from causing Vim scripts 5217 to generate all kinds of errors, the ":if" and ":endif" commands are still 5218 recognized, though the argument of the ":if" and everything between the ":if" 5219 and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but 5220 only if the commands are at the start of the line. The ":else" command is not 5221 recognized. 5222 5223 Example of how to avoid executing commands when the |+eval| feature is 5224 missing: > 5225 5226 :if 1 5227 : echo "Expression evaluation is compiled in" 5228 :else 5229 : echo "You will _never_ see this message" 5230 :endif 5231 5232 To execute a command only when the |+eval| feature is disabled can be done in 5233 two ways. The simplest is to exit the script (or Vim) prematurely: > 5234 if 1 5235 echo "commands executed with +eval" 5236 finish 5237 endif 5238 args " command executed without +eval 5239 5240 If you do not want to abort loading the script you can use a trick, as this 5241 example shows: > 5242 5243 silent! while 0 5244 set history=111 5245 silent! endwhile 5246 5247 When the |+eval| feature is available the command is skipped because of the 5248 "while 0". Without the |+eval| feature the "while 0" is an error, which is 5249 silently ignored, and the command is executed. 5250 5251 ============================================================================== 5252 12. The sandbox *eval-sandbox* *sandbox* 5253 5254 The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and 5255 'foldtext' options may be evaluated in a sandbox. This means that you are 5256 protected from these expressions having nasty side effects. This gives some 5257 safety for when these options are set from a modeline. It is also used when 5258 the command from a tags file is executed and for CTRL-R = in the command line. 5259 The sandbox is also used for the |:sandbox| command. 5260 *E48* 5261 These items are not allowed in the sandbox: 5262 - changing the buffer text 5263 - defining or changing mapping, autocommands, user commands 5264 - setting certain options (see |option-summary|) 5265 - setting certain v: variables (see |v:var|) *E794* 5266 - executing a shell command 5267 - reading or writing a file 5268 - jumping to another buffer or editing a file 5269 - executing Python, Perl, etc. commands 5270 This is not guaranteed 100% secure, but it should block most attacks. 5271 5272 *:san* *:sandbox* 5273 :san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an 5274 option that may have been set from a modeline, e.g. 5275 'foldexpr'. 5276 5277 *sandbox-option* 5278 A few options contain an expression. When this expression is evaluated it may 5279 have to be done in the sandbox to avoid a security risk. But the sandbox is 5280 restrictive, thus this only happens when the option was set from an insecure 5281 location. Insecure in this context are: 5282 - sourcing a .vimrc or .exrc in the current directory 5283 - while executing in the sandbox 5284 - value coming from a modeline 5285 - executing a function that was defined in the sandbox 5286 5287 Note that when in the sandbox and saving an option value and restoring it, the 5288 option will still be marked as it was set in the sandbox. 5289 5290 ============================================================================== 5291 13. Textlock *textlock* 5292 5293 In a few situations it is not allowed to change the text in the buffer, jump 5294 to another window and some other things that might confuse or break what Vim 5295 is currently doing. This mostly applies to things that happen when Vim is 5296 actually doing something else. For example, evaluating the 'balloonexpr' may 5297 happen any moment the mouse cursor is resting at some position. 5298 5299 This is not allowed when the textlock is active: 5300 - changing the buffer text 5301 - jumping to another buffer or window 5302 - editing another file 5303 - closing a window or quitting Vim 5304 - etc. 5305 5306 ============================================================================== 5307 14. Vim script library *vim-script-library* 5308 5309 Vim comes bundled with a Vim script library, that can be used by runtime, 5310 script authors. Currently, it only includes very few functions, but it may 5311 grow over time. 5312 5313 The functions are available as |Vim9-script| as well as using legacy Vim 5314 script (to be used for non Vim 9.0 versions and Neovim). 5315 5316 *dist#vim* *dist#vim9* 5317 The functions make use of the autoloaded prefix "dist#vim" (for legacy Vim 5318 script and Neovim) and "dist#vim9" for Vim9 script. 5319 5320 The following functions are available: 5321 5322 dist#vim#IsSafeExecutable(filetype, executable) ~ 5323 dist#vim9#IsSafeExecutable(filetype:string, executable:string): bool ~ 5324 5325 This function takes a filetype and an executable and checks whether it is safe 5326 to execute the given executable. For security reasons users may not want to 5327 have Vim execute random executables or may have forbidden to do so for 5328 specific filetypes by setting the "<filetype>_exec" variable (|plugin_exec|). 5329 5330 It returns |true| or |false| to indicate whether the plugin should run the 5331 given executable. It takes the following arguments: 5332 5333 argument type ~ 5334 5335 filetype string 5336 executable string 5337 5338 *package-open* 5339 The |:Open| and |:Launch| command are provided by the included plugin 5340 $VIMRUNTIME/plugin/openPlugin.vim 5341 5342 *dist#vim9#Open()* *:Open* *:URLOpen* 5343 *g:Openprg* *gx* 5344 dist#vim9#Open(file: string) ~ 5345 5346 Opens `path` with the system default handler (macOS `open`, Windows 5347 `start`, Linux `xdg-open`, …). If the variable |g:Openprg| exists the 5348 string specified in the variable is used instead. 5349 5350 The |:Open| user command uses file completion for its argument. 5351 5352 The |:URLOpen| user command works the same but does not perform file 5353 completion and therefore does not expand special characters |cmdline-special|. 5354 5355 This function is by default called using the gx mapping. In visual mode 5356 tries to open the visually selected text. 5357 5358 Associated setting variables: 5359 `g:gx_word`: control how gx picks up the text under the cursor. Uses 5360 `g:netrw_gx` as a fallback for backward compatibility. 5361 (default: `<cfile>`) 5362 5363 `g:nogx`: disables the gx mapping. Uses `g:netrw_nogx` as a fallback for 5364 backward compatibility. (default: `unset`) 5365 5366 5367 NOTE: Escaping of the path is automatically applied. 5368 5369 Usage: >vim 5370 :call dist#vim9#Open(<path>) 5371 :Open <path> 5372 :URLOpen <path> 5373 < 5374 *dist#vim9#Launch()* *:Launch* 5375 dist#vim9#Launch(file: string) ~ 5376 5377 Launches <args> with the appropriate system programs. Intended for launching 5378 GUI programs within Vim. 5379 5380 The |:Launch| user command uses shell completion for its first argument. 5381 5382 NOTE: escaping of <args> is left to the user 5383 5384 Examples: > 5385 vim9script 5386 5387 import autoload 'dist/vim9.vim' 5388 # Execute 'makeprg' into another xterm window 5389 vim9.Launch('xterm ' .. expandcmd(&makeprg)) 5390 < 5391 5392 Usage: >vim 5393 :call dist#vim9#Launch(<args>) 5394 :Launch <app> <args>. 5395 < 5396 ============================================================================== 5397 15. Clipboard providers *clipboard-providers* 5398 5399 The clipboard provider feature allows the "+" |quoteplus| and "*" |quotestar| 5400 registers to be overridden by custom Vim script functions. There can be 5401 multiple providers, and Vim chooses which one to use based on 'clipmethod'. 5402 5403 Despite the name, it should be treated separate from the clipboard 5404 functionality. It essentially overrides the existing behaviour of the 5405 clipboard registers. 5406 5407 *clipboard-providers-clipboard* 5408 The clipboard provider feature will respect the "unnamed" and "unnamedplus" 5409 values in the 'clipboard' option. Any other value will be ignored. 5410 5411 *clipboard-providers-no-clipboard* 5412 If the |+clipboard| feature is not enabled, then the "+" and "*" registers 5413 will not be enabled/available unless |v:clipmethod| is set to a provider. If 5414 it is set to a provider, then the clipboard registers will be exposed despite 5415 not having the |+clipboard| feature. 5416 5417 *clipboard-providers-plus* 5418 If on a platform that only has the "*" register, then the "+" register will 5419 only be available when |v:clipmethod| is set to a provider. If you want to 5420 check if the "+" is available for use, it can be checked with: > 5421 if has('unnamedplus') 5422 < 5423 *clipboard-providers-clipmethod* 5424 To integrate the providers with Vim's clipboard functionality, the 5425 'clipmethod' option is used on all platforms. The names of clipboard 5426 providers should be put inside the option, and if Vim chooses it, then it 5427 overrides the "+" and "*" registers. Note that the "+" and "*" will not be 5428 saved in the viminfo at all. 5429 5430 *clipboard-providers-define* 5431 To define a clipboard provider, the |v:clipproviders| vim variable is used. It 5432 is a |dict| where each key is the clipboard provider name, and the value is 5433 another |dict| declaring the "available", "copy", and "paste" callbacks: >vim 5434 let v:clipproviders["myprovider"] = { 5435 \ "available": function("Available"), 5436 \ "paste": { 5437 \ "+": function("Paste"), 5438 \ "*": function("Paste") 5439 \ }, 5440 \ "copy": { 5441 \ "+": function("Copy"), 5442 \ "*": function("Copy") 5443 \ } 5444 \ } 5445 set clipmethod^=myprovider 5446 < 5447 Each callback can either be a name of a function in a string, a |Funcref|, or 5448 a |lambda| expression. 5449 5450 With the exception of the "available" callback if a callback is not provided, 5451 Vim will not invoke anything, and this is not an error. 5452 5453 If the "paste" or "copy" callbacks are triggered recursively, then they will 5454 not be called. 5455 5456 *clipboard-providers-textlock* 5457 In both the "paste" and "copy" callbacks, it is not allowed to change the 5458 buffer text, see |textlock|. 5459 5460 *clipboard-providers-available* 5461 The "available" callback is optional, does not take any arguments and should 5462 return a |boolean| or non-zero number, which tells Vim if it is available 5463 for use. If it is not, then Vim skips over it and tries the next 'clipmethod' 5464 value. If the "available" callback is not provided, Vim assumes the provider 5465 is always available for use (true). 5466 5467 *clipboard-providers-paste* 5468 The "paste" callback takes the following arguments in the following order: 5469 1. Name of the register being accessed, either "+" or "*". 5470 5471 It should return a |list| or |tuple| containing the following elements in 5472 order: 5473 1. Register type (and optional width) conforming to |setreg()|. If it 5474 is an empty string, then the type is automatically chosen. 5475 2. A |list| of strings to return to Vim, each representing a line. 5476 5477 If an invalid value is returned, then this is not an error. Instead the 5478 register will be left unchanged (not cleared). 5479 5480 *clipboard-providers-copy* 5481 The "copy" callback returns nothing and takes the following arguments in the 5482 following order: 5483 1. Name of the register being accessed, either "+" or "*". 5484 2. Register type conforming to |getregtype()| 5485 3. List of strings to use, each representing a line. 5486 5487 A callback that uses |system()| or |systemlist()| should prepend |:silent|. 5488 Otherwise terminal output such as focus events appears on the screen while 5489 the command runs. 5490 5491 Below is a sample script that makes use of the clipboard provider feature: >vim 5492 func Available() 5493 return v:true 5494 endfunc 5495 5496 func Copy(reg, type, str) 5497 echom "Register: " .. a:reg 5498 echom "Register type: " .. a:type 5499 echom "Contents: " .. string(a:str) 5500 endfunc 5501 5502 func Paste(reg) 5503 return ("b40", ["this", "is", "the", a:reg, "register!"]) 5504 endfunc 5505 5506 let v:clipproviders["test"] = { 5507 \ "available": function("Available"), 5508 \ "copy": { 5509 \ "+": function("Copy"), 5510 \ "*": function("Copy") 5511 \ }, 5512 \ "paste": { 5513 \ "+": function("Paste"), 5514 \ "*": function("Paste") 5515 \ } 5516 \ } 5517 set clipmethod^=test 5518 < 5519 *clipboard-providers-wsl* 5520 For Windows WSL, try this script: 5521 >vim9 5522 vim9script 5523 5524 def Copy(_: string, _: string, lines: list<string>) 5525 silent system('wl-copy', lines) 5526 enddef 5527 def Paste(_: string): tuple<string, list<string>> 5528 silent return ('', systemlist('wl-paste --no-newline') 5529 ->map((_, v) => v->trim("\r", 2))) 5530 enddef 5531 5532 v:clipproviders["wslclip"] = { 5533 available: () => executable('wl-copy') && executable('wl-paste'), 5534 copy: { "*": Copy, "+": Copy }, 5535 paste: { "*": Paste, "+": Paste } 5536 } 5537 set clipmethod^=wslclip 5538 < 5539 vim:tw=78:ts=8:noet:ft=help:norl: