1*usr_41.txt* For Vim version 8.2. Last change: 2021 Sep 10 2 3 VIM USER MANUAL - by Bram Moolenaar 4 5 Write a Vim script 6 7 8The Vim script language is used for the startup vimrc file, syntax files, and 9many other things. This chapter explains the items that can be used in a Vim 10script. There are a lot of them, thus this is a long chapter. 11 12|41.1| Introduction 13|41.2| Variables 14|41.3| Expressions 15|41.4| Conditionals 16|41.5| Executing an expression 17|41.6| Using functions 18|41.7| Defining a function 19|41.8| Lists and Dictionaries 20|41.9| Exceptions 21|41.10| Various remarks 22|41.11| Writing a plugin 23|41.12| Writing a filetype plugin 24|41.13| Writing a compiler plugin 25|41.14| Writing a plugin that loads quickly 26|41.15| Writing library scripts 27|41.16| Distributing Vim scripts 28 29 Next chapter: |usr_42.txt| Add new menus 30 Previous chapter: |usr_40.txt| Make new commands 31Table of contents: |usr_toc.txt| 32 33============================================================================== 34*41.1* Introduction *vim-script-intro* *script* 35 36Your first experience with Vim scripts is the vimrc file. Vim reads it when 37it starts up and executes the commands. You can set options to values you 38prefer. And you can use any colon command in it (commands that start with a 39":"; these are sometimes referred to as Ex commands or command-line commands). 40 Syntax files are also Vim scripts. As are files that set options for a 41specific file type. A complicated macro can be defined by a separate Vim 42script file. You can think of other uses yourself. 43 44 If you are familiar with Python, you can find a comparison between 45 Python and Vim script here, with pointers to other documents: 46 https://gist.github.com/yegappan/16d964a37ead0979b05e655aa036cad0 47 And if you are familiar with JavaScript: 48 https://w0rp.com/blog/post/vim-script-for-the-javascripter/ 49 50Let's start with a simple example: > 51 52 :let i = 1 53 :while i < 5 54 : echo "count is" i 55 : let i += 1 56 :endwhile 57< 58 Note: 59 The ":" characters are not really needed here. You only need to use 60 them when you type a command. In a Vim script file they can be left 61 out. We will use them here anyway to make clear these are colon 62 commands and make them stand out from Normal mode commands. 63 Note: 64 You can try out the examples by yanking the lines from the text here 65 and executing them with :@" 66 67The output of the example code is: 68 69 count is 1 ~ 70 count is 2 ~ 71 count is 3 ~ 72 count is 4 ~ 73 74In the first line the ":let" command assigns a value to a variable. The 75generic form is: > 76 77 :let {variable} = {expression} 78 79In this case the variable name is "i" and the expression is a simple value, 80the number one. 81 The ":while" command starts a loop. The generic form is: > 82 83 :while {condition} 84 : {statements} 85 :endwhile 86 87The statements until the matching ":endwhile" are executed for as long as the 88condition is true. The condition used here is the expression "i < 5". This 89is true when the variable i is smaller than five. 90 Note: 91 If you happen to write a while loop that keeps on running, you can 92 interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows). 93 94The ":echo" command prints its arguments. In this case the string "count is" 95and the value of the variable i. Since i is one, this will print: 96 97 count is 1 ~ 98 99Then there is the ":let i += 1" command. This does the same thing as 100":let i = i + 1". This adds one to the variable i and assigns the new value 101to the same variable. 102Note: this is how it works in legacy Vim script, which is what we discuss in 103this file. In Vim9 script it's a bit different, see |usr_46.txt|. 104 105The example was given to explain the commands, but would you really want to 106make such a loop, it can be written much more compact: > 107 108 :for i in range(1, 4) 109 : echo "count is" i 110 :endfor 111 112We won't explain how |:for| and |range()| work until later. Follow the links 113if you are impatient. 114 115 116FOUR KINDS OF NUMBERS 117 118Numbers can be decimal, hexadecimal, octal or binary. 119 120A hexadecimal number starts with "0x" or "0X". For example "0x1f" is decimal 12131. 122 123An octal number starts with "0o", "0O" or a zero and another digit. "0o17" is 124decimal 15. Using just a zero prefix is not supported in Vim9 script. 125 126A binary number starts with "0b" or "0B". For example "0b101" is decimal 5. 127 128A decimal number is just digits. Careful: don't put a zero before a decimal 129number, it will be interpreted as an octal number in legacy script! 130 131The ":echo" command always prints decimal numbers. Example: > 132 133 :echo 0x7f 0o36 134< 127 30 ~ 135 136A number is made negative with a minus sign. This also works for hexadecimal, 137octal and binary numbers. A minus sign is also used for subtraction. Compare 138this with the previous example: > 139 140 :echo 0x7f -0o36 141< 97 ~ 142 143White space in an expression is ignored. However, it's recommended to use it 144for separating items, to make the expression easier to read. For example, to 145avoid the confusion with a negative number above, put a space between the 146minus sign and the following number: > 147 148 :echo 0x7f - 0o36 149 150============================================================================== 151*41.2* Variables 152 153A variable name consists of ASCII letters, digits and the underscore. It 154cannot start with a digit. Valid variable names are: 155 156 counter 157 _aap3 158 very_long_variable_name_with_underscores 159 FuncLength 160 LENGTH 161 162Invalid names are "foo+bar" and "6var". 163 These variables are global. To see a list of currently defined variables 164use this command: > 165 166 :let 167 168You can use global variables everywhere. This also means that when the 169variable "count" is used in one script file, it might also be used in another 170file. This leads to confusion at least, and real problems at worst. To avoid 171this, you can use a variable local to a script file by prepending "s:". For 172example, one script contains this code: > 173 174 :let s:count = 1 175 :while s:count < 5 176 : source other.vim 177 : let s:count += 1 178 :endwhile 179 180Since "s:count" is local to this script, you can be sure that sourcing the 181"other.vim" script will not change this variable. If "other.vim" also uses an 182"s:count" variable, it will be a different copy, local to that script. More 183about script-local variables here: |script-variable|. 184 185There are more kinds of variables, see |internal-variables|. The most often 186used ones are: 187 188 b:name variable local to a buffer 189 w:name variable local to a window 190 g:name global variable (also in a function) 191 v:name variable predefined by Vim 192 193 194DELETING VARIABLES 195 196Variables take up memory and show up in the output of the ":let" command. To 197delete a variable use the ":unlet" command. Example: > 198 199 :unlet s:count 200 201This deletes the script-local variable "s:count" to free up the memory it 202uses. If you are not sure if the variable exists, and don't want an error 203message when it doesn't, append !: > 204 205 :unlet! s:count 206 207When a script finishes, the local variables used there will not be 208automatically freed. The next time the script executes, it can still use the 209old value. Example: > 210 211 :if !exists("s:call_count") 212 : let s:call_count = 0 213 :endif 214 :let s:call_count = s:call_count + 1 215 :echo "called" s:call_count "times" 216 217The "exists()" function checks if a variable has already been defined. Its 218argument is the name of the variable you want to check. Not the variable 219itself! If you would do this: > 220 221 :if !exists(s:call_count) 222 223Then the value of s:call_count will be used as the name of the variable that 224exists() checks. That's not what you want. 225 The exclamation mark ! negates a value. When the value was true, it 226becomes false. When it was false, it becomes true. You can read it as "not". 227Thus "if !exists()" can be read as "if not exists()". 228 What Vim calls true is anything that is not zero. Zero is false. 229 Note: 230 Vim automatically converts a string to a number when it is looking for 231 a number. When using a string that doesn't start with a digit the 232 resulting number is zero. Thus look out for this: > 233 :if "true" 234< The "true" will be interpreted as a zero, thus as false! 235 236 237STRING VARIABLES AND CONSTANTS 238 239So far only numbers were used for the variable value. Strings can be used as 240well. Numbers and strings are the basic types of variables that Vim supports. 241The type is dynamic, it is set each time when assigning a value to the 242variable with ":let". More about types in |41.8|. 243 To assign a string value to a variable, you need to use a string constant. 244There are two types of these. First the string in double quotes: > 245 246 :let name = "peter" 247 :echo name 248< peter ~ 249 250If you want to include a double quote inside the string, put a backslash in 251front of it: > 252 253 :let name = "\"peter\"" 254 :echo name 255< "peter" ~ 256 257To avoid the need for a backslash, you can use a string in single quotes: > 258 259 :let name = '"peter"' 260 :echo name 261< "peter" ~ 262 263Inside a single-quote string all the characters are as they are. Only the 264single quote itself is special: you need to use two to get one. A backslash 265is taken literally, thus you can't use it to change the meaning of the 266character after it. 267 In double-quote strings it is possible to use special characters. Here are 268a few useful ones: 269 270 \t <Tab> 271 \n <NL>, line break 272 \r <CR>, <Enter> 273 \e <Esc> 274 \b <BS>, backspace 275 \" " 276 \\ \, backslash 277 \<Esc> <Esc> 278 \<C-W> CTRL-W 279 280The last two are just examples. The "\<name>" form can be used to include 281the special key "name". 282 See |expr-quote| for the full list of special items in a string. 283 284============================================================================== 285*41.3* Expressions 286 287Vim has a rich, yet simple way to handle expressions. You can read the 288definition here: |expression-syntax|. Here we will show the most common 289items. 290 The numbers, strings and variables mentioned above are expressions by 291themselves. Thus everywhere an expression is expected, you can use a number, 292string or variable. Other basic items in an expression are: 293 294 $NAME environment variable 295 &name option 296 @r register 297 298Examples: > 299 300 :echo "The value of 'tabstop' is" &ts 301 :echo "Your home directory is" $HOME 302 :if @a > 5 303 304The &name form can be used to save an option value, set it to a new value, 305do something and restore the old value. Example: > 306 307 :let save_ic = &ic 308 :set noic 309 :/The Start/,$delete 310 :let &ic = save_ic 311 312This makes sure the "The Start" pattern is used with the 'ignorecase' option 313off. Still, it keeps the value that the user had set. (Another way to do 314this would be to add "\C" to the pattern, see |/\C|.) 315 316 317MATHEMATICS 318 319It becomes more interesting if we combine these basic items. Let's start with 320mathematics on numbers: 321 322 a + b add 323 a - b subtract 324 a * b multiply 325 a / b divide 326 a % b modulo 327 328The usual precedence is used. Example: > 329 330 :echo 10 + 5 * 2 331< 20 ~ 332 333Grouping is done with parentheses. No surprises here. Example: > 334 335 :echo (10 + 5) * 2 336< 30 ~ 337 338Strings can be concatenated with ".." (see |expr6|). Example: > 339 340 :echo "foo" .. "bar" 341< foobar ~ 342 343When the ":echo" command gets multiple arguments, it separates them with a 344space. In the example the argument is a single expression, thus no space is 345inserted. 346 347Borrowed from the C language is the conditional expression: 348 349 a ? b : c 350 351If "a" evaluates to true "b" is used, otherwise "c" is used. Example: > 352 353 :let i = 4 354 :echo i > 5 ? "i is big" : "i is small" 355< i is small ~ 356 357The three parts of the constructs are always evaluated first, thus you could 358see it work as: 359 360 (a) ? (b) : (c) 361 362============================================================================== 363*41.4* Conditionals 364 365The ":if" commands executes the following statements, until the matching 366":endif", only when a condition is met. The generic form is: 367 368 :if {condition} 369 {statements} 370 :endif 371 372Only when the expression {condition} evaluates to true (non-zero) will the 373{statements} be executed. These must still be valid commands. If they 374contain garbage, Vim won't be able to find the ":endif". 375 You can also use ":else". The generic form for this is: 376 377 :if {condition} 378 {statements} 379 :else 380 {statements} 381 :endif 382 383The second {statements} is only executed if the first one isn't. 384 Finally, there is ":elseif": 385 386 :if {condition} 387 {statements} 388 :elseif {condition} 389 {statements} 390 :endif 391 392This works just like using ":else" and then "if", but without the need for an 393extra ":endif". 394 A useful example for your vimrc file is checking the 'term' option and 395doing something depending upon its value: > 396 397 :if &term == "xterm" 398 : " Do stuff for xterm 399 :elseif &term == "vt100" 400 : " Do stuff for a vt100 terminal 401 :else 402 : " Do something for other terminals 403 :endif 404 405 406LOGIC OPERATIONS 407 408We already used some of them in the examples. These are the most often used 409ones: 410 411 a == b equal to 412 a != b not equal to 413 a > b greater than 414 a >= b greater than or equal to 415 a < b less than 416 a <= b less than or equal to 417 418The result is one if the condition is met and zero otherwise. An example: > 419 420 :if v:version >= 700 421 : echo "congratulations" 422 :else 423 : echo "you are using an old version, upgrade!" 424 :endif 425 426Here "v:version" is a variable defined by Vim, which has the value of the Vim 427version. 600 is for version 6.0. Version 6.1 has the value 601. This is 428very useful to write a script that works with multiple versions of Vim. 429|v:version| 430 431The logic operators work both for numbers and strings. When comparing two 432strings, the mathematical difference is used. This compares byte values, 433which may not be right for some languages. 434 When comparing a string with a number, the string is first converted to a 435number. This is a bit tricky, because when a string doesn't look like a 436number, the number zero is used. Example: > 437 438 :if 0 == "one" 439 : echo "yes" 440 :endif 441 442This will echo "yes", because "one" doesn't look like a number, thus it is 443converted to the number zero. 444 445For strings there are two more items: 446 447 a =~ b matches with 448 a !~ b does not match with 449 450The left item "a" is used as a string. The right item "b" is used as a 451pattern, like what's used for searching. Example: > 452 453 :if str =~ " " 454 : echo "str contains a space" 455 :endif 456 :if str !~ '\.$' 457 : echo "str does not end in a full stop" 458 :endif 459 460Notice the use of a single-quote string for the pattern. This is useful, 461because backslashes would need to be doubled in a double-quote string and 462patterns tend to contain many backslashes. 463 464The 'ignorecase' option is used when comparing strings. When you don't want 465that, append "#" to match case and "?" to ignore case. Thus "==?" compares 466two strings to be equal while ignoring case. And "!~#" checks if a pattern 467doesn't match, also checking the case of letters. For the full table see 468|expr-==|. 469 470 471MORE LOOPING 472 473The ":while" command was already mentioned. Two more statements can be used 474in between the ":while" and the ":endwhile": 475 476 :continue Jump back to the start of the while loop; the 477 loop continues. 478 :break Jump forward to the ":endwhile"; the loop is 479 discontinued. 480 481Example: > 482 483 :while counter < 40 484 : call do_something() 485 : if skip_flag 486 : continue 487 : endif 488 : if finished_flag 489 : break 490 : endif 491 : sleep 50m 492 :endwhile 493 494The ":sleep" command makes Vim take a nap. The "50m" specifies fifty 495milliseconds. Another example is ":sleep 4", which sleeps for four seconds. 496 497Even more looping can be done with the ":for" command, see below in |41.8|. 498 499============================================================================== 500*41.5* Executing an expression 501 502So far the commands in the script were executed by Vim directly. The 503":execute" command allows executing the result of an expression. This is a 504very powerful way to build commands and execute them. 505 An example is to jump to a tag, which is contained in a variable: > 506 507 :execute "tag " .. tag_name 508 509The ".." is used to concatenate the string "tag " with the value of variable 510"tag_name". Suppose "tag_name" has the value "get_cmd", then the command that 511will be executed is: > 512 513 :tag get_cmd 514 515The ":execute" command can only execute colon commands. The ":normal" command 516executes Normal mode commands. However, its argument is not an expression but 517the literal command characters. Example: > 518 519 :normal gg=G 520 521This jumps to the first line and formats all lines with the "=" operator. 522 To make ":normal" work with an expression, combine ":execute" with it. 523Example: > 524 525 :execute "normal " .. normal_commands 526 527The variable "normal_commands" must contain the Normal mode commands. 528 Make sure that the argument for ":normal" is a complete command. Otherwise 529Vim will run into the end of the argument and abort the command. For example, 530if you start Insert mode, you must leave Insert mode as well. This works: > 531 532 :execute "normal Inew text \<Esc>" 533 534This inserts "new text " in the current line. Notice the use of the special 535key "\<Esc>". This avoids having to enter a real <Esc> character in your 536script. 537 538If you don't want to execute a string but evaluate it to get its expression 539value, you can use the eval() function: > 540 541 :let optname = "path" 542 :let optval = eval('&' .. optname) 543 544A "&" character is prepended to "path", thus the argument to eval() is 545"&path". The result will then be the value of the 'path' option. 546 The same thing can be done with: > 547 :exe 'let optval = &' .. optname 548 549============================================================================== 550*41.6* Using functions 551 552Vim defines many functions and provides a large amount of functionality that 553way. A few examples will be given in this section. You can find the whole 554list here: |functions|. 555 556A function is called with the ":call" command. The parameters are passed in 557between parentheses separated by commas. Example: > 558 559 :call search("Date: ", "W") 560 561This calls the search() function, with arguments "Date: " and "W". The 562search() function uses its first argument as a search pattern and the second 563one as flags. The "W" flag means the search doesn't wrap around the end of 564the file. 565 566A function can be called in an expression. Example: > 567 568 :let line = getline(".") 569 :let repl = substitute(line, '\a', "*", "g") 570 :call setline(".", repl) 571 572The getline() function obtains a line from the current buffer. Its argument 573is a specification of the line number. In this case "." is used, which means 574the line where the cursor is. 575 The substitute() function does something similar to the ":substitute" 576command. The first argument is the string on which to perform the 577substitution. The second argument is the pattern, the third the replacement 578string. Finally, the last arguments are the flags. 579 The setline() function sets the line, specified by the first argument, to a 580new string, the second argument. In this example the line under the cursor is 581replaced with the result of the substitute(). Thus the effect of the three 582statements is equal to: > 583 584 :substitute/\a/*/g 585 586Using the functions becomes more interesting when you do more work before and 587after the substitute() call. 588 589 590FUNCTIONS *function-list* 591 592There are many functions. We will mention them here, grouped by what they are 593used for. You can find an alphabetical list here: |functions|. Use CTRL-] on 594the function name to jump to detailed help on it. 595 596String manipulation: *string-functions* 597 nr2char() get a character by its number value 598 list2str() get a character string from a list of numbers 599 char2nr() get number value of a character 600 str2list() get list of numbers from a string 601 str2nr() convert a string to a Number 602 str2float() convert a string to a Float 603 printf() format a string according to % items 604 escape() escape characters in a string with a '\' 605 shellescape() escape a string for use with a shell command 606 fnameescape() escape a file name for use with a Vim command 607 tr() translate characters from one set to another 608 strtrans() translate a string to make it printable 609 tolower() turn a string to lowercase 610 toupper() turn a string to uppercase 611 charclass() class of a character 612 match() position where a pattern matches in a string 613 matchend() position where a pattern match ends in a string 614 matchfuzzy() fuzzy matches a string in a list of strings 615 matchfuzzypos() fuzzy matches a string in a list of strings 616 matchstr() match of a pattern in a string 617 matchstrpos() match and positions of a pattern in a string 618 matchlist() like matchstr() and also return submatches 619 stridx() first index of a short string in a long string 620 strridx() last index of a short string in a long string 621 strlen() length of a string in bytes 622 strcharlen() length of a string in characters 623 strchars() number of characters in a string 624 strwidth() size of string when displayed 625 strdisplaywidth() size of string when displayed, deals with tabs 626 setcellwidths() set character cell width overrides 627 substitute() substitute a pattern match with a string 628 submatch() get a specific match in ":s" and substitute() 629 strpart() get part of a string using byte index 630 strcharpart() get part of a string using char index 631 slice() take a slice of a string, using char index in 632 Vim9 script 633 strgetchar() get character from a string using char index 634 expand() expand special keywords 635 expandcmd() expand a command like done for `:edit` 636 iconv() convert text from one encoding to another 637 byteidx() byte index of a character in a string 638 byteidxcomp() like byteidx() but count composing characters 639 charidx() character index of a byte in a string 640 repeat() repeat a string multiple times 641 eval() evaluate a string expression 642 execute() execute an Ex command and get the output 643 win_execute() like execute() but in a specified window 644 trim() trim characters from a string 645 gettext() lookup message translation 646 647List manipulation: *list-functions* 648 get() get an item without error for wrong index 649 len() number of items in a List 650 empty() check if List is empty 651 insert() insert an item somewhere in a List 652 add() append an item to a List 653 extend() append a List to a List 654 extendnew() make a new List and append items 655 remove() remove one or more items from a List 656 copy() make a shallow copy of a List 657 deepcopy() make a full copy of a List 658 filter() remove selected items from a List 659 map() change each List item 660 mapnew() make a new List with changed items 661 reduce() reduce a List to a value 662 slice() take a slice of a List 663 sort() sort a List 664 reverse() reverse the order of a List 665 uniq() remove copies of repeated adjacent items 666 split() split a String into a List 667 join() join List items into a String 668 range() return a List with a sequence of numbers 669 string() String representation of a List 670 call() call a function with List as arguments 671 index() index of a value in a List 672 max() maximum value in a List 673 min() minimum value in a List 674 count() count number of times a value appears in a List 675 repeat() repeat a List multiple times 676 flatten() flatten a List 677 flattennew() flatten a copy of a List 678 679Dictionary manipulation: *dict-functions* 680 get() get an entry without an error for a wrong key 681 len() number of entries in a Dictionary 682 has_key() check whether a key appears in a Dictionary 683 empty() check if Dictionary is empty 684 remove() remove an entry from a Dictionary 685 extend() add entries from one Dictionary to another 686 extendnew() make a new Dictionary and append items 687 filter() remove selected entries from a Dictionary 688 map() change each Dictionary entry 689 mapnew() make a new Dictionary with changed items 690 keys() get List of Dictionary keys 691 values() get List of Dictionary values 692 items() get List of Dictionary key-value pairs 693 copy() make a shallow copy of a Dictionary 694 deepcopy() make a full copy of a Dictionary 695 string() String representation of a Dictionary 696 max() maximum value in a Dictionary 697 min() minimum value in a Dictionary 698 count() count number of times a value appears 699 700Floating point computation: *float-functions* 701 float2nr() convert Float to Number 702 abs() absolute value (also works for Number) 703 round() round off 704 ceil() round up 705 floor() round down 706 trunc() remove value after decimal point 707 fmod() remainder of division 708 exp() exponential 709 log() natural logarithm (logarithm to base e) 710 log10() logarithm to base 10 711 pow() value of x to the exponent y 712 sqrt() square root 713 sin() sine 714 cos() cosine 715 tan() tangent 716 asin() arc sine 717 acos() arc cosine 718 atan() arc tangent 719 atan2() arc tangent 720 sinh() hyperbolic sine 721 cosh() hyperbolic cosine 722 tanh() hyperbolic tangent 723 isinf() check for infinity 724 isnan() check for not a number 725 726Blob manipulation: *blob-functions* 727 blob2list() get a list of numbers from a blob 728 list2blob() get a blob from a list of numbers 729 730Other computation: *bitwise-function* 731 and() bitwise AND 732 invert() bitwise invert 733 or() bitwise OR 734 xor() bitwise XOR 735 sha256() SHA-256 hash 736 rand() get a pseudo-random number 737 srand() initialize seed used by rand() 738 739Variables: *var-functions* 740 type() type of a variable as a number 741 typename() type of a variable as text 742 islocked() check if a variable is locked 743 funcref() get a Funcref for a function reference 744 function() get a Funcref for a function name 745 getbufvar() get a variable value from a specific buffer 746 setbufvar() set a variable in a specific buffer 747 getwinvar() get a variable from specific window 748 gettabvar() get a variable from specific tab page 749 gettabwinvar() get a variable from specific window & tab page 750 setwinvar() set a variable in a specific window 751 settabvar() set a variable in a specific tab page 752 settabwinvar() set a variable in a specific window & tab page 753 garbagecollect() possibly free memory 754 755Cursor and mark position: *cursor-functions* *mark-functions* 756 col() column number of the cursor or a mark 757 virtcol() screen column of the cursor or a mark 758 line() line number of the cursor or mark 759 wincol() window column number of the cursor 760 winline() window line number of the cursor 761 cursor() position the cursor at a line/column 762 screencol() get screen column of the cursor 763 screenrow() get screen row of the cursor 764 screenpos() screen row and col of a text character 765 getcurpos() get position of the cursor 766 getpos() get position of cursor, mark, etc. 767 setpos() set position of cursor, mark, etc. 768 getmarklist() list of global/local marks 769 byte2line() get line number at a specific byte count 770 line2byte() byte count at a specific line 771 diff_filler() get the number of filler lines above a line 772 screenattr() get attribute at a screen line/row 773 screenchar() get character code at a screen line/row 774 screenchars() get character codes at a screen line/row 775 screenstring() get string of characters at a screen line/row 776 charcol() character number of the cursor or a mark 777 getcharpos() get character position of cursor, mark, etc. 778 setcharpos() set character position of cursor, mark, etc. 779 getcursorcharpos() get character position of the cursor 780 setcursorcharpos() set character position of the cursor 781 782Working with text in the current buffer: *text-functions* 783 getline() get a line or list of lines from the buffer 784 setline() replace a line in the buffer 785 append() append line or list of lines in the buffer 786 indent() indent of a specific line 787 cindent() indent according to C indenting 788 lispindent() indent according to Lisp indenting 789 nextnonblank() find next non-blank line 790 prevnonblank() find previous non-blank line 791 search() find a match for a pattern 792 searchpos() find a match for a pattern 793 searchcount() get number of matches before/after the cursor 794 searchpair() find the other end of a start/skip/end 795 searchpairpos() find the other end of a start/skip/end 796 searchdecl() search for the declaration of a name 797 getcharsearch() return character search information 798 setcharsearch() set character search information 799 800Working with text in another buffer: 801 getbufline() get a list of lines from the specified buffer 802 setbufline() replace a line in the specified buffer 803 appendbufline() append a list of lines in the specified buffer 804 deletebufline() delete lines from a specified buffer 805 806 *system-functions* *file-functions* 807System functions and manipulation of files: 808 glob() expand wildcards 809 globpath() expand wildcards in a number of directories 810 glob2regpat() convert a glob pattern into a search pattern 811 findfile() find a file in a list of directories 812 finddir() find a directory in a list of directories 813 resolve() find out where a shortcut points to 814 fnamemodify() modify a file name 815 pathshorten() shorten directory names in a path 816 simplify() simplify a path without changing its meaning 817 executable() check if an executable program exists 818 exepath() full path of an executable program 819 filereadable() check if a file can be read 820 filewritable() check if a file can be written to 821 getfperm() get the permissions of a file 822 setfperm() set the permissions of a file 823 getftype() get the kind of a file 824 isdirectory() check if a directory exists 825 getfsize() get the size of a file 826 getcwd() get the current working directory 827 haslocaldir() check if current window used |:lcd| or |:tcd| 828 tempname() get the name of a temporary file 829 mkdir() create a new directory 830 chdir() change current working directory 831 delete() delete a file 832 rename() rename a file 833 system() get the result of a shell command as a string 834 systemlist() get the result of a shell command as a list 835 environ() get all environment variables 836 getenv() get one environment variable 837 setenv() set an environment variable 838 hostname() name of the system 839 readfile() read a file into a List of lines 840 readblob() read a file into a Blob 841 readdir() get a List of file names in a directory 842 readdirex() get a List of file information in a directory 843 writefile() write a List of lines or Blob into a file 844 845Date and Time: *date-functions* *time-functions* 846 getftime() get last modification time of a file 847 localtime() get current time in seconds 848 strftime() convert time to a string 849 strptime() convert a date/time string to time 850 reltime() get the current or elapsed time accurately 851 reltimestr() convert reltime() result to a string 852 reltimefloat() convert reltime() result to a Float 853 854 *buffer-functions* *window-functions* *arg-functions* 855Buffers, windows and the argument list: 856 argc() number of entries in the argument list 857 argidx() current position in the argument list 858 arglistid() get id of the argument list 859 argv() get one entry from the argument list 860 bufadd() add a file to the list of buffers 861 bufexists() check if a buffer exists 862 buflisted() check if a buffer exists and is listed 863 bufload() ensure a buffer is loaded 864 bufloaded() check if a buffer exists and is loaded 865 bufname() get the name of a specific buffer 866 bufnr() get the buffer number of a specific buffer 867 tabpagebuflist() return List of buffers in a tab page 868 tabpagenr() get the number of a tab page 869 tabpagewinnr() like winnr() for a specified tab page 870 winnr() get the window number for the current window 871 bufwinid() get the window ID of a specific buffer 872 bufwinnr() get the window number of a specific buffer 873 winbufnr() get the buffer number of a specific window 874 listener_add() add a callback to listen to changes 875 listener_flush() invoke listener callbacks 876 listener_remove() remove a listener callback 877 win_findbuf() find windows containing a buffer 878 win_getid() get window ID of a window 879 win_gettype() get type of window 880 win_gotoid() go to window with ID 881 win_id2tabwin() get tab and window nr from window ID 882 win_id2win() get window nr from window ID 883 win_splitmove() move window to a split of another window 884 getbufinfo() get a list with buffer information 885 gettabinfo() get a list with tab page information 886 getwininfo() get a list with window information 887 getchangelist() get a list of change list entries 888 getjumplist() get a list of jump list entries 889 swapinfo() information about a swap file 890 swapname() get the swap file path of a buffer 891 892Command line: *command-line-functions* 893 getcmdline() get the current command line 894 getcmdpos() get position of the cursor in the command line 895 setcmdpos() set position of the cursor in the command line 896 getcmdtype() return the current command-line type 897 getcmdwintype() return the current command-line window type 898 getcompletion() list of command-line completion matches 899 fullcommand() get full command name 900 901Quickfix and location lists: *quickfix-functions* 902 getqflist() list of quickfix errors 903 setqflist() modify a quickfix list 904 getloclist() list of location list items 905 setloclist() modify a location list 906 907Insert mode completion: *completion-functions* 908 complete() set found matches 909 complete_add() add to found matches 910 complete_check() check if completion should be aborted 911 complete_info() get current completion information 912 pumvisible() check if the popup menu is displayed 913 pum_getpos() position and size of popup menu if visible 914 915Folding: *folding-functions* 916 foldclosed() check for a closed fold at a specific line 917 foldclosedend() like foldclosed() but return the last line 918 foldlevel() check for the fold level at a specific line 919 foldtext() generate the line displayed for a closed fold 920 foldtextresult() get the text displayed for a closed fold 921 922Syntax and highlighting: *syntax-functions* *highlighting-functions* 923 clearmatches() clear all matches defined by |matchadd()| and 924 the |:match| commands 925 getmatches() get all matches defined by |matchadd()| and 926 the |:match| commands 927 hlexists() check if a highlight group exists 928 hlget() get highlight group attributes 929 hlset() set highlight group attributes 930 hlID() get ID of a highlight group 931 synID() get syntax ID at a specific position 932 synIDattr() get a specific attribute of a syntax ID 933 synIDtrans() get translated syntax ID 934 synstack() get list of syntax IDs at a specific position 935 synconcealed() get info about concealing 936 diff_hlID() get highlight ID for diff mode at a position 937 matchadd() define a pattern to highlight (a "match") 938 matchaddpos() define a list of positions to highlight 939 matcharg() get info about |:match| arguments 940 matchdelete() delete a match defined by |matchadd()| or a 941 |:match| command 942 setmatches() restore a list of matches saved by 943 |getmatches()| 944 945Spelling: *spell-functions* 946 spellbadword() locate badly spelled word at or after cursor 947 spellsuggest() return suggested spelling corrections 948 soundfold() return the sound-a-like equivalent of a word 949 950History: *history-functions* 951 histadd() add an item to a history 952 histdel() delete an item from a history 953 histget() get an item from a history 954 histnr() get highest index of a history list 955 956Interactive: *interactive-functions* 957 browse() put up a file requester 958 browsedir() put up a directory requester 959 confirm() let the user make a choice 960 getchar() get a character from the user 961 getcharstr() get a character from the user as a string 962 getcharmod() get modifiers for the last typed character 963 getmousepos() get last known mouse position 964 echoraw() output characters as-is 965 feedkeys() put characters in the typeahead queue 966 input() get a line from the user 967 inputlist() let the user pick an entry from a list 968 inputsecret() get a line from the user without showing it 969 inputdialog() get a line from the user in a dialog 970 inputsave() save and clear typeahead 971 inputrestore() restore typeahead 972 973GUI: *gui-functions* 974 getfontname() get name of current font being used 975 getwinpos() position of the Vim window 976 getwinposx() X position of the Vim window 977 getwinposy() Y position of the Vim window 978 balloon_show() set the balloon content 979 balloon_split() split a message for a balloon 980 balloon_gettext() get the text in the balloon 981 982Vim server: *server-functions* 983 serverlist() return the list of server names 984 remote_startserver() run a server 985 remote_send() send command characters to a Vim server 986 remote_expr() evaluate an expression in a Vim server 987 server2client() send a reply to a client of a Vim server 988 remote_peek() check if there is a reply from a Vim server 989 remote_read() read a reply from a Vim server 990 foreground() move the Vim window to the foreground 991 remote_foreground() move the Vim server window to the foreground 992 993Window size and position: *window-size-functions* 994 winheight() get height of a specific window 995 winwidth() get width of a specific window 996 win_screenpos() get screen position of a window 997 winlayout() get layout of windows in a tab page 998 winrestcmd() return command to restore window sizes 999 winsaveview() get view of current window 1000 winrestview() restore saved view of current window 1001 1002Mappings and Menus: *mapping-functions* 1003 digraph_get() get |digraph| 1004 digraph_getlist() get all |digraph|s 1005 digraph_set() register |digraph| 1006 digraph_setlist() register multiple |digraph|s 1007 hasmapto() check if a mapping exists 1008 mapcheck() check if a matching mapping exists 1009 maparg() get rhs of a mapping 1010 mapset() restore a mapping 1011 menu_info() get information about a menu item 1012 wildmenumode() check if the wildmode is active 1013 1014Testing: *test-functions* 1015 assert_equal() assert that two expressions values are equal 1016 assert_equalfile() assert that two file contents are equal 1017 assert_notequal() assert that two expressions values are not equal 1018 assert_inrange() assert that an expression is inside a range 1019 assert_match() assert that a pattern matches the value 1020 assert_notmatch() assert that a pattern does not match the value 1021 assert_false() assert that an expression is false 1022 assert_true() assert that an expression is true 1023 assert_exception() assert that a command throws an exception 1024 assert_beeps() assert that a command beeps 1025 assert_nobeep() assert that a command does not cause a beep 1026 assert_fails() assert that a command fails 1027 assert_report() report a test failure 1028 test_alloc_fail() make memory allocation fail 1029 test_autochdir() enable 'autochdir' during startup 1030 test_override() test with Vim internal overrides 1031 test_garbagecollect_now() free memory right now 1032 test_garbagecollect_soon() set a flag to free memory soon 1033 test_getvalue() get value of an internal variable 1034 test_gui_drop_files() drop file(s) in a window 1035 test_gui_mouse_event() add a GUI mouse event to the input buffer 1036 test_ignore_error() ignore a specific error message 1037 test_null_blob() return a null Blob 1038 test_null_channel() return a null Channel 1039 test_null_dict() return a null Dict 1040 test_null_function() return a null Funcref 1041 test_null_job() return a null Job 1042 test_null_list() return a null List 1043 test_null_partial() return a null Partial function 1044 test_null_string() return a null String 1045 test_settime() set the time Vim uses internally 1046 test_setmouse() set the mouse position 1047 test_feedinput() add key sequence to input buffer 1048 test_option_not_set() reset flag indicating option was set 1049 test_scrollbar() simulate scrollbar movement in the GUI 1050 test_refcount() return an expression's reference count 1051 test_srand_seed() set the seed value for srand() 1052 test_unknown() return a value with unknown type 1053 test_void() return a value with void type 1054 1055Inter-process communication: *channel-functions* 1056 ch_canread() check if there is something to read 1057 ch_open() open a channel 1058 ch_close() close a channel 1059 ch_close_in() close the in part of a channel 1060 ch_read() read a message from a channel 1061 ch_readblob() read a Blob from a channel 1062 ch_readraw() read a raw message from a channel 1063 ch_sendexpr() send a JSON message over a channel 1064 ch_sendraw() send a raw message over a channel 1065 ch_evalexpr() evaluate an expression over channel 1066 ch_evalraw() evaluate a raw string over channel 1067 ch_status() get status of a channel 1068 ch_getbufnr() get the buffer number of a channel 1069 ch_getjob() get the job associated with a channel 1070 ch_info() get channel information 1071 ch_log() write a message in the channel log file 1072 ch_logfile() set the channel log file 1073 ch_setoptions() set the options for a channel 1074 json_encode() encode an expression to a JSON string 1075 json_decode() decode a JSON string to Vim types 1076 js_encode() encode an expression to a JSON string 1077 js_decode() decode a JSON string to Vim types 1078 1079Jobs: *job-functions* 1080 job_start() start a job 1081 job_stop() stop a job 1082 job_status() get the status of a job 1083 job_getchannel() get the channel used by a job 1084 job_info() get information about a job 1085 job_setoptions() set options for a job 1086 1087Signs: *sign-functions* 1088 sign_define() define or update a sign 1089 sign_getdefined() get a list of defined signs 1090 sign_getplaced() get a list of placed signs 1091 sign_jump() jump to a sign 1092 sign_place() place a sign 1093 sign_placelist() place a list of signs 1094 sign_undefine() undefine a sign 1095 sign_unplace() unplace a sign 1096 sign_unplacelist() unplace a list of signs 1097 1098Terminal window: *terminal-functions* 1099 term_start() open a terminal window and run a job 1100 term_list() get the list of terminal buffers 1101 term_sendkeys() send keystrokes to a terminal 1102 term_wait() wait for screen to be updated 1103 term_getjob() get the job associated with a terminal 1104 term_scrape() get row of a terminal screen 1105 term_getline() get a line of text from a terminal 1106 term_getattr() get the value of attribute {what} 1107 term_getcursor() get the cursor position of a terminal 1108 term_getscrolled() get the scroll count of a terminal 1109 term_getaltscreen() get the alternate screen flag 1110 term_getsize() get the size of a terminal 1111 term_getstatus() get the status of a terminal 1112 term_gettitle() get the title of a terminal 1113 term_gettty() get the tty name of a terminal 1114 term_setansicolors() set 16 ANSI colors, used for GUI 1115 term_getansicolors() get 16 ANSI colors, used for GUI 1116 term_dumpdiff() display difference between two screen dumps 1117 term_dumpload() load a terminal screen dump in a window 1118 term_dumpwrite() dump contents of a terminal screen to a file 1119 term_setkill() set signal to stop job in a terminal 1120 term_setrestore() set command to restore a terminal 1121 term_setsize() set the size of a terminal 1122 term_setapi() set terminal JSON API function name prefix 1123 1124Popup window: *popup-window-functions* 1125 popup_create() create popup centered in the screen 1126 popup_atcursor() create popup just above the cursor position, 1127 closes when the cursor moves away 1128 popup_beval() at the position indicated by v:beval_ 1129 variables, closes when the mouse moves away 1130 popup_notification() show a notification for three seconds 1131 popup_dialog() create popup centered with padding and border 1132 popup_menu() prompt for selecting an item from a list 1133 popup_hide() hide a popup temporarily 1134 popup_show() show a previously hidden popup 1135 popup_move() change the position and size of a popup 1136 popup_setoptions() override options of a popup 1137 popup_settext() replace the popup buffer contents 1138 popup_close() close one popup 1139 popup_clear() close all popups 1140 popup_filter_menu() select from a list of items 1141 popup_filter_yesno() block until 'y' or 'n' is pressed 1142 popup_getoptions() get current options for a popup 1143 popup_getpos() get actual position and size of a popup 1144 popup_findinfo() get window ID for popup info window 1145 popup_findpreview() get window ID for popup preview window 1146 popup_list() get list of all popup window IDs 1147 popup_locate() get popup window ID from its screen position 1148 1149Timers: *timer-functions* 1150 timer_start() create a timer 1151 timer_pause() pause or unpause a timer 1152 timer_stop() stop a timer 1153 timer_stopall() stop all timers 1154 timer_info() get information about timers 1155 1156Tags: *tag-functions* 1157 taglist() get list of matching tags 1158 tagfiles() get a list of tags files 1159 gettagstack() get the tag stack of a window 1160 settagstack() modify the tag stack of a window 1161 1162Prompt Buffer: *promptbuffer-functions* 1163 prompt_getprompt() get the effective prompt text for a buffer 1164 prompt_setcallback() set prompt callback for a buffer 1165 prompt_setinterrupt() set interrupt callback for a buffer 1166 prompt_setprompt() set the prompt text for a buffer 1167 1168Text Properties: *text-property-functions* 1169 prop_add() attach a property at a position 1170 prop_add_list() attach a property at multiple positions 1171 prop_clear() remove all properties from a line or lines 1172 prop_find() search for a property 1173 prop_list() return a list of all properties in a line 1174 prop_remove() remove a property from a line 1175 prop_type_add() add/define a property type 1176 prop_type_change() change properties of a type 1177 prop_type_delete() remove a text property type 1178 prop_type_get() return the properties of a type 1179 prop_type_list() return a list of all property types 1180 1181Sound: *sound-functions* 1182 sound_clear() stop playing all sounds 1183 sound_playevent() play an event's sound 1184 sound_playfile() play a sound file 1185 sound_stop() stop playing a sound 1186 1187Various: *various-functions* 1188 mode() get current editing mode 1189 state() get current busy state 1190 visualmode() last visual mode used 1191 exists() check if a variable, function, etc. exists 1192 exists_compiled() like exists() but check at compile time 1193 has() check if a feature is supported in Vim 1194 changenr() return number of most recent change 1195 cscope_connection() check if a cscope connection exists 1196 did_filetype() check if a FileType autocommand was used 1197 eventhandler() check if invoked by an event handler 1198 getpid() get process ID of Vim 1199 getimstatus() check if IME status is active 1200 interrupt() interrupt script execution 1201 windowsversion() get MS-Windows version 1202 terminalprops() properties of the terminal 1203 1204 libcall() call a function in an external library 1205 libcallnr() idem, returning a number 1206 1207 undofile() get the name of the undo file 1208 undotree() return the state of the undo tree 1209 1210 getreg() get contents of a register 1211 getreginfo() get information about a register 1212 getregtype() get type of a register 1213 setreg() set contents and type of a register 1214 reg_executing() return the name of the register being executed 1215 reg_recording() return the name of the register being recorded 1216 1217 shiftwidth() effective value of 'shiftwidth' 1218 1219 wordcount() get byte/word/char count of buffer 1220 1221 luaeval() evaluate |Lua| expression 1222 mzeval() evaluate |MzScheme| expression 1223 perleval() evaluate Perl expression (|+perl|) 1224 py3eval() evaluate Python expression (|+python3|) 1225 pyeval() evaluate Python expression (|+python|) 1226 pyxeval() evaluate |python_x| expression 1227 rubyeval() evaluate |Ruby| expression 1228 1229 debugbreak() interrupt a program being debugged 1230 1231============================================================================== 1232*41.7* Defining a function 1233 1234Vim enables you to define your own functions. The basic function declaration 1235begins as follows: > 1236 1237 :function {name}({var1}, {var2}, ...) 1238 : {body} 1239 :endfunction 1240< 1241 Note: 1242 Function names must begin with a capital letter. 1243 1244Let's define a short function to return the smaller of two numbers. It starts 1245with this line: > 1246 1247 :function Min(num1, num2) 1248 1249This tells Vim that the function is named "Min" and it takes two arguments: 1250"num1" and "num2". 1251 The first thing you need to do is to check to see which number is smaller: 1252 > 1253 : if a:num1 < a:num2 1254 1255The special prefix "a:" tells Vim that the variable is a function argument. 1256Let's assign the variable "smaller" the value of the smallest number: > 1257 1258 : if a:num1 < a:num2 1259 : let smaller = a:num1 1260 : else 1261 : let smaller = a:num2 1262 : endif 1263 1264The variable "smaller" is a local variable. Variables used inside a function 1265are local unless prefixed by something like "g:", "a:", or "s:". 1266 1267 Note: 1268 To access a global variable from inside a function you must prepend 1269 "g:" to it. Thus "g:today" inside a function is used for the global 1270 variable "today", and "today" is another variable, local to the 1271 function. 1272 1273You now use the ":return" statement to return the smallest number to the user. 1274Finally, you end the function: > 1275 1276 : return smaller 1277 :endfunction 1278 1279The complete function definition is as follows: > 1280 1281 :function Min(num1, num2) 1282 : if a:num1 < a:num2 1283 : let smaller = a:num1 1284 : else 1285 : let smaller = a:num2 1286 : endif 1287 : return smaller 1288 :endfunction 1289 1290For people who like short functions, this does the same thing: > 1291 1292 :function Min(num1, num2) 1293 : if a:num1 < a:num2 1294 : return a:num1 1295 : endif 1296 : return a:num2 1297 :endfunction 1298 1299A user defined function is called in exactly the same way as a built-in 1300function. Only the name is different. The Min function can be used like 1301this: > 1302 1303 :echo Min(5, 8) 1304 1305Only now will the function be executed and the lines be interpreted by Vim. 1306If there are mistakes, like using an undefined variable or function, you will 1307now get an error message. When defining the function these errors are not 1308detected. 1309 1310When a function reaches ":endfunction" or ":return" is used without an 1311argument, the function returns zero. 1312 1313To redefine a function that already exists, use the ! for the ":function" 1314command: > 1315 1316 :function! Min(num1, num2, num3) 1317 1318 1319USING A RANGE 1320 1321The ":call" command can be given a line range. This can have one of two 1322meanings. When a function has been defined with the "range" keyword, it will 1323take care of the line range itself. 1324 The function will be passed the variables "a:firstline" and "a:lastline". 1325These will have the line numbers from the range the function was called with. 1326Example: > 1327 1328 :function Count_words() range 1329 : let lnum = a:firstline 1330 : let n = 0 1331 : while lnum <= a:lastline 1332 : let n = n + len(split(getline(lnum))) 1333 : let lnum = lnum + 1 1334 : endwhile 1335 : echo "found " .. n .. " words" 1336 :endfunction 1337 1338You can call this function with: > 1339 1340 :10,30call Count_words() 1341 1342It will be executed once and echo the number of words. 1343 The other way to use a line range is by defining a function without the 1344"range" keyword. The function will be called once for every line in the 1345range, with the cursor in that line. Example: > 1346 1347 :function Number() 1348 : echo "line " .. line(".") .. " contains: " .. getline(".") 1349 :endfunction 1350 1351If you call this function with: > 1352 1353 :10,15call Number() 1354 1355The function will be called six times. 1356 1357 1358VARIABLE NUMBER OF ARGUMENTS 1359 1360Vim enables you to define functions that have a variable number of arguments. 1361The following command, for instance, defines a function that must have 1 1362argument (start) and can have up to 20 additional arguments: > 1363 1364 :function Show(start, ...) 1365 1366The variable "a:1" contains the first optional argument, "a:2" the second, and 1367so on. The variable "a:0" contains the number of extra arguments. 1368 For example: > 1369 1370 :function Show(start, ...) 1371 : echohl Title 1372 : echo "start is " .. a:start 1373 : echohl None 1374 : let index = 1 1375 : while index <= a:0 1376 : echo " Arg " .. index .. " is " .. a:{index} 1377 : let index = index + 1 1378 : endwhile 1379 : echo "" 1380 :endfunction 1381 1382This uses the ":echohl" command to specify the highlighting used for the 1383following ":echo" command. ":echohl None" stops it again. The ":echon" 1384command works like ":echo", but doesn't output a line break. 1385 1386You can also use the a:000 variable, it is a List of all the "..." arguments. 1387See |a:000|. 1388 1389 1390LISTING FUNCTIONS 1391 1392The ":function" command lists the names and arguments of all user-defined 1393functions: > 1394 1395 :function 1396< function Show(start, ...) ~ 1397 function GetVimIndent() ~ 1398 function SetSyn(name) ~ 1399 1400To see what a function does, use its name as an argument for ":function": > 1401 1402 :function SetSyn 1403< 1 if &syntax == '' ~ 1404 2 let &syntax = a:name ~ 1405 3 endif ~ 1406 endfunction ~ 1407 1408 1409DEBUGGING 1410 1411The line number is useful for when you get an error message or when debugging. 1412See |debug-scripts| about debugging mode. 1413 You can also set the 'verbose' option to 12 or higher to see all function 1414calls. Set it to 15 or higher to see every executed line. 1415 1416 1417DELETING A FUNCTION 1418 1419To delete the Show() function: > 1420 1421 :delfunction Show 1422 1423You get an error when the function doesn't exist. 1424 1425 1426FUNCTION REFERENCES 1427 1428Sometimes it can be useful to have a variable point to one function or 1429another. You can do it with the function() function. It turns the name of a 1430function into a reference: > 1431 1432 :let result = 0 " or 1 1433 :function! Right() 1434 : return 'Right!' 1435 :endfunc 1436 :function! Wrong() 1437 : return 'Wrong!' 1438 :endfunc 1439 : 1440 :if result == 1 1441 : let Afunc = function('Right') 1442 :else 1443 : let Afunc = function('Wrong') 1444 :endif 1445 :echo call(Afunc, []) 1446< Wrong! ~ 1447 1448Note that the name of a variable that holds a function reference must start 1449with a capital. Otherwise it could be confused with the name of a builtin 1450function. 1451 The way to invoke a function that a variable refers to is with the call() 1452function. Its first argument is the function reference, the second argument 1453is a List with arguments. 1454 1455Function references are most useful in combination with a Dictionary, as is 1456explained in the next section. 1457 1458More information about defining your own functions here: |user-functions|. 1459 1460============================================================================== 1461*41.8* Lists and Dictionaries 1462 1463So far we have used the basic types String and Number. Vim also supports two 1464composite types: List and Dictionary. 1465 1466A List is an ordered sequence of things. The things can be any kind of value, 1467thus you can make a List of numbers, a List of Lists and even a List of mixed 1468items. To create a List with three strings: > 1469 1470 :let alist = ['aap', 'mies', 'noot'] 1471 1472The List items are enclosed in square brackets and separated by commas. To 1473create an empty List: > 1474 1475 :let alist = [] 1476 1477You can add items to a List with the add() function: > 1478 1479 :let alist = [] 1480 :call add(alist, 'foo') 1481 :call add(alist, 'bar') 1482 :echo alist 1483< ['foo', 'bar'] ~ 1484 1485List concatenation is done with +: > 1486 1487 :echo alist + ['foo', 'bar'] 1488< ['foo', 'bar', 'foo', 'bar'] ~ 1489 1490Or, if you want to extend a List directly: > 1491 1492 :let alist = ['one'] 1493 :call extend(alist, ['two', 'three']) 1494 :echo alist 1495< ['one', 'two', 'three'] ~ 1496 1497Notice that using add() will have a different effect: > 1498 1499 :let alist = ['one'] 1500 :call add(alist, ['two', 'three']) 1501 :echo alist 1502< ['one', ['two', 'three']] ~ 1503 1504The second argument of add() is added as a single item. 1505 1506 1507FOR LOOP 1508 1509One of the nice things you can do with a List is iterate over it: > 1510 1511 :let alist = ['one', 'two', 'three'] 1512 :for n in alist 1513 : echo n 1514 :endfor 1515< one ~ 1516 two ~ 1517 three ~ 1518 1519This will loop over each element in List "alist", assigning the value to 1520variable "n". The generic form of a for loop is: > 1521 1522 :for {varname} in {listexpression} 1523 : {commands} 1524 :endfor 1525 1526To loop a certain number of times you need a List of a specific length. The 1527range() function creates one for you: > 1528 1529 :for a in range(3) 1530 : echo a 1531 :endfor 1532< 0 ~ 1533 1 ~ 1534 2 ~ 1535 1536Notice that the first item of the List that range() produces is zero, thus the 1537last item is one less than the length of the list. 1538 You can also specify the maximum value, the stride and even go backwards: > 1539 1540 :for a in range(8, 4, -2) 1541 : echo a 1542 :endfor 1543< 8 ~ 1544 6 ~ 1545 4 ~ 1546 1547A more useful example, looping over lines in the buffer: > 1548 1549 :for line in getline(1, 20) 1550 : if line =~ "Date: " 1551 : echo matchstr(line, 'Date: \zs.*') 1552 : endif 1553 :endfor 1554 1555This looks into lines 1 to 20 (inclusive) and echoes any date found in there. 1556 1557 1558DICTIONARIES 1559 1560A Dictionary stores key-value pairs. You can quickly lookup a value if you 1561know the key. A Dictionary is created with curly braces: > 1562 1563 :let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'} 1564 1565Now you can lookup words by putting the key in square brackets: > 1566 1567 :echo uk2nl['two'] 1568< twee ~ 1569 1570The generic form for defining a Dictionary is: > 1571 1572 {<key> : <value>, ...} 1573 1574An empty Dictionary is one without any keys: > 1575 1576 {} 1577 1578The possibilities with Dictionaries are numerous. There are various functions 1579for them as well. For example, you can obtain a list of the keys and loop 1580over them: > 1581 1582 :for key in keys(uk2nl) 1583 : echo key 1584 :endfor 1585< three ~ 1586 one ~ 1587 two ~ 1588 1589You will notice the keys are not ordered. You can sort the list to get a 1590specific order: > 1591 1592 :for key in sort(keys(uk2nl)) 1593 : echo key 1594 :endfor 1595< one ~ 1596 three ~ 1597 two ~ 1598 1599But you can never get back the order in which items are defined. For that you 1600need to use a List, it stores items in an ordered sequence. 1601 1602 1603DICTIONARY FUNCTIONS 1604 1605The items in a Dictionary can normally be obtained with an index in square 1606brackets: > 1607 1608 :echo uk2nl['one'] 1609< een ~ 1610 1611A method that does the same, but without so many punctuation characters: > 1612 1613 :echo uk2nl.one 1614< een ~ 1615 1616This only works for a key that is made of ASCII letters, digits and the 1617underscore. You can also assign a new value this way: > 1618 1619 :let uk2nl.four = 'vier' 1620 :echo uk2nl 1621< {'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'} ~ 1622 1623And now for something special: you can directly define a function and store a 1624reference to it in the dictionary: > 1625 1626 :function uk2nl.translate(line) dict 1627 : return join(map(split(a:line), 'get(self, v:val, "???")')) 1628 :endfunction 1629 1630Let's first try it out: > 1631 1632 :echo uk2nl.translate('three two five one') 1633< drie twee ??? een ~ 1634 1635The first special thing you notice is the "dict" at the end of the ":function" 1636line. This marks the function as being used from a Dictionary. The "self" 1637local variable will then refer to that Dictionary. 1638 Now let's break up the complicated return command: > 1639 1640 split(a:line) 1641 1642The split() function takes a string, chops it into whitespace separated words 1643and returns a list with these words. Thus in the example it returns: > 1644 1645 :echo split('three two five one') 1646< ['three', 'two', 'five', 'one'] ~ 1647 1648This list is the first argument to the map() function. This will go through 1649the list, evaluating its second argument with "v:val" set to the value of each 1650item. This is a shortcut to using a for loop. This command: > 1651 1652 :let alist = map(split(a:line), 'get(self, v:val, "???")') 1653 1654Is equivalent to: > 1655 1656 :let alist = split(a:line) 1657 :for idx in range(len(alist)) 1658 : let alist[idx] = get(self, alist[idx], "???") 1659 :endfor 1660 1661The get() function checks if a key is present in a Dictionary. If it is, then 1662the value is retrieved. If it isn't, then the default value is returned, in 1663the example it's '???'. This is a convenient way to handle situations where a 1664key may not be present and you don't want an error message. 1665 1666The join() function does the opposite of split(): it joins together a list of 1667words, putting a space in between. 1668 This combination of split(), map() and join() is a nice way to filter a line 1669of words in a very compact way. 1670 1671 1672OBJECT ORIENTED PROGRAMMING 1673 1674Now that you can put both values and functions in a Dictionary, you can 1675actually use a Dictionary like an object. 1676 Above we used a Dictionary for translating Dutch to English. We might want 1677to do the same for other languages. Let's first make an object (aka 1678Dictionary) that has the translate function, but no words to translate: > 1679 1680 :let transdict = {} 1681 :function transdict.translate(line) dict 1682 : return join(map(split(a:line), 'get(self.words, v:val, "???")')) 1683 :endfunction 1684 1685It's slightly different from the function above, using 'self.words' to lookup 1686word translations. But we don't have a self.words. Thus you could call this 1687an abstract class. 1688 1689Now we can instantiate a Dutch translation object: > 1690 1691 :let uk2nl = copy(transdict) 1692 :let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'} 1693 :echo uk2nl.translate('three one') 1694< drie een ~ 1695 1696And a German translator: > 1697 1698 :let uk2de = copy(transdict) 1699 :let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'} 1700 :echo uk2de.translate('three one') 1701< drei eins ~ 1702 1703You see that the copy() function is used to make a copy of the "transdict" 1704Dictionary and then the copy is changed to add the words. The original 1705remains the same, of course. 1706 1707Now you can go one step further, and use your preferred translator: > 1708 1709 :if $LANG =~ "de" 1710 : let trans = uk2de 1711 :else 1712 : let trans = uk2nl 1713 :endif 1714 :echo trans.translate('one two three') 1715< een twee drie ~ 1716 1717Here "trans" refers to one of the two objects (Dictionaries). No copy is 1718made. More about List and Dictionary identity can be found at |list-identity| 1719and |dict-identity|. 1720 1721Now you might use a language that isn't supported. You can overrule the 1722translate() function to do nothing: > 1723 1724 :let uk2uk = copy(transdict) 1725 :function! uk2uk.translate(line) 1726 : return a:line 1727 :endfunction 1728 :echo uk2uk.translate('three one wladiwostok') 1729< three one wladiwostok ~ 1730 1731Notice that a ! was used to overwrite the existing function reference. Now 1732use "uk2uk" when no recognized language is found: > 1733 1734 :if $LANG =~ "de" 1735 : let trans = uk2de 1736 :elseif $LANG =~ "nl" 1737 : let trans = uk2nl 1738 :else 1739 : let trans = uk2uk 1740 :endif 1741 :echo trans.translate('one two three') 1742< one two three ~ 1743 1744For further reading see |Lists| and |Dictionaries|. 1745 1746============================================================================== 1747*41.9* Exceptions 1748 1749Let's start with an example: > 1750 1751 :try 1752 : read ~/templates/pascal.tmpl 1753 :catch /E484:/ 1754 : echo "Sorry, the Pascal template file cannot be found." 1755 :endtry 1756 1757The ":read" command will fail if the file does not exist. Instead of 1758generating an error message, this code catches the error and gives the user a 1759nice message. 1760 1761For the commands in between ":try" and ":endtry" errors are turned into 1762exceptions. An exception is a string. In the case of an error the string 1763contains the error message. And every error message has a number. In this 1764case, the error we catch contains "E484:". This number is guaranteed to stay 1765the same (the text may change, e.g., it may be translated). 1766 1767When the ":read" command causes another error, the pattern "E484:" will not 1768match in it. Thus this exception will not be caught and result in the usual 1769error message. 1770 1771You might be tempted to do this: > 1772 1773 :try 1774 : read ~/templates/pascal.tmpl 1775 :catch 1776 : echo "Sorry, the Pascal template file cannot be found." 1777 :endtry 1778 1779This means all errors are caught. But then you will not see errors that are 1780useful, such as "E21: Cannot make changes, 'modifiable' is off". 1781 1782Another useful mechanism is the ":finally" command: > 1783 1784 :let tmp = tempname() 1785 :try 1786 : exe ".,$write " .. tmp 1787 : exe "!filter " .. tmp 1788 : .,$delete 1789 : exe "$read " .. tmp 1790 :finally 1791 : call delete(tmp) 1792 :endtry 1793 1794This filters the lines from the cursor until the end of the file through the 1795"filter" command, which takes a file name argument. No matter if the 1796filtering works, something goes wrong in between ":try" and ":finally" or the 1797user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is 1798always executed. This makes sure you don't leave the temporary file behind. 1799 1800More information about exception handling can be found in the reference 1801manual: |exception-handling|. 1802 1803============================================================================== 1804*41.10* Various remarks 1805 1806Here is a summary of items that apply to Vim scripts. They are also mentioned 1807elsewhere, but form a nice checklist. 1808 1809The end-of-line character depends on the system. For Unix a single <NL> 1810character is used. For MS-Windows and the like, <CR><NL> is used. This is 1811important when using mappings that end in a <CR>. See |:source_crnl|. 1812 1813 1814WHITE SPACE 1815 1816Blank lines are allowed and ignored. 1817 1818Leading whitespace characters (blanks and TABs) are always ignored. The 1819whitespaces between parameters (e.g. between the "set" and the "cpoptions" in 1820the example below) are reduced to one blank character and plays the role of a 1821separator, the whitespaces after the last (visible) character may or may not 1822be ignored depending on the situation, see below. 1823 1824For a ":set" command involving the "=" (equal) sign, such as in: > 1825 1826 :set cpoptions =aABceFst 1827 1828the whitespace immediately before the "=" sign is ignored. But there can be 1829no whitespace after the "=" sign! 1830 1831To include a whitespace character in the value of an option, it must be 1832escaped by a "\" (backslash) as in the following example: > 1833 1834 :set tags=my\ nice\ file 1835 1836The same example written as: > 1837 1838 :set tags=my nice file 1839 1840will issue an error, because it is interpreted as: > 1841 1842 :set tags=my 1843 :set nice 1844 :set file 1845 1846 1847COMMENTS 1848 1849The character " (the double quote mark) starts a comment. Everything after 1850and including this character until the end-of-line is considered a comment and 1851is ignored, except for commands that don't consider comments, as shown in 1852examples below. A comment can start on any character position on the line. 1853 1854There is a little "catch" with comments for some commands. Examples: > 1855 1856 :abbrev dev development " shorthand 1857 :map <F3> o#include " insert include 1858 :execute cmd " do it 1859 :!ls *.c " list C files 1860 1861The abbreviation 'dev' will be expanded to 'development " shorthand'. The 1862mapping of <F3> will actually be the whole line after the 'o# ....' including 1863the '" insert include'. The "execute" command will give an error. The "!" 1864command will send everything after it to the shell, causing an error for an 1865unmatched '"' character. 1866 There can be no comment after ":map", ":abbreviate", ":execute" and "!" 1867commands (there are a few more commands with this restriction). For the 1868":map", ":abbreviate" and ":execute" commands there is a trick: > 1869 1870 :abbrev dev development|" shorthand 1871 :map <F3> o#include|" insert include 1872 :execute cmd |" do it 1873 1874With the '|' character the command is separated from the next one. And that 1875next command is only a comment. For the last command you need to do two 1876things: |:execute| and use '|': > 1877 :exe '!ls *.c' |" list C files 1878 1879Notice that there is no white space before the '|' in the abbreviation and 1880mapping. For these commands, any character until the end-of-line or '|' is 1881included. As a consequence of this behavior, you don't always see that 1882trailing whitespace is included: > 1883 1884 :map <F4> o#include 1885 1886To spot these problems, you can set the 'list' option when editing vimrc 1887files. 1888 1889For Unix there is one special way to comment a line, that allows making a Vim 1890script executable: > 1891 #!/usr/bin/env vim -S 1892 echo "this is a Vim script" 1893 quit 1894 1895The "#" command by itself lists a line with the line number. Adding an 1896exclamation mark changes it into doing nothing, so that you can add the shell 1897command to execute the rest of the file. |:#!| |-S| 1898 1899 1900PITFALLS 1901 1902Even bigger problem arises in the following example: > 1903 1904 :map ,ab o#include 1905 :unmap ,ab 1906 1907Here the unmap command will not work, because it tries to unmap ",ab ". This 1908does not exist as a mapped sequence. An error will be issued, which is very 1909hard to identify, because the ending whitespace character in ":unmap ,ab " is 1910not visible. 1911 1912And this is the same as what happens when one uses a comment after an 'unmap' 1913command: > 1914 1915 :unmap ,ab " comment 1916 1917Here the comment part will be ignored. However, Vim will try to unmap 1918',ab ', which does not exist. Rewrite it as: > 1919 1920 :unmap ,ab| " comment 1921 1922 1923RESTORING THE VIEW 1924 1925Sometimes you want to make a change and go back to where the cursor was. 1926Restoring the relative position would also be nice, so that the same line 1927appears at the top of the window. 1928 This example yanks the current line, puts it above the first line in the 1929file and then restores the view: > 1930 1931 map ,p ma"aYHmbgg"aP`bzt`a 1932 1933What this does: > 1934 ma"aYHmbgg"aP`bzt`a 1935< ma set mark a at cursor position 1936 "aY yank current line into register a 1937 Hmb go to top line in window and set mark b there 1938 gg go to first line in file 1939 "aP put the yanked line above it 1940 `b go back to top line in display 1941 zt position the text in the window as before 1942 `a go back to saved cursor position 1943 1944 1945PACKAGING 1946 1947To avoid your function names to interfere with functions that you get from 1948others, use this scheme: 1949- Prepend a unique string before each function name. I often use an 1950 abbreviation. For example, "OW_" is used for the option window functions. 1951- Put the definition of your functions together in a file. Set a global 1952 variable to indicate that the functions have been loaded. When sourcing the 1953 file again, first unload the functions. 1954Example: > 1955 1956 " This is the XXX package 1957 1958 if exists("XXX_loaded") 1959 delfun XXX_one 1960 delfun XXX_two 1961 endif 1962 1963 function XXX_one(a) 1964 ... body of function ... 1965 endfun 1966 1967 function XXX_two(b) 1968 ... body of function ... 1969 endfun 1970 1971 let XXX_loaded = 1 1972 1973============================================================================== 1974*41.11* Writing a plugin *write-plugin* 1975 1976You can write a Vim script in such a way that many people can use it. This is 1977called a plugin. Vim users can drop your script in their plugin directory and 1978use its features right away |add-plugin|. 1979 1980There are actually two types of plugins: 1981 1982 global plugins: For all types of files. 1983filetype plugins: Only for files of a specific type. 1984 1985In this section the first type is explained. Most items are also relevant for 1986writing filetype plugins. The specifics for filetype plugins are in the next 1987section |write-filetype-plugin|. 1988 1989 1990NAME 1991 1992First of all you must choose a name for your plugin. The features provided 1993by the plugin should be clear from its name. And it should be unlikely that 1994someone else writes a plugin with the same name but which does something 1995different. And please limit the name to 8 characters, to avoid problems on 1996old MS-Windows systems. 1997 1998A script that corrects typing mistakes could be called "typecorr.vim". We 1999will use it here as an example. 2000 2001For the plugin to work for everybody, it should follow a few guidelines. This 2002will be explained step-by-step. The complete example plugin is at the end. 2003 2004 2005BODY 2006 2007Let's start with the body of the plugin, the lines that do the actual work: > 2008 2009 14 iabbrev teh the 2010 15 iabbrev otehr other 2011 16 iabbrev wnat want 2012 17 iabbrev synchronisation 2013 18 \ synchronization 2014 19 let s:count = 4 2015 2016The actual list should be much longer, of course. 2017 2018The line numbers have only been added to explain a few things, don't put them 2019in your plugin file! 2020 2021 2022HEADER 2023 2024You will probably add new corrections to the plugin and soon have several 2025versions lying around. And when distributing this file, people will want to 2026know who wrote this wonderful plugin and where they can send remarks. 2027Therefore, put a header at the top of your plugin: > 2028 2029 1 " Vim global plugin for correcting typing mistakes 2030 2 " Last Change: 2000 Oct 15 2031 3 " Maintainer: Bram Moolenaar <[email protected]> 2032 2033About copyright and licensing: Since plugins are very useful and it's hardly 2034worth restricting their distribution, please consider making your plugin 2035either public domain or use the Vim |license|. A short note about this near 2036the top of the plugin should be sufficient. Example: > 2037 2038 4 " License: This file is placed in the public domain. 2039 2040 2041LINE CONTINUATION, AVOIDING SIDE EFFECTS *use-cpo-save* 2042 2043In line 18 above, the line-continuation mechanism is used |line-continuation|. 2044Users with 'compatible' set will run into trouble here, they will get an error 2045message. We can't just reset 'compatible', because that has a lot of side 2046effects. To avoid this, we will set the 'cpoptions' option to its Vim default 2047value and restore it later. That will allow the use of line-continuation and 2048make the script work for most people. It is done like this: > 2049 2050 11 let s:save_cpo = &cpo 2051 12 set cpo&vim 2052 .. 2053 42 let &cpo = s:save_cpo 2054 43 unlet s:save_cpo 2055 2056We first store the old value of 'cpoptions' in the s:save_cpo variable. At 2057the end of the plugin this value is restored. 2058 2059Notice that a script-local variable is used |s:var|. A global variable could 2060already be in use for something else. Always use script-local variables for 2061things that are only used in the script. 2062 2063 2064NOT LOADING 2065 2066It's possible that a user doesn't always want to load this plugin. Or the 2067system administrator has dropped it in the system-wide plugin directory, but a 2068user has his own plugin he wants to use. Then the user must have a chance to 2069disable loading this specific plugin. This will make it possible: > 2070 2071 6 if exists("g:loaded_typecorr") 2072 7 finish 2073 8 endif 2074 9 let g:loaded_typecorr = 1 2075 2076This also avoids that when the script is loaded twice it would cause error 2077messages for redefining functions and cause trouble for autocommands that are 2078added twice. 2079 2080The name is recommended to start with "loaded_" and then the file name of the 2081plugin, literally. The "g:" is prepended just to avoid mistakes when using 2082the variable in a function (without "g:" it would be a variable local to the 2083function). 2084 2085Using "finish" stops Vim from reading the rest of the file, it's much quicker 2086than using if-endif around the whole file. 2087 2088 2089MAPPING 2090 2091Now let's make the plugin more interesting: We will add a mapping that adds a 2092correction for the word under the cursor. We could just pick a key sequence 2093for this mapping, but the user might already use it for something else. To 2094allow the user to define which keys a mapping in a plugin uses, the <Leader> 2095item can be used: > 2096 2097 22 map <unique> <Leader>a <Plug>TypecorrAdd; 2098 2099The "<Plug>TypecorrAdd;" thing will do the work, more about that further on. 2100 2101The user can set the "mapleader" variable to the key sequence that he wants 2102this mapping to start with. Thus if the user has done: > 2103 2104 let mapleader = "_" 2105 2106the mapping will define "_a". If the user didn't do this, the default value 2107will be used, which is a backslash. Then a map for "\a" will be defined. 2108 2109Note that <unique> is used, this will cause an error message if the mapping 2110already happened to exist. |:map-<unique>| 2111 2112But what if the user wants to define his own key sequence? We can allow that 2113with this mechanism: > 2114 2115 21 if !hasmapto('<Plug>TypecorrAdd;') 2116 22 map <unique> <Leader>a <Plug>TypecorrAdd; 2117 23 endif 2118 2119This checks if a mapping to "<Plug>TypecorrAdd;" already exists, and only 2120defines the mapping from "<Leader>a" if it doesn't. The user then has a 2121chance of putting this in his vimrc file: > 2122 2123 map ,c <Plug>TypecorrAdd; 2124 2125Then the mapped key sequence will be ",c" instead of "_a" or "\a". 2126 2127 2128PIECES 2129 2130If a script gets longer, you often want to break up the work in pieces. You 2131can use functions or mappings for this. But you don't want these functions 2132and mappings to interfere with the ones from other scripts. For example, you 2133could define a function Add(), but another script could try to define the same 2134function. To avoid this, we define the function local to the script by 2135prepending it with "s:". 2136 2137We will define a function that adds a new typing correction: > 2138 2139 30 function s:Add(from, correct) 2140 31 let to = input("type the correction for " .. a:from .. ": ") 2141 32 exe ":iabbrev " .. a:from .. " " .. to 2142 .. 2143 36 endfunction 2144 2145Now we can call the function s:Add() from within this script. If another 2146script also defines s:Add(), it will be local to that script and can only 2147be called from the script it was defined in. There can also be a global Add() 2148function (without the "s:"), which is again another function. 2149 2150<SID> can be used with mappings. It generates a script ID, which identifies 2151the current script. In our typing correction plugin we use it like this: > 2152 2153 24 noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add 2154 .. 2155 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR> 2156 2157Thus when a user types "\a", this sequence is invoked: > 2158 2159 \a -> <Plug>TypecorrAdd; -> <SID>Add -> :call <SID>Add() 2160 2161If another script also maps <SID>Add, it will get another script ID and 2162thus define another mapping. 2163 2164Note that instead of s:Add() we use <SID>Add() here. That is because the 2165mapping is typed by the user, thus outside of the script. The <SID> is 2166translated to the script ID, so that Vim knows in which script to look for 2167the Add() function. 2168 2169This is a bit complicated, but it's required for the plugin to work together 2170with other plugins. The basic rule is that you use <SID>Add() in mappings and 2171s:Add() in other places (the script itself, autocommands, user commands). 2172 2173We can also add a menu entry to do the same as the mapping: > 2174 2175 26 noremenu <script> Plugin.Add\ Correction <SID>Add 2176 2177The "Plugin" menu is recommended for adding menu items for plugins. In this 2178case only one item is used. When adding more items, creating a submenu is 2179recommended. For example, "Plugin.CVS" could be used for a plugin that offers 2180CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc. 2181 2182Note that in line 28 ":noremap" is used to avoid that any other mappings cause 2183trouble. Someone may have remapped ":call", for example. In line 24 we also 2184use ":noremap", but we do want "<SID>Add" to be remapped. This is why 2185"<script>" is used here. This only allows mappings which are local to the 2186script. |:map-<script>| The same is done in line 26 for ":noremenu". 2187|:menu-<script>| 2188 2189 2190<SID> AND <Plug> *using-<Plug>* 2191 2192Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere 2193with mappings that are only to be used from other mappings. Note the 2194difference between using <SID> and <Plug>: 2195 2196<Plug> is visible outside of the script. It is used for mappings which the 2197 user might want to map a key sequence to. <Plug> is a special code 2198 that a typed key will never produce. 2199 To make it very unlikely that other plugins use the same sequence of 2200 characters, use this structure: <Plug> scriptname mapname 2201 In our example the scriptname is "Typecorr" and the mapname is "Add". 2202 We add a semicolon as the terminator. This results in 2203 "<Plug>TypecorrAdd;". Only the first character of scriptname and 2204 mapname is uppercase, so that we can see where mapname starts. 2205 2206<SID> is the script ID, a unique identifier for a script. 2207 Internally Vim translates <SID> to "<SNR>123_", where "123" can be any 2208 number. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()" 2209 in one script, and "<SNR>22_Add()" in another. You can see this if 2210 you use the ":function" command to get a list of functions. The 2211 translation of <SID> in mappings is exactly the same, that's how you 2212 can call a script-local function from a mapping. 2213 2214 2215USER COMMAND 2216 2217Now let's add a user command to add a correction: > 2218 2219 38 if !exists(":Correct") 2220 39 command -nargs=1 Correct :call s:Add(<q-args>, 0) 2221 40 endif 2222 2223The user command is defined only if no command with the same name already 2224exists. Otherwise we would get an error here. Overriding the existing user 2225command with ":command!" is not a good idea, this would probably make the user 2226wonder why the command he defined himself doesn't work. |:command| 2227 2228 2229SCRIPT VARIABLES 2230 2231When a variable starts with "s:" it is a script variable. It can only be used 2232inside a script. Outside the script it's not visible. This avoids trouble 2233with using the same variable name in different scripts. The variables will be 2234kept as long as Vim is running. And the same variables are used when sourcing 2235the same script again. |s:var| 2236 2237The fun is that these variables can also be used in functions, autocommands 2238and user commands that are defined in the script. In our example we can add 2239a few lines to count the number of corrections: > 2240 2241 19 let s:count = 4 2242 .. 2243 30 function s:Add(from, correct) 2244 .. 2245 34 let s:count = s:count + 1 2246 35 echo s:count .. " corrections now" 2247 36 endfunction 2248 2249First s:count is initialized to 4 in the script itself. When later the 2250s:Add() function is called, it increments s:count. It doesn't matter from 2251where the function was called, since it has been defined in the script, it 2252will use the local variables from this script. 2253 2254 2255THE RESULT 2256 2257Here is the resulting complete example: > 2258 2259 1 " Vim global plugin for correcting typing mistakes 2260 2 " Last Change: 2000 Oct 15 2261 3 " Maintainer: Bram Moolenaar <[email protected]> 2262 4 " License: This file is placed in the public domain. 2263 5 2264 6 if exists("g:loaded_typecorr") 2265 7 finish 2266 8 endif 2267 9 let g:loaded_typecorr = 1 2268 10 2269 11 let s:save_cpo = &cpo 2270 12 set cpo&vim 2271 13 2272 14 iabbrev teh the 2273 15 iabbrev otehr other 2274 16 iabbrev wnat want 2275 17 iabbrev synchronisation 2276 18 \ synchronization 2277 19 let s:count = 4 2278 20 2279 21 if !hasmapto('<Plug>TypecorrAdd;') 2280 22 map <unique> <Leader>a <Plug>TypecorrAdd; 2281 23 endif 2282 24 noremap <unique> <script> <Plug>TypecorrAdd; <SID>Add 2283 25 2284 26 noremenu <script> Plugin.Add\ Correction <SID>Add 2285 27 2286 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR> 2287 29 2288 30 function s:Add(from, correct) 2289 31 let to = input("type the correction for " .. a:from .. ": ") 2290 32 exe ":iabbrev " .. a:from .. " " .. to 2291 33 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif 2292 34 let s:count = s:count + 1 2293 35 echo s:count .. " corrections now" 2294 36 endfunction 2295 37 2296 38 if !exists(":Correct") 2297 39 command -nargs=1 Correct :call s:Add(<q-args>, 0) 2298 40 endif 2299 41 2300 42 let &cpo = s:save_cpo 2301 43 unlet s:save_cpo 2302 2303Line 33 wasn't explained yet. It applies the new correction to the word under 2304the cursor. The |:normal| command is used to use the new abbreviation. Note 2305that mappings and abbreviations are expanded here, even though the function 2306was called from a mapping defined with ":noremap". 2307 2308Using "unix" for the 'fileformat' option is recommended. The Vim scripts will 2309then work everywhere. Scripts with 'fileformat' set to "dos" do not work on 2310Unix. Also see |:source_crnl|. To be sure it is set right, do this before 2311writing the file: > 2312 2313 :set fileformat=unix 2314 2315 2316DOCUMENTATION *write-local-help* 2317 2318It's a good idea to also write some documentation for your plugin. Especially 2319when its behavior can be changed by the user. See |add-local-help| for how 2320they are installed. 2321 2322Here is a simple example for a plugin help file, called "typecorr.txt": > 2323 2324 1 *typecorr.txt* Plugin for correcting typing mistakes 2325 2 2326 3 If you make typing mistakes, this plugin will have them corrected 2327 4 automatically. 2328 5 2329 6 There are currently only a few corrections. Add your own if you like. 2330 7 2331 8 Mappings: 2332 9 <Leader>a or <Plug>TypecorrAdd; 2333 10 Add a correction for the word under the cursor. 2334 11 2335 12 Commands: 2336 13 :Correct {word} 2337 14 Add a correction for {word}. 2338 15 2339 16 *typecorr-settings* 2340 17 This plugin doesn't have any settings. 2341 2342The first line is actually the only one for which the format matters. It will 2343be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of 2344help.txt |local-additions|. The first "*" must be in the first column of the 2345first line. After adding your help file do ":help" and check that the entries 2346line up nicely. 2347 2348You can add more tags inside ** in your help file. But be careful not to use 2349existing help tags. You would probably use the name of your plugin in most of 2350them, like "typecorr-settings" in the example. 2351 2352Using references to other parts of the help in || is recommended. This makes 2353it easy for the user to find associated help. 2354 2355 2356FILETYPE DETECTION *plugin-filetype* 2357 2358If your filetype is not already detected by Vim, you should create a filetype 2359detection snippet in a separate file. It is usually in the form of an 2360autocommand that sets the filetype when the file name matches a pattern. 2361Example: > 2362 2363 au BufNewFile,BufRead *.foo set filetype=foofoo 2364 2365Write this single-line file as "ftdetect/foofoo.vim" in the first directory 2366that appears in 'runtimepath'. For Unix that would be 2367"~/.vim/ftdetect/foofoo.vim". The convention is to use the name of the 2368filetype for the script name. 2369 2370You can make more complicated checks if you like, for example to inspect the 2371contents of the file to recognize the language. Also see |new-filetype|. 2372 2373 2374SUMMARY *plugin-special* 2375 2376Summary of special things to use in a plugin: 2377 2378s:name Variables local to the script. 2379 2380<SID> Script-ID, used for mappings and functions local to 2381 the script. 2382 2383hasmapto() Function to test if the user already defined a mapping 2384 for functionality the script offers. 2385 2386<Leader> Value of "mapleader", which the user defines as the 2387 keys that plugin mappings start with. 2388 2389:map <unique> Give a warning if a mapping already exists. 2390 2391:noremap <script> Use only mappings local to the script, not global 2392 mappings. 2393 2394exists(":Cmd") Check if a user command already exists. 2395 2396============================================================================== 2397*41.12* Writing a filetype plugin *write-filetype-plugin* *ftplugin* 2398 2399A filetype plugin is like a global plugin, except that it sets options and 2400defines mappings for the current buffer only. See |add-filetype-plugin| for 2401how this type of plugin is used. 2402 2403First read the section on global plugins above |41.11|. All that is said there 2404also applies to filetype plugins. There are a few extras, which are explained 2405here. The essential thing is that a filetype plugin should only have an 2406effect on the current buffer. 2407 2408 2409DISABLING 2410 2411If you are writing a filetype plugin to be used by many people, they need a 2412chance to disable loading it. Put this at the top of the plugin: > 2413 2414 " Only do this when not done yet for this buffer 2415 if exists("b:did_ftplugin") 2416 finish 2417 endif 2418 let b:did_ftplugin = 1 2419 2420This also needs to be used to avoid that the same plugin is executed twice for 2421the same buffer (happens when using an ":edit" command without arguments). 2422 2423Now users can disable loading the default plugin completely by making a 2424filetype plugin with only this line: > 2425 2426 let b:did_ftplugin = 1 2427 2428This does require that the filetype plugin directory comes before $VIMRUNTIME 2429in 'runtimepath'! 2430 2431If you do want to use the default plugin, but overrule one of the settings, 2432you can write the different setting in a script: > 2433 2434 setlocal textwidth=70 2435 2436Now write this in the "after" directory, so that it gets sourced after the 2437distributed "vim.vim" ftplugin |after-directory|. For Unix this would be 2438"~/.vim/after/ftplugin/vim.vim". Note that the default plugin will have set 2439"b:did_ftplugin", but it is ignored here. 2440 2441 2442OPTIONS 2443 2444To make sure the filetype plugin only affects the current buffer use the > 2445 2446 :setlocal 2447 2448command to set options. And only set options which are local to a buffer (see 2449the help for the option to check that). When using |:setlocal| for global 2450options or options local to a window, the value will change for many buffers, 2451and that is not what a filetype plugin should do. 2452 2453When an option has a value that is a list of flags or items, consider using 2454"+=" and "-=" to keep the existing value. Be aware that the user may have 2455changed an option value already. First resetting to the default value and 2456then changing it is often a good idea. Example: > 2457 2458 :setlocal formatoptions& formatoptions+=ro 2459 2460 2461MAPPINGS 2462 2463To make sure mappings will only work in the current buffer use the > 2464 2465 :map <buffer> 2466 2467command. This needs to be combined with the two-step mapping explained above. 2468An example of how to define functionality in a filetype plugin: > 2469 2470 if !hasmapto('<Plug>JavaImport;') 2471 map <buffer> <unique> <LocalLeader>i <Plug>JavaImport; 2472 endif 2473 noremap <buffer> <unique> <Plug>JavaImport; oimport ""<Left><Esc> 2474 2475|hasmapto()| is used to check if the user has already defined a map to 2476<Plug>JavaImport;. If not, then the filetype plugin defines the default 2477mapping. This starts with |<LocalLeader>|, which allows the user to select 2478the key(s) he wants filetype plugin mappings to start with. The default is a 2479backslash. 2480"<unique>" is used to give an error message if the mapping already exists or 2481overlaps with an existing mapping. 2482|:noremap| is used to avoid that any other mappings that the user has defined 2483interferes. You might want to use ":noremap <script>" to allow remapping 2484mappings defined in this script that start with <SID>. 2485 2486The user must have a chance to disable the mappings in a filetype plugin, 2487without disabling everything. Here is an example of how this is done for a 2488plugin for the mail filetype: > 2489 2490 " Add mappings, unless the user didn't want this. 2491 if !exists("no_plugin_maps") && !exists("no_mail_maps") 2492 " Quote text by inserting "> " 2493 if !hasmapto('<Plug>MailQuote;') 2494 vmap <buffer> <LocalLeader>q <Plug>MailQuote; 2495 nmap <buffer> <LocalLeader>q <Plug>MailQuote; 2496 endif 2497 vnoremap <buffer> <Plug>MailQuote; :s/^/> /<CR> 2498 nnoremap <buffer> <Plug>MailQuote; :.,$s/^/> /<CR> 2499 endif 2500 2501Two global variables are used: 2502|no_plugin_maps| disables mappings for all filetype plugins 2503|no_mail_maps| disables mappings for the "mail" filetype 2504 2505 2506USER COMMANDS 2507 2508To add a user command for a specific file type, so that it can only be used in 2509one buffer, use the "-buffer" argument to |:command|. Example: > 2510 2511 :command -buffer Make make %:r.s 2512 2513 2514VARIABLES 2515 2516A filetype plugin will be sourced for each buffer of the type it's for. Local 2517script variables |s:var| will be shared between all invocations. Use local 2518buffer variables |b:var| if you want a variable specifically for one buffer. 2519 2520 2521FUNCTIONS 2522 2523When defining a function, this only needs to be done once. But the filetype 2524plugin will be sourced every time a file with this filetype will be opened. 2525This construct makes sure the function is only defined once: > 2526 2527 :if !exists("*s:Func") 2528 : function s:Func(arg) 2529 : ... 2530 : endfunction 2531 :endif 2532< 2533 2534UNDO *undo_indent* *undo_ftplugin* 2535 2536When the user does ":setfiletype xyz" the effect of the previous filetype 2537should be undone. Set the b:undo_ftplugin variable to the commands that will 2538undo the settings in your filetype plugin. Example: > 2539 2540 let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<" 2541 \ .. "| unlet b:match_ignorecase b:match_words b:match_skip" 2542 2543Using ":setlocal" with "<" after the option name resets the option to its 2544global value. That is mostly the best way to reset the option value. 2545 2546This does require removing the "C" flag from 'cpoptions' to allow line 2547continuation, as mentioned above |use-cpo-save|. 2548 2549For undoing the effect of an indent script, the b:undo_indent variable should 2550be set accordingly. 2551 2552 2553FILE NAME 2554 2555The filetype must be included in the file name |ftplugin-name|. Use one of 2556these three forms: 2557 2558 .../ftplugin/stuff.vim 2559 .../ftplugin/stuff_foo.vim 2560 .../ftplugin/stuff/bar.vim 2561 2562"stuff" is the filetype, "foo" and "bar" are arbitrary names. 2563 2564 2565SUMMARY *ftplugin-special* 2566 2567Summary of special things to use in a filetype plugin: 2568 2569<LocalLeader> Value of "maplocalleader", which the user defines as 2570 the keys that filetype plugin mappings start with. 2571 2572:map <buffer> Define a mapping local to the buffer. 2573 2574:noremap <script> Only remap mappings defined in this script that start 2575 with <SID>. 2576 2577:setlocal Set an option for the current buffer only. 2578 2579:command -buffer Define a user command local to the buffer. 2580 2581exists("*s:Func") Check if a function was already defined. 2582 2583Also see |plugin-special|, the special things used for all plugins. 2584 2585============================================================================== 2586*41.13* Writing a compiler plugin *write-compiler-plugin* 2587 2588A compiler plugin sets options for use with a specific compiler. The user can 2589load it with the |:compiler| command. The main use is to set the 2590'errorformat' and 'makeprg' options. 2591 2592Easiest is to have a look at examples. This command will edit all the default 2593compiler plugins: > 2594 2595 :next $VIMRUNTIME/compiler/*.vim 2596 2597Use |:next| to go to the next plugin file. 2598 2599There are two special items about these files. First is a mechanism to allow 2600a user to overrule or add to the default file. The default files start with: > 2601 2602 :if exists("current_compiler") 2603 : finish 2604 :endif 2605 :let current_compiler = "mine" 2606 2607When you write a compiler file and put it in your personal runtime directory 2608(e.g., ~/.vim/compiler for Unix), you set the "current_compiler" variable to 2609make the default file skip the settings. 2610 *:CompilerSet* 2611The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for 2612":compiler". Vim defines the ":CompilerSet" user command for this. However, 2613older Vim versions don't, thus your plugin should define it then. This is an 2614example: > 2615 2616 if exists(":CompilerSet") != 2 2617 command -nargs=* CompilerSet setlocal <args> 2618 endif 2619 CompilerSet errorformat& " use the default 'errorformat' 2620 CompilerSet makeprg=nmake 2621 2622When you write a compiler plugin for the Vim distribution or for a system-wide 2623runtime directory, use the mechanism mentioned above. When 2624"current_compiler" was already set by a user plugin nothing will be done. 2625 2626When you write a compiler plugin to overrule settings from a default plugin, 2627don't check "current_compiler". This plugin is supposed to be loaded 2628last, thus it should be in a directory at the end of 'runtimepath'. For Unix 2629that could be ~/.vim/after/compiler. 2630 2631============================================================================== 2632*41.14* Writing a plugin that loads quickly *write-plugin-quickload* 2633 2634A plugin may grow and become quite long. The startup delay may become 2635noticeable, while you hardly ever use the plugin. Then it's time for a 2636quickload plugin. 2637 2638The basic idea is that the plugin is loaded twice. The first time user 2639commands and mappings are defined that offer the functionality. The second 2640time the functions that implement the functionality are defined. 2641 2642It may sound surprising that quickload means loading a script twice. What we 2643mean is that it loads quickly the first time, postponing the bulk of the 2644script to the second time, which only happens when you actually use it. When 2645you always use the functionality it actually gets slower! 2646 2647Note that since Vim 7 there is an alternative: use the |autoload| 2648functionality |41.15|. 2649 2650The following example shows how it's done: > 2651 2652 " Vim global plugin for demonstrating quick loading 2653 " Last Change: 2005 Feb 25 2654 " Maintainer: Bram Moolenaar <[email protected]> 2655 " License: This file is placed in the public domain. 2656 2657 if !exists("s:did_load") 2658 command -nargs=* BNRead call BufNetRead(<f-args>) 2659 map <F19> :call BufNetWrite('something')<CR> 2660 2661 let s:did_load = 1 2662 exe 'au FuncUndefined BufNet* source ' .. expand('<sfile>') 2663 finish 2664 endif 2665 2666 function BufNetRead(...) 2667 echo 'BufNetRead(' .. string(a:000) .. ')' 2668 " read functionality here 2669 endfunction 2670 2671 function BufNetWrite(...) 2672 echo 'BufNetWrite(' .. string(a:000) .. ')' 2673 " write functionality here 2674 endfunction 2675 2676When the script is first loaded "s:did_load" is not set. The commands between 2677the "if" and "endif" will be executed. This ends in a |:finish| command, thus 2678the rest of the script is not executed. 2679 2680The second time the script is loaded "s:did_load" exists and the commands 2681after the "endif" are executed. This defines the (possible long) 2682BufNetRead() and BufNetWrite() functions. 2683 2684If you drop this script in your plugin directory Vim will execute it on 2685startup. This is the sequence of events that happens: 2686 26871. The "BNRead" command is defined and the <F19> key is mapped when the script 2688 is sourced at startup. A |FuncUndefined| autocommand is defined. The 2689 ":finish" command causes the script to terminate early. 2690 26912. The user types the BNRead command or presses the <F19> key. The 2692 BufNetRead() or BufNetWrite() function will be called. 2693 26943. Vim can't find the function and triggers the |FuncUndefined| autocommand 2695 event. Since the pattern "BufNet*" matches the invoked function, the 2696 command "source fname" will be executed. "fname" will be equal to the name 2697 of the script, no matter where it is located, because it comes from 2698 expanding "<sfile>" (see |expand()|). 2699 27004. The script is sourced again, the "s:did_load" variable exists and the 2701 functions are defined. 2702 2703Notice that the functions that are loaded afterwards match the pattern in the 2704|FuncUndefined| autocommand. You must make sure that no other plugin defines 2705functions that match this pattern. 2706 2707============================================================================== 2708*41.15* Writing library scripts *write-library-script* 2709 2710Some functionality will be required in several places. When this becomes more 2711than a few lines you will want to put it in one script and use it from many 2712scripts. We will call that one script a library script. 2713 2714Manually loading a library script is possible, so long as you avoid loading it 2715when it's already done. You can do this with the |exists()| function. 2716Example: > 2717 2718 if !exists('*MyLibFunction') 2719 runtime library/mylibscript.vim 2720 endif 2721 call MyLibFunction(arg) 2722 2723Here you need to know that MyLibFunction() is defined in a script 2724"library/mylibscript.vim" in one of the directories in 'runtimepath'. 2725 2726To make this a bit simpler Vim offers the autoload mechanism. Then the 2727example looks like this: > 2728 2729 call mylib#myfunction(arg) 2730 2731That's a lot simpler, isn't it? Vim will recognize the function name and when 2732it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'. 2733That script must define the "mylib#myfunction()" function. 2734 2735You can put many other functions in the mylib.vim script, you are free to 2736organize your functions in library scripts. But you must use function names 2737where the part before the '#' matches the script name. Otherwise Vim would 2738not know what script to load. 2739 2740If you get really enthusiastic and write lots of library scripts, you may 2741want to use subdirectories. Example: > 2742 2743 call netlib#ftp#read('somefile') 2744 2745For Unix the library script used for this could be: 2746 2747 ~/.vim/autoload/netlib/ftp.vim 2748 2749Where the function is defined like this: > 2750 2751 function netlib#ftp#read(fname) 2752 " Read the file fname through ftp 2753 endfunction 2754 2755Notice that the name the function is defined with is exactly the same as the 2756name used for calling the function. And the part before the last '#' 2757exactly matches the subdirectory and script name. 2758 2759You can use the same mechanism for variables: > 2760 2761 let weekdays = dutch#weekdays 2762 2763This will load the script "autoload/dutch.vim", which should contain something 2764like: > 2765 2766 let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag', 2767 \ 'donderdag', 'vrijdag', 'zaterdag'] 2768 2769Further reading: |autoload|. 2770 2771============================================================================== 2772*41.16* Distributing Vim scripts *distribute-script* 2773 2774Vim users will look for scripts on the Vim website: http://www.vim.org. 2775If you made something that is useful for others, share it! 2776 2777Vim scripts can be used on any system. There might not be a tar or gzip 2778command. If you want to pack files together and/or compress them the "zip" 2779utility is recommended. 2780 2781For utmost portability use Vim itself to pack scripts together. This can be 2782done with the Vimball utility. See |vimball|. 2783 2784It's good if you add a line to allow automatic updating. See |glvs-plugins|. 2785 2786============================================================================== 2787 2788Next chapter: |usr_42.txt| Add new menus 2789 2790Copyright: see |manual-copyright| vim:tw=78:ts=8:noet:ft=help:norl: 2791