usr_41.txt (70564B)
1 *usr_41.txt* For Vim version 9.2. Last change: 2026 Sep 30 2 3 4 VIM USER MANUAL by Bram Moolenaar 5 6 7 Write a Vim script 8 9 10 The Vim script language is used for the startup vimrc file, syntax files, and 11 many other things. This chapter explains the items that can be used in a Vim 12 script. There are a lot of them, therefore this is a long chapter. 13 14 |41.1| Introduction 15 |41.2| Variables 16 |41.3| Expressions 17 |41.4| Conditionals 18 |41.5| Executing an expression 19 |41.6| Using functions 20 |41.7| Defining a function 21 |41.8| Lists and Dictionaries 22 |41.9| White space 23 |41.10| Line continuation 24 |41.11| Comments 25 |41.12| Fileformat 26 27 Next chapter: |usr_42.txt| Add new menus 28 Previous chapter: |usr_40.txt| Make new commands 29 Table of contents: |usr_toc.txt| 30 31 ============================================================================== 32 *41.1* Introduction *vim-script-intro* *script* 33 34 Let's start with some nomenclature. A Vim script is any file that Vim can 35 interpret and execute. This includes files written in Vim's scripting 36 language like for example .vim files or configuration files like .vimrc and 37 .gvimrc. These scripts may define functions, commands and settings that Vim 38 uses to customize and extend its behavior. 39 40 *vim-script-notation* 41 The correct notation is "Vim script" (or "Vim9 script" when referring to the 42 new Vim9 language |Vim9-script|), so we will use "Vim script" to refer to the 43 Vim scripting language throughout this documentation. This shorthand helps to 44 streamline explanations and discussions about scripting with Vim. 45 46 A Vim plugin is a collection of one or more Vim scripts, along with additional 47 files like help documentation, configuration files, and other resources, 48 designed to add specific features or functionalities to Vim. A plugin can 49 provide new commands, enhance existing capabilities, and integrate external 50 tools or services into the Vim environment. 51 52 Your first experience with Vim scripts is the vimrc file. Vim reads it when 53 it starts up and executes the commands. You can set options to the values you 54 prefer, define mappings, select plugins and much more. You can use any colon 55 command in it (commands that start with a ":"; these are sometimes referred to 56 as Ex commands or command-line commands). 57 58 Syntax files are also Vim scripts. As are files that set options for a 59 specific file type. A complicated macro can be defined by a separate Vim 60 script file. You can think of other uses yourself. 61 62 Vim script comes in two flavors: legacy and |Vim9|. Since this help file is 63 for new users, we'll teach you the newer and more convenient |Vim9| syntax. 64 While legacy script is particularly for Vim, |Vim9| script looks more like 65 other languages, such as JavaScript and TypeScript. 66 67 To try out Vim script the best way is to edit a script file and source it. 68 Basically: > 69 :edit test.vim 70 [insert the script lines you want] 71 :w 72 :source % 73 74 Let's start with a simple example: > 75 76 vim9script 77 var i = 1 78 while i < 5 79 echo "count is" i 80 i += 1 81 endwhile 82 < 83 The output of the example code is: 84 85 count is 1 ~ 86 count is 2 ~ 87 count is 3 ~ 88 count is 4 ~ 89 90 In the first line the `vim9script` command makes clear this is a new, |Vim9| 91 script file. That matters for how the rest of the file is used. It is 92 recommended to put it in the very first line, before any comments. 93 *vim9-declarations* 94 The `var i = 1` command declares the "i" variable and initializes it. The 95 generic form is: > 96 97 var {name} = {expression} 98 99 In this case the variable name is "i" and the expression is a simple value, 100 the number one. 101 102 The `while` command starts a loop. The generic form is: > 103 104 while {condition} 105 {statements} 106 endwhile 107 108 The statements until the matching `endwhile` are executed for as long as the 109 condition is true. The condition used here is the expression "i < 5". This 110 is true when the variable i is smaller than five. 111 Note: 112 If you happen to write a while loop that keeps on running, you can 113 interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows). 114 115 The `echo` command prints its arguments. In this case the string "count is" 116 and the value of the variable i. Since i is one, this will print: 117 118 count is 1 ~ 119 120 Then there is the `i += 1` command. This does the same thing as "i = i + 1", 121 it adds one to the variable i and assigns the new value to the same variable. 122 123 The example was given to explain the commands, but would you really want to 124 make such a loop, it can be written much more compact: > 125 126 for i in range(1, 4) 127 echo $"count is {i}" 128 endfor 129 130 We won't explain how `for`, `range()` and `$"string"` work until later. 131 Follow the links if you are impatient. 132 133 134 TRYING OUT EXAMPLES 135 136 You can easily try out most examples in these help files without saving the 137 commands to a file. For example, to try out the "for" loop above do this: 138 1. position the cursor on the "for" 139 2. start Visual mode with "v" 140 3. move down to the "endfor" 141 4. press colon, then "so" and Enter 142 143 After pressing colon you will see ":'<,'>", which is the range of the Visually 144 selected text. 145 146 For some commands it matters they are executed as in |Vim9| script. But typed 147 commands normally use legacy script syntax, such as the example below that 148 causes the E1004 error. For that use this fourth step: 149 4. press colon, then "vim9 so" and Enter 150 151 "vim9" is short for `vim9cmd`, which is a command modifier to execute the 152 following command in |Vim9| syntax. 153 154 Note that this won't work for examples that require a script context. 155 156 157 FOUR KINDS OF NUMBERS 158 159 Numbers can be decimal, hexadecimal, octal and binary. 160 161 A hexadecimal number starts with "0x" or "0X". For example "0x1f" is decimal 162 31 and "0x1234" is decimal 4660. 163 164 An octal number starts with "0o", "0O". "0o17" is decimal 15. 165 166 A binary number starts with "0b" or "0B". For example "0b101" is decimal 5. 167 168 A decimal number is just digits. Careful: In legacy script don't put a zero 169 before a decimal number, it will be interpreted as an octal number! That's 170 one reason to use |Vim9| script. 171 172 The `echo` command evaluates its argument and when it is a number always 173 prints the decimal form. Example: > 174 175 echo 0x7f 0o36 176 < 127 30 ~ 177 178 A number is made negative with a minus sign. This also works for hexadecimal, 179 octal and binary numbers: > 180 181 echo -0x7f 182 < -127 ~ 183 184 A minus sign is also used for subtraction. This can sometimes lead to 185 confusion. If we put a minus sign before both numbers we get an error: > 186 187 echo -0x7f -0o36 188 < E1004: White space required before and after '-' at "-0o36" ~ 189 190 Note: if you are not using a |Vim9| script to try out these commands but type 191 them directly, they will be executed as legacy script. Then the echo command 192 sees the second minus sign as subtraction. To get the error, prefix the 193 command with `vim9cmd`: > 194 195 vim9cmd echo -0x7f -0o36 196 < E1004: White space required before and after '-' at "-0o36" ~ 197 198 White space in an expression is often required to make sure it is easy to read 199 and avoid errors. Such as thinking that the "-0o36" above makes the number 200 negative, while it is actually seen as a subtraction. 201 202 To actually have the minus sign be used for negation, you can put the second 203 expression in parentheses: > 204 205 echo -0x7f (-0o36) 206 < -127 -30 ~ 207 208 ============================================================================== 209 *41.2* Variables 210 211 A variable name consists of ASCII letters, digits and the underscore. It 212 cannot start with a digit. Valid variable names are: 213 214 counter 215 _aap3 216 very_long_variable_name_with_underscores 217 CamelCaseName 218 LENGTH 219 220 Invalid names are "foo.bar" and "6var". 221 222 Some variables are global. To see a list of currently defined global 223 variables type this command: > 224 225 :let 226 227 You can use global variables everywhere. However, it is too easy to use the 228 same name in two unrelated scripts. Therefore variables declared in a script 229 are local to that script. For example, if you have this in "script1.vim": > 230 231 vim9script 232 var counter = 5 233 echo counter 234 < 5 ~ 235 236 And you try to use the variable in "script2.vim": > 237 238 vim9script 239 echo counter 240 < E121: Undefined variable: counter ~ 241 242 Using a script-local variable means you can be sure that it is only changed in 243 that script and not elsewhere. 244 245 If you do want to share variables between scripts, use the "g:" prefix and 246 assign the value directly, do not use `var`. And use a specific name to avoid 247 mistakes. Thus in "script1.vim": > 248 249 vim9script 250 g:mash_counter = 5 251 echo g:mash_counter 252 < 5 ~ 253 254 And then in "script2.vim": > 255 256 vim9script 257 echo g:mash_counter 258 < 5 ~ 259 260 Global variables can also be accessed on the command line, E.g. typing this: > 261 echo g:mash_counter 262 That will not work for a script-local variable. 263 264 More about script-local variables here: |script-variable|. 265 266 There are more kinds of variables, see |internal-variables|. The most often 267 used ones are: 268 269 b:name variable local to a buffer 270 w:name variable local to a window 271 g:name global variable (also in a function) 272 v:name variable predefined by Vim 273 274 275 DELETING VARIABLES 276 277 Variables take up memory and show up in the output of the `let` command. To 278 delete a global variable use the `unlet` command. Example: > 279 280 unlet g:counter 281 282 This deletes the global variable "g:counter" to free up the memory it uses. 283 If you are not sure if the variable exists, and don't want an error message 284 when it doesn't, append !: > 285 286 unlet! g:counter 287 288 You cannot `unlet` script-local variables in |Vim9| script, only in legacy 289 script. 290 291 When a script has been processed to the end, the local variables declared 292 there will not be deleted. Functions defined in the script can use them. 293 Example: 294 > 295 vim9script 296 var counter = 0 297 def g:GetCount(): number 298 counter += 1 299 return counter 300 enddef 301 302 Every time you call the function it will return the next count: > 303 :echo g:GetCount() 304 < 1 ~ 305 > 306 :echo g:GetCount() 307 < 2 ~ 308 309 If you are worried a script-local variable is consuming too much memory, set 310 it to an empty or null value after you no longer need it. Example: > 311 var lines = readfile(...) 312 ... 313 lines = [] 314 315 Note: below we'll leave out the `vim9script` line from examples, so we can 316 concentrate on the relevant commands, but you'll still need to put it at the 317 top of your script file. 318 319 320 STRING VARIABLES AND CONSTANTS 321 322 So far only numbers were used for the variable value. Strings can be used as 323 well. Numbers and strings are the basic types of variables that Vim supports. 324 Example: > 325 326 var name = "Peter" 327 echo name 328 < Peter ~ 329 330 Every variable has a type. Very often, as in this example, the type is 331 defined by assigning a value. This is called type inference. If you do not 332 want to give the variable a value yet, you need to specify the type: > 333 334 var name: string 335 var age: number 336 if male 337 name = "Peter" 338 age = 42 339 else 340 name = "Elisa" 341 age = 45 342 endif 343 344 If you make a mistake and try to assign the wrong type of value you'll get an 345 error: > 346 347 age = "Peter" 348 < E1012: Type mismatch; expected number but got string ~ 349 350 More about types in |41.8|. 351 352 To assign a string value to a variable, you can use a string constant. There 353 are two types of these. First the string in double quotes, as we used 354 already. If you want to include a double quote inside the string, put a 355 backslash in front of it: > 356 357 var name = "he is \"Peter\"" 358 echo name 359 < he is "Peter" ~ 360 361 To avoid the need for backslashes, you can use a string in single quotes: > 362 363 var name = 'he is "Peter"' 364 echo name 365 < he is "Peter" ~ 366 367 Inside a single-quote string all the characters are as they are. Only the 368 single quote itself is special: you need to use two to get one. A backslash 369 is taken literally, thus you can't use it to change the meaning of the 370 character after it: > 371 372 var name = 'P\e''ter''' 373 echo name 374 < P\e'ter' ~ 375 376 In double-quote strings it is possible to use special characters. Here are a 377 few useful ones: 378 379 \t <Tab> 380 \n <NL>, line break 381 \r <CR>, <Enter> 382 \e <Esc> 383 \b <BS>, backspace 384 \" " 385 \\ \, backslash 386 \<Esc> <Esc> 387 \<C-W> CTRL-W 388 389 The last two are just examples. The "\<name>" form can be used to include 390 the special key "name". 391 392 See |expr-quote| for the full list of special items in a string. 393 394 ============================================================================== 395 *41.3* Expressions 396 397 Vim has a fairly standard way to handle expressions. You can read the 398 definition here: |expression-syntax|. Here we will show the most common 399 items. 400 401 The numbers, strings and variables mentioned above are expressions by 402 themselves. Thus everywhere an expression is expected, you can use a number, 403 string or variable. Other basic items in an expression are: 404 405 $NAME environment variable 406 &name option value 407 @r register contents 408 409 Examples: > 410 411 echo "The value of 'tabstop' is" &ts 412 echo "Your home directory is" $HOME 413 if @a == 'text' 414 415 The &name form can also be used to set an option value, do something and 416 restore the old value. Example: > 417 418 var save_ic = &ic 419 set noic 420 s/The Start/The Beginning/ 421 &ic = save_ic 422 423 This makes sure the "The Start" pattern is used with the 'ignorecase' option 424 off. Still, it keeps the value that the user had set. (Another way to do 425 this would be to add "\C" to the pattern, see |/\C|.) 426 427 428 MATHEMATICS 429 430 It becomes more interesting if we combine these basic items. Let's start with 431 mathematics on numbers: 432 433 a + b add 434 a - b subtract 435 a * b multiply 436 a / b divide 437 a % b modulo 438 439 The usual precedence is used. Example: > 440 441 echo 10 + 5 * 2 442 < 20 ~ 443 444 Grouping is done with parentheses. No surprises here. Example: > 445 446 echo (10 + 5) * 2 447 < 30 ~ 448 449 450 OTHERS 451 452 Strings can be concatenated with ".." (see |expr6|). Example: > 453 454 echo "Name: " .. name 455 Name: Peter 456 457 When the "echo" command gets multiple arguments, it separates them with a 458 space. In the example the argument is a single expression, thus no space is 459 inserted. 460 461 If you don't like the concatenation you can use the $"string" form, which 462 accepts an expression in curly braces: > 463 echo $"Name: {name}" 464 465 See |interpolated-string| for more information. 466 467 Borrowed from the C language is the conditional expression: > 468 469 a ? b : c 470 471 If "a" evaluates to true "b" is used, otherwise "c" is used. Example: > 472 473 var nr = 4 474 echo nr > 5 ? "nr is big" : "nr is small" 475 < nr is small ~ 476 477 The three parts of the constructs are always evaluated first, thus you could 478 see it works as: > 479 480 (a) ? (b) : (c) 481 482 There is also the falsy operator: > 483 echo name ?? "No name given" 484 See |??|. 485 486 ============================================================================== 487 *41.4* Conditionals 488 489 The `if` commands executes the following statements, until the matching 490 `endif`, only when a condition is met. The generic form is: 491 492 if {condition} 493 {statements} 494 endif 495 496 Only when the expression {condition} evaluates to true or one will the 497 {statements} be executed. If they are not executed they must still be valid 498 commands. If they contain garbage, Vim won't be able to find the matching 499 `endif`. 500 501 You can also use `else`. The generic form for this is: 502 503 if {condition} 504 {statements} 505 else 506 {statements} 507 endif 508 509 The second {statements} block is only executed if the first one isn't. 510 511 Finally, there is `elseif` 512 513 if {condition} 514 {statements} 515 elseif {condition} 516 {statements} 517 endif 518 519 This works just like using `else` and then `if`, but without the need for an 520 extra `endif`. 521 522 A useful example for your vimrc file is checking the 'term' option and doing 523 something depending upon its value: > 524 525 if &term == "xterm" 526 # Do stuff for xterm 527 elseif &term == "vt100" 528 # Do stuff for a vt100 terminal 529 else 530 # Do something for other terminals 531 endif 532 533 This uses "#" to start a comment, more about that later. 534 535 536 LOGIC OPERATIONS 537 538 We already used some of them in the examples. These are the most often used 539 ones: 540 541 a == b equal to 542 a != b not equal to 543 a > b greater than 544 a >= b greater than or equal to 545 a < b less than 546 a <= b less than or equal to 547 548 The result is true if the condition is met and false otherwise. An example: > 549 550 if v:version >= 800 551 echo "congratulations" 552 else 553 echo "you are using an old version, upgrade!" 554 endif 555 556 Here "v:version" is a variable defined by Vim, which has the value of the Vim 557 version. 800 is for version 8.0, version 8.1 has the value 801. This is 558 useful to write a script that works with multiple versions of Vim. 559 See |v:version|. You can also check for a specific feature with `has()` or a 560 specific patch, see |has-patch|. 561 562 The logic operators work both for numbers and strings. When comparing two 563 strings, the mathematical difference is used. This compares byte values, 564 which may not be right for some languages. 565 566 If you try to compare a string with a number you will get an error. 567 568 For strings there are two more useful items: 569 570 str =~ pat matches with 571 str !~ pat does not match with 572 573 The left item "str" is used as a string. The right item "pat" is used as a 574 pattern, like what's used for searching. Example: > 575 576 if str =~ " " 577 echo "str contains a space" 578 endif 579 if str !~ '\.$' 580 echo "str does not end in a full stop" 581 endif 582 583 Notice the use of a single-quote string for the pattern. This is useful, 584 because patterns tend to contain many backslashes and backslashes need to be 585 doubled in a double-quote string. 586 587 The match is not anchored, if you want to match the whole string start with 588 "^" and end with "$". 589 590 The 'ignorecase' option is not used when comparing strings. When you do want 591 to ignore case append "?". Thus "==?" compares two strings to be equal while 592 ignoring case. For the full table see |expr-==|. 593 594 595 MORE LOOPING 596 597 The `while` command was already mentioned. Two more statements can be used in 598 between the `while` and the `endwhile`: 599 600 continue Jump back to the start of the while loop; the 601 loop continues. 602 break Jump forward to the `endwhile`; the loop is 603 discontinued. 604 605 Example: > 606 607 var counter = 1 608 while counter < 40 609 if skip_number(counter) 610 continue 611 endif 612 if last_number(counter) 613 break 614 endif 615 sleep 50m 616 ++counter 617 endwhile 618 619 The `sleep` command makes Vim take a nap. The "50m" specifies fifty 620 milliseconds. Another example is `sleep 4`, which sleeps for four seconds. 621 622 `continue` and `break` can also be used in between `for` and `endfor`. 623 Even more looping can be done with the `for` command, see below in |41.8|. 624 625 ============================================================================== 626 *41.5* Executing an expression 627 628 So far the commands in the script were executed by Vim directly. The 629 `execute` command allows executing the result of an expression. This is a 630 very powerful way to build commands and execute them. 631 632 An example is to jump to a tag, which is contained in a variable: > 633 634 execute "tag " .. tag_name 635 636 The ".." is used to concatenate the string "tag " with the value of variable 637 "tag_name". Suppose "tag_name" has the value "get_cmd", then the command that 638 will be executed is: > 639 640 tag get_cmd 641 642 The `execute` command can only execute Ex commands. The `normal` command 643 executes Normal mode commands. However, its argument is not an expression but 644 the literal command characters. Example: > 645 646 normal gg=G 647 648 This jumps to the first line with "gg" and formats all lines with the "=" 649 operator and the "G" movement. 650 651 To make `normal` work with an expression, combine `execute` with it. 652 Example: > 653 654 execute "normal " .. count .. "j" 655 656 This will move the cursor "count" lines down. 657 658 Make sure that the argument for `normal` is a complete command. Otherwise 659 Vim will run into the end of the argument and silently abort the command. For 660 example, if you start the delete operator, you must give the movement command 661 also. This works: > 662 663 normal d$ 664 665 This does nothing: > 666 667 normal d 668 669 If you start Insert mode and do not end it with Esc, it will end anyway. This 670 works to insert "new text": > 671 672 execute "normal inew text" 673 674 If you want to do something after inserting text you do need to end Insert 675 mode: > 676 677 execute "normal inew text\<Esc>b" 678 679 This inserts "new text" and puts the cursor on the first letter of "text". 680 Notice the use of the special key "\<Esc>". This avoids having to enter a 681 real <Esc> character in your script. That is where `execute` with a 682 double-quote string comes in handy. 683 684 If you don't want to execute a string as a command but evaluate it to get the 685 result of the expression, you can use the eval() function: > 686 687 var optname = "path" 688 var optvalue = eval('&' .. optname) 689 690 A "&" character is prepended to "path", thus the argument to eval() is 691 "&path". The result will then be the value of the 'path' option. 692 693 ============================================================================== 694 *41.6* Using functions 695 696 Vim defines many functions and provides a large amount of functionality that 697 way. A few examples will be given in this section. You can find the whole 698 list below: |function-list|. 699 700 A function is called with the parameters in between parentheses, separated by 701 commas. Example: > 702 703 search("Date: ", "W") 704 705 This calls the search() function, with arguments "Date: " and "W". The 706 search() function uses its first argument as a search pattern and the second 707 one as flags. The "W" flag means the search doesn't wrap around the end of 708 the file. 709 710 Using the `call` command is optional in |Vim9| script. It is required in 711 legacy script and on the command line: > 712 713 call search("Date: ", "W") 714 715 A function can be called in an expression. Example: > 716 717 var line = getline(".") 718 var repl = substitute(line, '\a', "*", "g") 719 setline(".", repl) 720 721 The getline() function obtains a line from the current buffer. Its argument 722 is a specification of the line number. In this case "." is used, which means 723 the line where the cursor is. 724 725 The substitute() function does something similar to the `:substitute` command. 726 The first argument "line" is the string on which to perform the substitution. 727 The second argument '\a' is the pattern, the third "*" is the replacement 728 string. Finally, the last argument "g" is the flags. 729 730 The setline() function sets the line, specified by the first argument, to a 731 new string, the second argument. In this example the line under the cursor is 732 replaced with the result of the substitute(). Thus the effect of the three 733 statements is equal to: > 734 735 :substitute/\a/*/g 736 737 Using the functions becomes interesting when you do more work before and 738 after the substitute() call. 739 740 741 FUNCTIONS *function-list* 742 743 There are many functions. We will mention them here, grouped by what they are 744 used for. You can find an alphabetical list here: |builtin-function-list|. 745 Use CTRL-] on the function name to jump to detailed help on it. 746 747 String manipulation: *string-functions* 748 nr2char() get a character by its number value 749 list2str() get a character string from a list of numbers 750 char2nr() get number value of a character 751 str2list() get list of numbers from a string 752 str2nr() convert a string to a Number 753 str2float() convert a string to a Float 754 printf() format a string according to "%" items 755 escape() escape characters in a string with a '\' 756 shellescape() escape a string for use with a shell command 757 fnameescape() escape a file name for use with a Vim command 758 tr() translate characters from one set to another 759 strtrans() translate a string to make it printable 760 keytrans() translate internal keycodes to a form that 761 can be used by |:map| 762 tolower() turn a string to lowercase 763 toupper() turn a string to uppercase 764 charclass() class of a character 765 match() position where a pattern matches in a string 766 matchbufline() all the matches of a pattern in a buffer 767 matchend() position where a pattern match ends in a 768 string 769 matchfuzzy() fuzzy matches a string in a list of strings 770 matchfuzzypos() fuzzy matches a string in a list of strings 771 matchstr() match of a pattern in a string 772 matchstrlist() all the matches of a pattern in a List of 773 strings 774 matchstrpos() match and positions of a pattern in a string 775 matchlist() like matchstr() and also return submatches 776 stridx() first index of a short string in a long string 777 strridx() last index of a short string in a long string 778 strlen() length of a string in bytes 779 strcharlen() length of a string in characters 780 strchars() number of characters in a string 781 strutf16len() number of UTF-16 code units in a string 782 strwidth() size of string when displayed 783 strdisplaywidth() size of string when displayed, deals with tabs 784 setcellwidths() set character cell width overrides 785 getcellwidths() get character cell width overrides 786 getcellpixels() get character cell pixel size 787 reverse() reverse the order of characters in a string 788 substitute() substitute a pattern match with a string 789 submatch() get a specific match in ":s" and substitute() 790 strpart() get part of a string using byte index 791 strcharpart() get part of a string using char index 792 slice() take a slice of a string, using char index in 793 Vim9 script 794 strgetchar() get character from a string using char index 795 expand() expand special keywords 796 expandcmd() expand a command like done for `:edit` 797 iconv() convert text from one encoding to another 798 byteidx() byte index of a character in a string 799 byteidxcomp() like byteidx() but count composing characters 800 charidx() character index of a byte in a string 801 utf16idx() UTF-16 index of a byte in a string 802 repeat() repeat a string multiple times 803 eval() evaluate a string expression 804 execute() execute an Ex command and get the output 805 win_execute() like execute() but in a specified window 806 trim() trim characters from a string 807 bindtextdomain() set message lookup translation base path 808 gettext() lookup message translation 809 ngettext() lookup single/plural message translation 810 str2blob() convert a list of strings into a blob 811 blob2str() convert a blob into a list of strings 812 items() get List of String index-character pairs 813 uri_encode() URI-encode a string 814 uri_decode() URI-decode a string 815 816 List manipulation: *list-functions* 817 get() get an item without error for wrong index 818 len() number of items in a List 819 empty() check if List is empty 820 insert() insert an item somewhere in a List 821 add() append an item to a List 822 extend() append a List to a List 823 extendnew() make a new List and append items 824 remove() remove one or more items from a List 825 copy() make a shallow copy of a List 826 deepcopy() make a full copy of a List 827 filter() remove selected items from a List 828 map() change each List item 829 mapnew() make a new List with changed items 830 foreach() apply function to List items 831 reduce() reduce a List to a value 832 slice() take a slice of a List 833 sort() sort a List 834 reverse() reverse the order of items in a List 835 uniq() remove copies of repeated adjacent items 836 split() split a String into a List 837 join() join List items into a String 838 range() return a List with a sequence of numbers 839 string() String representation of a List 840 call() call a function with List as arguments 841 index() index of a value in a List 842 indexof() index in a List where an expression is true 843 max() maximum value in a List 844 min() minimum value in a List 845 count() count number of times a value appears in a 846 List 847 repeat() repeat a List multiple times 848 flatten() flatten a List 849 flattennew() flatten a copy of a List 850 items() get List of List index-value pairs 851 852 Tuple manipulation: *tuple-functions* 853 copy() make a shallow copy of a Tuple 854 count() count number of times a value appears in a 855 Tuple 856 deepcopy() make a full copy of a Tuple 857 empty() check if Tuple is empty 858 foreach() apply function to Tuple items 859 get() get an item without error for wrong index 860 index() index of a value in a Tuple 861 indexof() index in a Tuple where an expression is true 862 items() get List of Tuple index-value pairs 863 join() join Tuple items into a String 864 len() number of items in a Tuple 865 list2tuple() convert a list of items into a Tuple 866 max() maximum value in a Tuple 867 min() minimum value in a Tuple 868 reduce() reduce a Tuple to a value 869 repeat() repeat a Tuple multiple times 870 reverse() reverse the order of items in a Tuple 871 slice() take a slice of a Tuple 872 string() string representation of a Tuple 873 tuple2list() convert a Tuple into a List 874 875 Dictionary manipulation: *dict-functions* 876 get() get an entry without an error for a wrong key 877 len() number of entries in a Dictionary 878 has_key() check whether a key appears in a Dictionary 879 empty() check if Dictionary is empty 880 remove() remove an entry from a Dictionary 881 extend() add entries from one Dictionary to another 882 extendnew() make a new Dictionary and append items 883 filter() remove selected entries from a Dictionary 884 map() change each Dictionary entry 885 mapnew() make a new Dictionary with changed items 886 foreach() apply function to Dictionary items 887 keys() get List of Dictionary keys 888 values() get List of Dictionary values 889 items() get List of Dictionary key-value pairs 890 copy() make a shallow copy of a Dictionary 891 deepcopy() make a full copy of a Dictionary 892 string() String representation of a Dictionary 893 max() maximum value in a Dictionary 894 min() minimum value in a Dictionary 895 count() count number of times a value appears 896 897 Floating point computation: *float-functions* 898 float2nr() convert Float to Number 899 abs() absolute value (also works for Number) 900 round() round off 901 ceil() round up 902 floor() round down 903 trunc() remove value after decimal point 904 fmod() remainder of division 905 exp() exponential 906 log() natural logarithm (logarithm to base e) 907 log10() logarithm to base 10 908 pow() value of x to the exponent y 909 sqrt() square root 910 sin() sine 911 cos() cosine 912 tan() tangent 913 asin() arc sine 914 acos() arc cosine 915 atan() arc tangent 916 atan2() arc tangent 917 sinh() hyperbolic sine 918 cosh() hyperbolic cosine 919 tanh() hyperbolic tangent 920 isinf() check for infinity 921 isnan() check for not a number 922 923 Blob manipulation: *blob-functions* 924 get() get a byte without error for wrong index 925 len() number of bytes in a Blob 926 empty() check if Blob is empty 927 insert() insert a byte somewhere in a Blob 928 add() append a byte to a Blob 929 extend() append a Blob to a Blob 930 extendnew() make a new Blob and append bytes 931 remove() remove one or more bytes from a Blob 932 copy() make a copy of a Blob 933 filter() remove selected bytes from a Blob 934 map() change each byte of a Blob 935 mapnew() make a new Blob with changed bytes 936 foreach() apply function to Blob bytes 937 reduce() reduce a Blob to a value 938 slice() take a slice of a Blob 939 blob2list() get a list of numbers from a Blob 940 list2blob() get a Blob from a list of numbers 941 blob2str() get a list of strings from a Blob 942 str2blob() get a Blob from a list of strings 943 base64_encode() encode a Blob into a base64 String 944 base64_decode() decode a base64 String into a Blob 945 reverse() reverse the order of bytes in a Blob 946 string() String representation of a Blob 947 index() index of a value in a Blob 948 indexof() index in a Blob where an expression is true 949 repeat() repeat a Blob multiple times 950 items() get List of Blob index-value pairs 951 952 Other computation: *bitwise-function* 953 and() bitwise AND 954 invert() bitwise invert 955 or() bitwise OR 956 xor() bitwise XOR 957 sha256() SHA-256 hash 958 rand() get a pseudo-random number 959 srand() initialize seed used by rand() 960 961 Variables: *var-functions* 962 instanceof() check if a variable is an instance of a given 963 class 964 type() type of a variable as a number 965 typename() type of a variable as text 966 islocked() check if a variable is locked 967 funcref() get a Funcref for a function reference 968 function() get a Funcref for a function name 969 getbufvar() get a variable value from a specific buffer 970 setbufvar() set a variable in a specific buffer 971 getwinvar() get a variable from specific window 972 gettabvar() get a variable from specific tab page 973 gettabwinvar() get a variable from specific window & tab page 974 setwinvar() set a variable in a specific window 975 settabvar() set a variable in a specific tab page 976 settabwinvar() set a variable in a specific window & tab page 977 garbagecollect() possibly free memory 978 979 Cursor and mark position: *cursor-functions* *mark-functions* 980 col() column number of the cursor or a mark 981 virtcol() screen column of the cursor or a mark 982 line() line number of the cursor or mark 983 wincol() window column number of the cursor 984 winline() window line number of the cursor 985 cursor() position the cursor at a line/column 986 screencol() get screen column of the cursor 987 screenrow() get screen row of the cursor 988 screenpos() screen row and col of a text character 989 virtcol2col() byte index of a text character on screen 990 getcurpos() get position of the cursor 991 getpos() get position of cursor, mark, etc. 992 setpos() set position of cursor, mark, etc. 993 getmarklist() list of global/local marks 994 byte2line() get line number at a specific byte count 995 line2byte() byte count at a specific line 996 diff_filler() get the number of filler lines above a line 997 screenattr() get attribute at a screen line/row 998 screenchar() get character code at a screen line/row 999 screenchars() get character codes at a screen line/row 1000 screenstring() get string of characters at a screen line/row 1001 charcol() character number of the cursor or a mark 1002 getcharpos() get character position of cursor, mark, etc. 1003 setcharpos() set character position of cursor, mark, etc. 1004 getcursorcharpos() get character position of the cursor 1005 setcursorcharpos() set character position of the cursor 1006 1007 Working with text in the current buffer: *text-functions* 1008 getline() get a line or list of lines from the buffer 1009 getregion() get a region of text from the buffer 1010 getregionpos() get a list of positions for a region 1011 setline() replace a line in the buffer 1012 append() append line or list of lines in the buffer 1013 indent() indent of a specific line 1014 cindent() indent according to C indenting 1015 lispindent() indent according to Lisp indenting 1016 nextnonblank() find next non-blank line 1017 prevnonblank() find previous non-blank line 1018 search() find a match for a pattern 1019 searchpos() find a match for a pattern 1020 searchcount() get number of matches before/after the cursor 1021 searchpair() find the other end of a start/skip/end 1022 searchpairpos() find the other end of a start/skip/end 1023 searchdecl() search for the declaration of a name 1024 getcharsearch() return character search information 1025 setcharsearch() set character search information 1026 1027 Working with text in another buffer: 1028 getbufline() get a list of lines from the specified buffer 1029 getbufoneline() get a one line from the specified buffer 1030 setbufline() replace a line in the specified buffer 1031 appendbufline() append a list of lines in the specified buffer 1032 deletebufline() delete lines from a specified buffer 1033 1034 *system-functions* *file-functions* 1035 System functions and manipulation of files: 1036 glob() expand wildcards 1037 globpath() expand wildcards in a number of directories 1038 glob2regpat() convert a glob pattern into a search pattern 1039 findfile() find a file in a list of directories 1040 finddir() find a directory in a list of directories 1041 resolve() find out where a shortcut points to 1042 fnamemodify() modify a file name 1043 pathshorten() shorten directory names in a path 1044 simplify() simplify a path without changing its meaning 1045 executable() check if an executable program exists 1046 exepath() full path of an executable program 1047 filereadable() check if a file can be read 1048 filewritable() check if a file can be written to 1049 getfperm() get the permissions of a file 1050 setfperm() set the permissions of a file 1051 getftype() get the kind of a file 1052 isabsolutepath() check if a path is absolute 1053 isdirectory() check if a directory exists 1054 getfsize() get the size of a file 1055 getcwd() get the current working directory 1056 haslocaldir() check if current window used |:lcd| or |:tcd| 1057 tempname() get the name of a temporary file 1058 mkdir() create a new directory 1059 chdir() change current working directory 1060 delete() delete a file 1061 rename() rename a file 1062 system() get the result of a shell command as a string 1063 systemlist() get the result of a shell command as a list 1064 environ() get all environment variables 1065 getenv() get one environment variable 1066 setenv() set an environment variable 1067 hostname() name of the system 1068 readfile() read a file into a List of lines 1069 readblob() read a file into a Blob 1070 readdir() get a List of file names in a directory 1071 readdirex() get a List of file information in a directory 1072 writefile() write a List of lines or Blob into a file 1073 filecopy() copy a file {from} to {to} 1074 1075 Date and Time: *date-functions* *time-functions* 1076 getftime() get last modification time of a file 1077 localtime() get current time in seconds 1078 strftime() convert time to a string 1079 strptime() convert a date/time string to time 1080 reltime() get the current or elapsed time accurately 1081 reltimestr() convert reltime() result to a string 1082 reltimefloat() convert reltime() result to a Float 1083 1084 Autocmds: *autocmd-functions* 1085 autocmd_add() add a list of autocmds and groups 1086 autocmd_delete() delete a list of autocmds and groups 1087 autocmd_get() return a list of autocmds 1088 1089 *buffer-functions* *window-functions* *arg-functions* 1090 Buffers, windows and the argument list: 1091 argc() number of entries in the argument list 1092 argidx() current position in the argument list 1093 arglistid() get id of the argument list 1094 argv() get one entry from the argument list 1095 bufadd() add a file to the list of buffers 1096 bufexists() check if a buffer exists 1097 buflisted() check if a buffer exists and is listed 1098 bufload() ensure a buffer is loaded 1099 bufloaded() check if a buffer exists and is loaded 1100 bufname() get the name of a specific buffer 1101 bufnr() get the buffer number of a specific buffer 1102 tabpagebuflist() return List of buffers in a tab page 1103 tabpagenr() get the number of a tab page 1104 tabpagewinnr() like winnr() for a specified tab page 1105 tabpanel_getinfo() get current state of the tabpanel 1106 tabpanel_scroll() scroll the tabpanel 1107 winnr() get the window number for the current window 1108 bufwinid() get the window ID of a specific buffer 1109 bufwinnr() get the window number of a specific buffer 1110 winbufnr() get the buffer number of a specific window 1111 listener_add() add a callback to listen to changes 1112 listener_flush() invoke listener callbacks 1113 listener_remove() remove a listener callback 1114 win_findbuf() find windows containing a buffer 1115 win_getid() get window ID of a window 1116 win_gettype() get type of window 1117 win_gotoid() go to window with ID 1118 win_id2tabwin() get tab and window nr from window ID 1119 win_id2win() get window nr from window ID 1120 win_move_separator() move window vertical separator 1121 win_move_statusline() move window status line 1122 win_splitmove() move window to a split of another window 1123 getbufinfo() get a list with buffer information 1124 gettabinfo() get a list with tab page information 1125 getwininfo() get a list with window information 1126 getchangelist() get a list of change list entries 1127 getjumplist() get a list of jump list entries 1128 swapfilelist() list of existing swap files in 'directory' 1129 swapinfo() information about a swap file 1130 swapname() get the swap file path of a buffer 1131 1132 Command line: *command-line-functions* 1133 getcmdcomplpat() get completion pattern of the current command 1134 line 1135 getcmdcompltype() get the type of the current command line 1136 completion 1137 getcmdline() get the current command line input 1138 getcmdprompt() get the current command line prompt 1139 getcmdpos() get position of the cursor in the command line 1140 getcmdscreenpos() get screen position of the cursor in the 1141 command line 1142 setcmdline() set the current command line 1143 setcmdpos() set position of the cursor in the command line 1144 getcmdtype() return the current command-line type 1145 getcmdwintype() return the current command-line window type 1146 getcompletion() list of command-line completion matches 1147 getcompletiontype() get the type of the command-line completion 1148 for specified string 1149 fullcommand() get full command name 1150 cmdcomplete_info() get command-line completion information 1151 1152 Quickfix and location lists: *quickfix-functions* 1153 getqflist() list of quickfix errors 1154 setqflist() modify a quickfix list 1155 getloclist() list of location list items 1156 setloclist() modify a location list 1157 1158 Insert mode completion: *completion-functions* 1159 complete() set found matches 1160 complete_add() add to found matches 1161 complete_check() check if completion should be aborted 1162 complete_info() get current completion information 1163 preinserted() check if text is inserted after cursor 1164 pumvisible() check if the popup menu is displayed 1165 pum_getpos() position and size of popup menu if visible 1166 1167 Folding: *folding-functions* 1168 foldclosed() check for a closed fold at a specific line 1169 foldclosedend() like foldclosed() but return the last line 1170 foldlevel() check for the fold level at a specific line 1171 foldtext() generate the line displayed for a closed fold 1172 foldtextresult() get the text displayed for a closed fold 1173 1174 Syntax and highlighting: *syntax-functions* *highlighting-functions* 1175 clearmatches() clear all matches defined by |matchadd()| and 1176 the |:match| commands 1177 getmatches() get all matches defined by |matchadd()| and 1178 the |:match| commands 1179 hlexists() check if a highlight group exists 1180 hlget() get highlight group attributes 1181 hlset() set highlight group attributes 1182 hlID() get ID of a highlight group 1183 synID() get syntax ID at a specific position 1184 synIDattr() get a specific attribute of a syntax ID 1185 synIDtrans() get translated syntax ID 1186 synstack() get list of syntax IDs at a specific position 1187 synconcealed() get info about (syntax) concealing 1188 diff_hlID() get highlight ID for diff mode at a position 1189 matchadd() define a pattern to highlight (a "match") 1190 matchaddpos() define a list of positions to highlight 1191 matcharg() get info about |:match| arguments 1192 matchdelete() delete a match defined by |matchadd()| or a 1193 |:match| command 1194 setmatches() restore a list of matches saved by 1195 |getmatches()| 1196 1197 Spelling: *spell-functions* 1198 spellbadword() locate badly spelled word at or after cursor 1199 spellsuggest() return suggested spelling corrections 1200 soundfold() return the sound-a-like equivalent of a word 1201 1202 History: *history-functions* 1203 histadd() add an item to a history 1204 histdel() delete an item from a history 1205 histget() get an item from a history 1206 histnr() get highest index of a history list 1207 1208 Interactive: *interactive-functions* 1209 browse() put up a file requester 1210 browsedir() put up a directory requester 1211 confirm() let the user make a choice 1212 getchar() get a character from the user 1213 getcharstr() get a character from the user as a string 1214 getcharmod() get modifiers for the last typed character 1215 getmousepos() get last known mouse position 1216 getmouseshape() get name of the current mouse shape 1217 echoraw() output characters as-is 1218 feedkeys() put characters in the typeahead queue 1219 input() get a line from the user 1220 inputlist() let the user pick an entry from a list 1221 inputsecret() get a line from the user without showing it 1222 inputdialog() get a line from the user in a dialog 1223 inputsave() save and clear typeahead 1224 inputrestore() restore typeahead 1225 1226 GUI: *gui-functions* 1227 getbgcolor() get current background colour as [r, g, b] 1228 getfontname() get name of current font being used 1229 getwinpos() position of the Vim window 1230 getwinposx() X position of the Vim window 1231 getwinposy() Y position of the Vim window 1232 balloon_show() set the balloon content 1233 balloon_split() split a message for a balloon 1234 balloon_gettext() get the text in the balloon 1235 1236 Vim server: *server-functions* 1237 serverlist() return the list of server names 1238 remote_startserver() run a server 1239 remote_send() send command characters to a Vim server 1240 remote_expr() evaluate an expression in a Vim server 1241 server2client() send a reply to a client of a Vim server 1242 remote_peek() check if there is a reply from a Vim server 1243 remote_read() read a reply from a Vim server 1244 foreground() move the Vim window to the foreground 1245 remote_foreground() move the Vim server window to the foreground 1246 1247 Window size and position: *window-size-functions* 1248 winheight() get height of a specific window 1249 winwidth() get width of a specific window 1250 win_screenpos() get screen position of a window 1251 winlayout() get layout of windows in a tab page 1252 winrestcmd() return command to restore window sizes 1253 winsaveview() get view of current window 1254 winrestview() restore saved view of current window 1255 1256 Mappings and Menus: *mapping-functions* 1257 digraph_get() get |digraph| 1258 digraph_getlist() get all |digraph|s 1259 digraph_set() register |digraph| 1260 digraph_setlist() register multiple |digraph|s 1261 hasmapto() check if a mapping exists 1262 mapcheck() check if a matching mapping exists 1263 maparg() get rhs of a mapping 1264 maplist() get list of all mappings 1265 mapset() restore a mapping 1266 menu_info() get information about a menu item 1267 wildmenumode() check if the wildmode is active 1268 wildtrigger() start wildcard expansion 1269 1270 Testing: *test-functions* 1271 assert_equal() assert that two expressions values are equal 1272 assert_equalfile() assert that two file contents are equal 1273 assert_notequal() assert that two expressions values are not 1274 equal 1275 assert_inrange() assert that an expression is inside a range 1276 assert_match() assert that a pattern matches the value 1277 assert_notmatch() assert that a pattern does not match the value 1278 assert_false() assert that an expression is false 1279 assert_true() assert that an expression is true 1280 assert_exception() assert that a command throws an exception 1281 assert_beeps() assert that a command beeps 1282 assert_nobeep() assert that a command does not cause a beep 1283 assert_fails() assert that a command fails 1284 assert_report() report a test failure 1285 test_alloc_fail() make memory allocation fail 1286 test_autochdir() enable 'autochdir' during startup 1287 test_override() test with Vim internal overrides 1288 test_garbagecollect_now() free memory right now 1289 test_garbagecollect_soon() set a flag to free memory soon 1290 test_getvalue() get value of an internal variable 1291 test_gui_event() generate a GUI event for testing 1292 test_ignore_error() ignore a specific error message 1293 test_mswin_event() generate an MS-Windows event 1294 test_null_blob() return a null Blob 1295 test_null_channel() return a null Channel 1296 test_null_dict() return a null Dict 1297 test_null_function() return a null Funcref 1298 test_null_job() return a null Job 1299 test_null_list() return a null List 1300 test_null_partial() return a null Partial function 1301 test_null_string() return a null String 1302 test_null_tuple() return a null Tuple 1303 test_settime() set the time Vim uses internally 1304 test_setmouse() set the mouse position 1305 test_feedinput() add key sequence to input buffer 1306 test_option_not_set() reset flag indicating option was set 1307 test_refcount() return an expression's reference count 1308 test_srand_seed() set the seed value for srand() 1309 test_unknown() return a value with unknown type 1310 test_void() return a value with void type 1311 1312 Inter-process communication: *channel-functions* 1313 ch_canread() check if there is something to read 1314 ch_close() close a channel 1315 ch_close_in() close the in part of a channel 1316 ch_evalexpr() evaluate an expression over channel 1317 ch_evalraw() evaluate a raw string over channel 1318 ch_getbufnr() get the buffer number for a channel 1319 ch_getjob() get the Job of a channel 1320 ch_info() get information about a channel 1321 ch_listen() listen on a channel 1322 ch_log() write a message in the channel log 1323 ch_logfile() start logging channel activity 1324 ch_open() open a channel 1325 ch_read() read a message from a channel 1326 ch_readblob() read a Blob from a channel 1327 ch_readraw() read a raw message from a channel 1328 ch_sendexpr() send a JSON message over a channel 1329 ch_sendraw() send a raw message over a channel 1330 ch_setoptions() set channel options 1331 ch_status() get status of a channel 1332 json_encode() encode an expression to a JSON string 1333 json_decode() decode a JSON string to Vim types 1334 js_encode() encode an expression to a JSON string 1335 js_decode() decode a JSON string to Vim types 1336 base64_encode() encode a blob into a base64 string 1337 base64_decode() decode a base64 string into a blob 1338 err_teapot() give error 418 or 503 1339 1340 Jobs: *job-functions* 1341 job_start() start a job 1342 job_stop() stop a job 1343 job_status() get the status of a job 1344 job_getchannel() get the channel used by a job 1345 job_info() get information about a job 1346 job_setoptions() set options for a job 1347 1348 Signs: *sign-functions* 1349 sign_define() define or update a sign 1350 sign_getdefined() get a list of defined signs 1351 sign_getplaced() get a list of placed signs 1352 sign_jump() jump to a sign 1353 sign_place() place a sign 1354 sign_placelist() place a list of signs 1355 sign_undefine() undefine a sign 1356 sign_unplace() unplace a sign 1357 sign_unplacelist() unplace a list of signs 1358 1359 Terminal window: *terminal-functions* 1360 term_start() open a terminal window and run a job 1361 term_list() get the list of terminal buffers 1362 term_sendkeys() send keystrokes to a terminal 1363 term_wait() wait for screen to be updated 1364 term_getjob() get the job associated with a terminal 1365 term_scrape() get row of a terminal screen 1366 term_getline() get a line of text from a terminal 1367 term_getattr() get the value of attribute {what} 1368 term_getcursor() get the cursor position of a terminal 1369 term_getscrolled() get the scroll count of a terminal 1370 term_getaltscreen() get the alternate screen flag 1371 term_getsize() get the size of a terminal 1372 term_getstatus() get the status of a terminal 1373 term_gettitle() get the title of a terminal 1374 term_gettty() get the tty name of a terminal 1375 term_setansicolors() set 16 ANSI colors, used for GUI 1376 term_getansicolors() get 16 ANSI colors, used for GUI 1377 term_dumpdiff() display difference between two screen dumps 1378 term_dumpload() load a terminal screen dump in a window 1379 term_dumpwrite() dump contents of a terminal screen to a file 1380 term_setkill() set signal to stop job in a terminal 1381 term_setrestore() set command to restore a terminal 1382 term_setsize() set the size of a terminal 1383 term_setapi() set terminal JSON API function name prefix 1384 1385 Popup window: *popup-window-functions* 1386 popup_create() create popup centered in the screen 1387 popup_atcursor() create popup just above the cursor position, 1388 closes when the cursor moves away 1389 popup_beval() at the position indicated by v:beval_ 1390 variables, closes when the mouse moves away 1391 popup_notification() show a notification for three seconds 1392 popup_dialog() create popup centered with padding and border 1393 popup_menu() prompt for selecting an item from a list 1394 popup_hide() hide a popup temporarily 1395 popup_show() show a previously hidden popup 1396 popup_move() change the position and size of a popup 1397 popup_setoptions() override options of a popup 1398 popup_settext() replace the popup buffer contents 1399 popup_setbuf() set the popup buffer 1400 popup_close() close one popup 1401 popup_clear() close all popups 1402 popup_filter_menu() select from a list of items 1403 popup_filter_yesno() block until 'y' or 'n' is pressed 1404 popup_getoptions() get current options for a popup 1405 popup_getpos() get actual position and size of a popup 1406 popup_findecho() get window ID for popup used for `:echowindow` 1407 popup_findinfo() get window ID for popup info window 1408 popup_findpreview() get window ID for popup preview window 1409 popup_list() get list of all popup window IDs 1410 popup_locate() get popup window ID from its screen position 1411 1412 Timers: *timer-functions* 1413 timer_start() create a timer 1414 timer_pause() pause or unpause a timer 1415 timer_stop() stop a timer 1416 timer_stopall() stop all timers 1417 timer_info() get information about timers 1418 1419 Tags: *tag-functions* 1420 taglist() get list of matching tags 1421 tagfiles() get a list of tags files 1422 gettagstack() get the tag stack of a window 1423 settagstack() modify the tag stack of a window 1424 1425 Prompt Buffer: *promptbuffer-functions* 1426 prompt_getprompt() get the effective prompt text for a buffer 1427 prompt_setcallback() set prompt callback for a buffer 1428 prompt_setinterrupt() set interrupt callback for a buffer 1429 prompt_setprompt() set the prompt text for a buffer 1430 1431 Registers: *register-functions* 1432 getreg() get contents of a register 1433 getreginfo() get information about a register 1434 getregtype() get type of a register 1435 setreg() set contents and type of a register 1436 reg_executing() return the name of the register being executed 1437 reg_recording() return the name of the register being recorded 1438 1439 Text Properties: *text-property-functions* 1440 prop_add() attach a property at a position 1441 prop_add_list() attach a property at multiple positions 1442 prop_clear() remove all properties from a line or lines 1443 prop_find() search for a property 1444 prop_list() return a list of all properties in a line 1445 prop_remove() remove a property from a line 1446 prop_type_add() add/define a property type 1447 prop_type_change() change properties of a type 1448 prop_type_delete() remove a text property type 1449 prop_type_get() return the properties of a type 1450 prop_type_list() return a list of all property types 1451 1452 Sound: *sound-functions* 1453 sound_clear() stop playing all sounds 1454 sound_playevent() play an event's sound 1455 sound_playfile() play a sound file 1456 sound_stop() stop playing a sound 1457 1458 Images: *image-functions* 1459 image_add() add an image 1460 image_discard() discard an image 1461 image_info() get information about image(s) 1462 1463 Various: *various-functions* 1464 mode() get current editing mode 1465 state() get current busy state 1466 visualmode() last visual mode used 1467 exists() check if a variable, function, etc. exists 1468 exists_compiled() like exists() but check at compile time 1469 getinfo() get the definition of a function, command, 1470 option or Vim variable 1471 has() check if a feature is supported in Vim 1472 changenr() return number of most recent change 1473 cscope_connection() check if a cscope connection exists 1474 did_filetype() check if a FileType autocommand was used 1475 diff() diff two Lists of strings 1476 eventhandler() check if invoked by an event handler 1477 getcellpixels() get List of cell pixel size 1478 getpid() get process ID of Vim 1479 getscriptinfo() get list of sourced Vim scripts 1480 getstacktrace() get current stack trace of Vim scripts 1481 getimstatus() check if IME status is active 1482 interrupt() interrupt script execution 1483 windowsversion() get MS-Windows version 1484 terminalprops() properties of the terminal 1485 1486 libcall() call a function in an external library 1487 libcallnr() idem, returning a number 1488 1489 undofile() get the name of the undo file 1490 undotree() return the state of the undo tree for a buffer 1491 1492 shiftwidth() effective value of 'shiftwidth' 1493 1494 wordcount() get byte/word/char count of buffer 1495 1496 id() get unique string for item to use as a key 1497 1498 luaeval() evaluate |Lua| expression 1499 mzeval() evaluate |MzScheme| expression 1500 perleval() evaluate Perl expression 1501 py3eval() evaluate Python expression 1502 pyeval() evaluate Python expression 1503 pyxeval() evaluate |python_x| expression 1504 rubyeval() evaluate |Ruby| expression 1505 1506 debugbreak() interrupt a program being debugged 1507 1508 redraw_listener_add() add callbacks to listen for redraws 1509 redraw_listener_remove() remove a redraw listener 1510 1511 ============================================================================== 1512 *41.7* Defining a function 1513 1514 Vim enables you to define your own functions. The basic function declaration 1515 begins as follows: > 1516 1517 def {name}({var1}, {var2}, ...): return-type 1518 {body} 1519 enddef 1520 < 1521 Note: 1522 Function names must begin with a capital letter. 1523 1524 Let's define a short function to return the smaller of two numbers. It starts 1525 with this line: > 1526 1527 def Min(num1: number, num2: number): number 1528 1529 This tells Vim that the function is named "Min", it takes two arguments that 1530 are numbers: "num1" and "num2" and returns a number. 1531 1532 The first thing you need to do is to check to see which number is smaller: 1533 > 1534 if num1 < num2 1535 1536 Let's assign the variable "smaller" the value of the smallest number: > 1537 1538 var smaller: number 1539 if num1 < num2 1540 smaller = num1 1541 else 1542 smaller = num2 1543 endif 1544 1545 The variable "smaller" is a local variable. It is declared to be a number, 1546 that way Vim can warn you for any mistakes. Variables used inside a function 1547 are local unless prefixed by something like "g:", "w:", or "b:". 1548 1549 Note: 1550 To access a global variable from inside a function you must prepend 1551 "g:" to it. Thus "g:today" inside a function is used for the global 1552 variable "today", and "today" is another variable, local to the 1553 function or the script. 1554 1555 You now use the `return` statement to return the smallest number to the user. 1556 Finally, you end the function: > 1557 1558 return smaller 1559 enddef 1560 1561 The complete function definition is as follows: > 1562 1563 def Min(num1: number, num2: number): number 1564 var smaller: number 1565 if num1 < num2 1566 smaller = num1 1567 else 1568 smaller = num2 1569 endif 1570 return smaller 1571 enddef 1572 1573 Obviously this is a verbose example. You can make it shorter by using two 1574 return commands: > 1575 1576 def Min(num1: number, num2: number): number 1577 if num1 < num2 1578 return num1 1579 endif 1580 return num2 1581 enddef 1582 1583 And if you remember the conditional expression, you need only one line: > 1584 1585 def Min(num1: number, num2: number): number 1586 return num1 < num2 ? num1 : num2 1587 enddef 1588 1589 A user defined function is called in exactly the same way as a built-in 1590 function. Only the name is different. The Min function can be used like 1591 this: > 1592 1593 echo Min(5, 8) 1594 1595 Only now will the function be executed and the lines be parsed by Vim. 1596 If there are mistakes, like using an undefined variable or function, you will 1597 now get an error message. When defining the function these errors are not 1598 detected. To get the errors sooner you can tell Vim to compile all the 1599 functions in the script: > 1600 1601 defcompile 1602 1603 Compiling functions takes a little time, but does report errors early. You 1604 could use `:defcompile` at the end of your script while working on it, and 1605 comment it out when everything is fine. 1606 1607 For a function that does not return anything simply leave out the return type: > 1608 1609 def SayIt(text: string) 1610 echo text 1611 enddef 1612 1613 If you want to return any kind of value, you can use the "any" return type: > 1614 def GetValue(): any 1615 This disables type checking for the return value, use only when needed. 1616 1617 It is also possible to define a legacy function with `function` and 1618 `endfunction`. These do not have types and are not compiled. Therefore they 1619 execute much slower. 1620 1621 1622 USING A RANGE 1623 1624 A line range can be used with a function call. The function will be called 1625 once for every line in the range, with the cursor in that line. Example: > 1626 1627 def Number() 1628 echo "line " .. line(".") .. " contains: " .. getline(".") 1629 enddef 1630 1631 If you call this function with: > 1632 1633 :10,15call Number() 1634 1635 The function will be called six times, starting on line 10 and ending on line 1636 15. 1637 1638 1639 LISTING FUNCTIONS 1640 1641 The `function` command lists the names and arguments of all user-defined 1642 functions: > 1643 1644 :function 1645 < def <SNR>86_Show(start: string, ...items: list<string>) ~ 1646 function GetVimIndent() ~ 1647 function SetSyn(name) ~ 1648 1649 The "<SNR>" prefix means that a function is script-local. |Vim9| functions 1650 will start with "def" and include argument and return types. Legacy functions 1651 are listed with "function". 1652 1653 To see what a function does, use its name as an argument for `function`: > 1654 1655 :function SetSyn 1656 < 1 if &syntax == '' ~ 1657 2 let &syntax = a:name ~ 1658 3 endif ~ 1659 endfunction ~ 1660 1661 To see the "Show" function you need to include the script prefix, since 1662 multiple "Show" functions can be defined in different scripts. To find 1663 the exact name you can use `function`, but the result may be a very long list. 1664 To only get the functions matching a pattern you can use the `filter` prefix: 1665 > 1666 :filter Show function 1667 < def <SNR>86_Show(start: string, ...items: list<string>) ~ 1668 > 1669 :function <SNR>86_Show 1670 < 1 echohl Title ~ 1671 2 echo "start is " .. start ~ 1672 etc. 1673 1674 1675 DEBUGGING 1676 1677 The line number is useful for when you get an error message or when debugging. 1678 See |debug-scripts| about debugging mode. 1679 1680 You can also set the 'verbose' option to 12 or higher to see all function 1681 calls. Set it to 15 or higher to see every executed line. 1682 1683 1684 DELETING A FUNCTION 1685 1686 To delete the SetSyn() function: > 1687 1688 :delfunction SetSyn 1689 1690 Deleting only works for global functions and functions in legacy script, not 1691 for functions defined in a |Vim9| script. 1692 1693 You get an error when the function doesn't exist or cannot be deleted. 1694 1695 1696 FUNCTION REFERENCES 1697 1698 Sometimes it can be useful to have a variable point to one function or 1699 another. You can do it with a function reference variable. Often shortened 1700 to "funcref". Example: > 1701 1702 def Right(): string 1703 return 'Right!' 1704 enddef 1705 def Wrong(): string 1706 return 'Wrong!' 1707 enddef 1708 1709 var Afunc = g:result == 1 ? Right : Wrong 1710 echo Afunc() 1711 < Wrong! ~ 1712 1713 This assumes "g:result" is not one. See |Funcref| for details. 1714 1715 Note that the name of a variable that holds a function reference must start 1716 with a capital. Otherwise it could be confused with the name of a builtin 1717 function. 1718 1719 1720 FURTHER READING 1721 1722 Using a variable number of arguments is introduced in section |50.2|. 1723 1724 More information about defining your own functions here: |user-functions|. 1725 1726 ============================================================================== 1727 *41.8* Lists and Dictionaries 1728 1729 So far we have used the basic types String and Number. Vim also supports 1730 three composite types: List, Tuple and Dictionary. 1731 1732 A List is an ordered sequence of items. The items can be any kind of value, 1733 thus you can make a List of numbers, a List of Lists and even a List of mixed 1734 items. To create a List with three strings: > 1735 1736 var alist = ['aap', 'noot', 'mies'] 1737 1738 The List items are enclosed in square brackets and separated by commas. To 1739 create an empty List: > 1740 1741 var alist = [] 1742 1743 You can add items to a List with the add() function: > 1744 1745 var alist = [] 1746 add(alist, 'foo') 1747 add(alist, 'bar') 1748 echo alist 1749 < ['foo', 'bar'] ~ 1750 1751 List concatenation is done with +: > 1752 1753 var alist = ['foo', 'bar'] 1754 alist = alist + ['and', 'more'] 1755 echo alist 1756 < ['foo', 'bar', 'and', 'more'] ~ 1757 1758 Or, if you want to extend a List with a function, use `extend()`: > 1759 1760 var alist = ['one'] 1761 extend(alist, ['two', 'three']) 1762 echo alist 1763 < ['one', 'two', 'three'] ~ 1764 1765 Notice that using `add()` will have a different effect than `extend()`: > 1766 1767 var alist = ['one'] 1768 add(alist, ['two', 'three']) 1769 echo alist 1770 < ['one', ['two', 'three']] ~ 1771 1772 The second argument of add() is added as an item, now you have a nested list. 1773 1774 1775 FOR LOOP 1776 1777 One of the nice things you can do with a List is iterate over it: > 1778 1779 var alist = ['one', 'two', 'three'] 1780 for n in alist 1781 echo n 1782 endfor 1783 < one ~ 1784 two ~ 1785 three ~ 1786 1787 This will loop over each element in List "alist", assigning each value to 1788 variable "n". The generic form of a for loop is: > 1789 1790 for {varname} in {list-expression} 1791 {commands} 1792 endfor 1793 1794 To loop a certain number of times you need a List of a specific length. The 1795 range() function creates one for you: > 1796 1797 for a in range(3) 1798 echo a 1799 endfor 1800 < 0 ~ 1801 1 ~ 1802 2 ~ 1803 1804 Notice that the first item of the List that range() produces is zero, thus the 1805 last item is one less than the length of the list. Detail: Internally range() 1806 does not actually create the list, so that a large range used in a for loop 1807 works efficiently. When used elsewhere, the range is turned into an actual 1808 list, which takes more time for a long list. 1809 1810 You can also specify the maximum value, the stride and even go backwards: > 1811 1812 for a in range(8, 4, -2) 1813 echo a 1814 endfor 1815 < 8 ~ 1816 6 ~ 1817 4 ~ 1818 1819 A more useful example, looping over all the lines in the buffer: > 1820 1821 for line in getline(1, 50) 1822 if line =~ "Date: " 1823 echo line 1824 endif 1825 endfor 1826 1827 This looks into lines 1 to 50 (inclusive) and echoes any date found in there. 1828 1829 For further reading see |Lists|. 1830 1831 TUPLE 1832 1833 A Tuple is an immutable ordered sequence of items. An item can be of any 1834 type. Items can be accessed by their index number. To create a Tuple with 1835 three strings: > 1836 1837 var atuple = ('one', 'two', 'three') 1838 1839 The Tuple items are enclosed in parenthesis and separated by commas. To 1840 create an empty Tuple: > 1841 1842 var atuple = () 1843 1844 The |:for| loop can be used to iterate over the items in a Tuple similar to a 1845 List. 1846 1847 For further reading see |Tuples|. 1848 1849 DICTIONARIES 1850 1851 A Dictionary stores key-value pairs. You can quickly lookup a value if you 1852 know the key. A Dictionary is created with curly braces: > 1853 1854 var uk2nl = {one: 'een', two: 'twee', three: 'drie'} 1855 1856 Now you can lookup words by putting the key in square brackets: > 1857 1858 echo uk2nl['two'] 1859 < twee ~ 1860 1861 If the key does not have special characters, you can use the dot notation: > 1862 1863 echo uk2nl.two 1864 < twee ~ 1865 1866 The generic form for defining a Dictionary is: > 1867 1868 {<key> : <value>, ...} 1869 1870 An empty Dictionary is one without any keys: > 1871 1872 {} 1873 1874 The possibilities with Dictionaries are numerous. There are various functions 1875 for them as well. For example, you can obtain a list of the keys and loop 1876 over them: > 1877 1878 for key in keys(uk2nl) 1879 echo key 1880 endfor 1881 < three ~ 1882 one ~ 1883 two ~ 1884 1885 You will notice the keys are not ordered. You can sort the list to get a 1886 specific order: > 1887 1888 for key in sort(keys(uk2nl)) 1889 echo key 1890 endfor 1891 < one ~ 1892 three ~ 1893 two ~ 1894 1895 But you can never get back the order in which items are defined. For that you 1896 need to use a List, it stores items in an ordered sequence. 1897 1898 For further reading see |Dictionaries|. 1899 1900 ============================================================================== 1901 *41.9* White space 1902 1903 Blank lines are allowed in a script and ignored. 1904 1905 Leading whitespace characters (blanks and TABs) are ignored, except when using 1906 |:let-heredoc| without "trim". 1907 1908 Trailing whitespace is often ignored, but not always. One command that 1909 includes it is `map`. You have to watch out for that, it can cause hard to 1910 understand mistakes. A generic solution is to never use trailing white space, 1911 unless you really need it. 1912 1913 To include a whitespace character in the value of an option, it must be 1914 escaped by a "\" (backslash) as in the following example: > 1915 1916 :set tags=my\ nice\ file 1917 1918 If it would be written as: > 1919 1920 :set tags=my nice file 1921 1922 This will issue an error, because it is interpreted as: > 1923 1924 :set tags=my 1925 :set nice 1926 :set file 1927 1928 |Vim9| script is very picky when it comes to white space. This was done 1929 intentionally to make sure scripts are easy to read and to avoid mistakes. 1930 If you use white space sensibly it will just work. When not you will get an 1931 error message telling you where white space is missing or should be removed. 1932 1933 ============================================================================== 1934 *41.10* Line continuation 1935 1936 In legacy Vim script line continuation is done by preceding a continuation 1937 line with a backslash: > 1938 let mylist = [ 1939 \ 'one', 1940 \ 'two', 1941 \ ] 1942 1943 This requires the 'cpo' option to exclude the "C" flag. Normally this is done 1944 by putting this at the start of the script: > 1945 let s:save_cpo = &cpo 1946 set cpo&vim 1947 1948 And restore the option at the end of the script: > 1949 let &cpo = s:save_cpo 1950 unlet s:save_cpo 1951 1952 A few more details can be found here: |line-continuation|. 1953 1954 In |Vim9| script the backslash can still be used, but in most places it is not 1955 needed: > 1956 var mylist = [ 1957 'one', 1958 'two', 1959 ] 1960 1961 Also, the 'cpo' option does not need to be changed. See 1962 |vim9-line-continuation| for details. 1963 1964 ============================================================================== 1965 *41.11* Comments 1966 1967 In |Vim9| script the character # starts a comment. That character and 1968 everything after it until the end-of-line is considered a comment and 1969 is ignored, except for commands that don't consider comments, as shown in 1970 examples below. A comment can start on any character position on the line, 1971 but not when it is part of the command, e.g. inside a string. 1972 1973 The character " (the double quote mark) starts a comment in legacy script. 1974 This involves some cleverness to make sure double quoted strings are not 1975 recognized as comments (just one reason to prefer |Vim9| script). 1976 1977 There is a little "catch" with comments for some commands. Examples: > 1978 1979 abbrev dev development # shorthand 1980 map <F3> o#include # insert include 1981 execute cmd # do it 1982 !ls *.c # list C files 1983 1984 - The abbreviation 'dev' will be expanded to 'development # shorthand'. 1985 - The mapping of <F3> will actually be the whole line after the 'o# ....' 1986 including the '# insert include'. 1987 - The `execute` command will give an error. 1988 - The `!` command will send everything after it to the shell, most likely 1989 causing an error. 1990 1991 There can be no comment after `map`, `abbreviate`, `execute` and `!` commands 1992 (there are a few more commands with this restriction). For the `map`, 1993 `abbreviate` and `execute` commands there is a trick: > 1994 1995 abbrev dev development|# shorthand 1996 map <F3> o#include|# insert include 1997 execute '!ls *.c' |# do it 1998 1999 With the '|' character the command is separated from the next one. And that 2000 next command is only a comment. The last command, using `execute` is a 2001 general solution, it works for all commands that do not accept a comment or a 2002 '|' to separate the next command. 2003 2004 Notice that there is no white space before the '|' in the abbreviation and 2005 mapping. For these commands, any character until the end-of-line or '|' is 2006 included. As a consequence of this behavior, you don't always see that 2007 trailing whitespace is included: > 2008 2009 map <F4> o#include 2010 2011 Here it is intended, in other cases it might be accidental. To spot these 2012 problems, you can highlight trailing spaces: > 2013 match Search /\s\+$/ 2014 2015 For Unix there is one special way to comment a line, that allows making a Vim 2016 script executable, and it also works in legacy script: > 2017 #!/usr/bin/env vim -S 2018 echo "this is a Vim script" 2019 quit 2020 2021 ============================================================================== 2022 *41.12* Fileformat 2023 2024 The end-of-line character depends on the system. For Vim scripts it is 2025 recommended to always use the Unix fileformat. Lines are then separated with 2026 the Newline character. This also works on any other system. That way you can 2027 copy your Vim scripts from MS-Windows to Unix and they still work. See 2028 |:source_crnl|. To be sure it is set right, do this before writing the file: 2029 > 2030 :setlocal fileformat=unix 2031 2032 When using "dos" fileformat, lines are separated with CR-NL, two characters. 2033 The CR character causes various problems, better avoid this. 2034 2035 ============================================================================== 2036 2037 Advance information about writing Vim script is in |usr_50.txt|. 2038 2039 Next chapter: |usr_42.txt| Add new menus 2040 2041 Copyright: see |manual-copyright| vim:tw=78:ts=8:noet:ft=help:norl: