1*eval.txt* For Vim version 7.0aa. Last change: 2004 Oct 10 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7Expression evaluation *expression* *expr* *E15* *eval* 8 9Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|. 10 11Note: Expression evaluation can be disabled at compile time. If this has been 12done, the features in this document are not available. See |+eval| and the 13last chapter below. 14 151. Variables |variables| 162. Expression syntax |expression-syntax| 173. Internal variable |internal-variables| 184. Builtin Functions |functions| 195. Defining functions |user-functions| 206. Curly braces names |curly-braces-names| 217. Commands |expression-commands| 228. Exception handling |exception-handling| 239. Examples |eval-examples| 2410. No +eval feature |no-eval-feature| 2511. The sandbox |eval-sandbox| 26 27{Vi does not have any of these commands} 28 29============================================================================== 301. Variables *variables* 31 32There are two types of variables: 33 34Number a 32 bit signed number. 35String a NUL terminated string of 8-bit unsigned characters. 36 37These are converted automatically, depending on how they are used. 38 39Conversion from a Number to a String is by making the ASCII representation of 40the Number. Examples: > 41 Number 123 --> String "123" 42 Number 0 --> String "0" 43 Number -1 --> String "-1" 44 45Conversion from a String to a Number is done by converting the first digits 46to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If 47the String doesn't start with digits, the result is zero. Examples: > 48 String "456" --> Number 456 49 String "6bar" --> Number 6 50 String "foo" --> Number 0 51 String "0xf1" --> Number 241 52 String "0100" --> Number 64 53 String "-8" --> Number -8 54 String "+8" --> Number 0 55 56To force conversion from String to Number, add zero to it: > 57 :echo "0100" + 0 58 59For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE. 60 61Note that in the command > 62 :if "foo" 63"foo" is converted to 0, which means FALSE. To test for a non-empty string, 64use strlen(): > 65 :if strlen("foo") 66 67If you need to know the type of a variable or expression, use the |type()| 68function. 69 70When the '!' flag is included in the 'viminfo' option, global variables that 71start with an uppercase letter, and don't contain a lowercase letter, are 72stored in the viminfo file |viminfo-file|. 73 74When the 'sessionoptions' option contains "global", global variables that 75start with an uppercase letter and contain at least one lowercase letter are 76stored in the session file |session-file|. 77 78variable name can be stored where ~ 79my_var_6 not 80My_Var_6 session file 81MY_VAR_6 viminfo file 82 83 84It's possible to form a variable name with curly braces, see 85|curly-braces-names|. 86 87============================================================================== 882. Expression syntax *expression-syntax* 89 90Expression syntax summary, from least to most significant: 91 92|expr1| expr2 ? expr1 : expr1 if-then-else 93 94|expr2| expr3 || expr3 .. logical OR 95 96|expr3| expr4 && expr4 .. logical AND 97 98|expr4| expr5 == expr5 equal 99 expr5 != expr5 not equal 100 expr5 > expr5 greater than 101 expr5 >= expr5 greater than or equal 102 expr5 < expr5 smaller than 103 expr5 <= expr5 smaller than or equal 104 expr5 =~ expr5 regexp matches 105 expr5 !~ expr5 regexp doesn't match 106 107 expr5 ==? expr5 equal, ignoring case 108 expr5 ==# expr5 equal, match case 109 etc. As above, append ? for ignoring case, # for 110 matching case 111 112|expr5| expr6 + expr6 .. number addition 113 expr6 - expr6 .. number subtraction 114 expr6 . expr6 .. string concatenation 115 116|expr6| expr7 * expr7 .. number multiplication 117 expr7 / expr7 .. number division 118 expr7 % expr7 .. number modulo 119 120|expr7| ! expr7 logical NOT 121 - expr7 unary minus 122 + expr7 unary plus 123 expr8 124 125|expr8| expr9[expr1] index in String 126 127|expr9| number number constant 128 "string" string constant, backslash is special 129 'string' string constant 130 &option option value 131 (expr1) nested expression 132 variable internal variable 133 va{ria}ble internal variable with curly braces 134 $VAR environment variable 135 @r contents of register 'r' 136 function(expr1, ...) function call 137 func{ti}on(expr1, ...) function call with curly braces 138 139 140".." indicates that the operations in this level can be concatenated. 141Example: > 142 &nu || &list && &shell == "csh" 143 144All expressions within one level are parsed from left to right. 145 146 147expr1 *expr1* *E109* 148----- 149 150expr2 ? expr1 : expr1 151 152The expression before the '?' is evaluated to a number. If it evaluates to 153non-zero, the result is the value of the expression between the '?' and ':', 154otherwise the result is the value of the expression after the ':'. 155Example: > 156 :echo lnum == 1 ? "top" : lnum 157 158Since the first expression is an "expr2", it cannot contain another ?:. The 159other two expressions can, thus allow for recursive use of ?:. 160Example: > 161 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum 162 163To keep this readable, using |line-continuation| is suggested: > 164 :echo lnum == 1 165 :\ ? "top" 166 :\ : lnum == 1000 167 :\ ? "last" 168 :\ : lnum 169 170 171expr2 and expr3 *expr2* *expr3* 172--------------- 173 174 *expr-barbar* *expr-&&* 175The "||" and "&&" operators take one argument on each side. The arguments 176are (converted to) Numbers. The result is: 177 178 input output ~ 179n1 n2 n1 || n2 n1 && n2 ~ 180zero zero zero zero 181zero non-zero non-zero zero 182non-zero zero non-zero zero 183non-zero non-zero non-zero non-zero 184 185The operators can be concatenated, for example: > 186 187 &nu || &list && &shell == "csh" 188 189Note that "&&" takes precedence over "||", so this has the meaning of: > 190 191 &nu || (&list && &shell == "csh") 192 193Once the result is known, the expression "short-circuits", that is, further 194arguments are not evaluated. This is like what happens in C. For example: > 195 196 let a = 1 197 echo a || b 198 199This is valid even if there is no variable called "b" because "a" is non-zero, 200so the result must be non-zero. Similarly below: > 201 202 echo exists("b") && b == "yes" 203 204This is valid whether "b" has been defined or not. The second clause will 205only be evaluated if "b" has been defined. 206 207 208expr4 *expr4* 209----- 210 211expr5 {cmp} expr5 212 213Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1 214if it evaluates to true. 215 216 *expr-==* *expr-!=* *expr->* *expr->=* 217 *expr-<* *expr-<=* *expr-=~* *expr-!~* 218 *expr-==#* *expr-!=#* *expr->#* *expr->=#* 219 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#* 220 *expr-==?* *expr-!=?* *expr->?* *expr->=?* 221 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?* 222 use 'ignorecase' match case ignore case ~ 223equal == ==# ==? 224not equal != !=# !=? 225greater than > ># >? 226greater than or equal >= >=# >=? 227smaller than < <# <? 228smaller than or equal <= <=# <=? 229regexp matches =~ =~# =~? 230regexp doesn't match !~ !~# !~? 231 232Examples: 233"abc" ==# "Abc" evaluates to 0 234"abc" ==? "Abc" evaluates to 1 235"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise 236 237When comparing a String with a Number, the String is converted to a Number, 238and the comparison is done on Numbers. This means that "0 == 'x'" is TRUE, 239because 'x' converted to a Number is zero. 240 241When comparing two Strings, this is done with strcmp() or stricmp(). This 242results in the mathematical difference (comparing byte values), not 243necessarily the alphabetical difference in the local language. 244 245When using the operators with a trailing '#", or the short version and 246'ignorecase' is off, the comparing is done with strcmp(). 247 248When using the operators with a trailing '?', or the short version and 249'ignorecase' is set, the comparing is done with stricmp(). 250 251The "=~" and "!~" operators match the lefthand argument with the righthand 252argument, which is used as a pattern. See |pattern| for what a pattern is. 253This matching is always done like 'magic' was set and 'cpoptions' is empty, no 254matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts 255portable. To avoid backslashes in the regexp pattern to be doubled, use a 256single-quote string, see |literal-string|. 257Since a string is considered to be a single line, a multi-line pattern 258(containing \n, backslash-n) will not match. However, a literal NL character 259can be matched like an ordinary character. Examples: 260 "foo\nbar" =~ "\n" evaluates to 1 261 "foo\nbar" =~ "\\n" evaluates to 0 262 263 264expr5 and expr6 *expr5* *expr6* 265--------------- 266expr6 + expr6 .. number addition *expr-+* 267expr6 - expr6 .. number subtraction *expr--* 268expr6 . expr6 .. string concatenation *expr-.* 269 270expr7 * expr7 .. number multiplication *expr-star* 271expr7 / expr7 .. number division *expr-/* 272expr7 % expr7 .. number modulo *expr-%* 273 274For all, except ".", Strings are converted to Numbers. 275 276Note the difference between "+" and ".": 277 "123" + "456" = 579 278 "123" . "456" = "123456" 279 280When the righthand side of '/' is zero, the result is 0x7fffffff. 281When the righthand side of '%' is zero, the result is 0. 282 283 284expr7 *expr7* 285----- 286! expr7 logical NOT *expr-!* 287- expr7 unary minus *expr-unary--* 288+ expr7 unary plus *expr-unary-+* 289 290For '!' non-zero becomes zero, zero becomes one. 291For '-' the sign of the number is changed. 292For '+' the number is unchanged. 293 294A String will be converted to a Number first. 295 296These three can be repeated and mixed. Examples: 297 !-1 == 0 298 !!8 == 1 299 --9 == 9 300 301 302expr8 *expr8* 303----- 304expr9[expr1] index in String *expr-[]* *E111* 305 306This results in a String that contains the expr1'th single byte from expr9. 307expr9 is used as a String, expr1 as a Number. Note that this doesn't work for 308multi-byte encodings. 309 310Note that index zero gives the first character. This is like it works in C. 311Careful: text column numbers start with one! Example, to get the character 312under the cursor: > 313 :let c = getline(line("."))[col(".") - 1] 314 315If the length of the String is less than the index, the result is an empty 316String. 317 318 *expr9* 319number 320------ 321number number constant *expr-number* 322 323Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0). 324 325 326string *expr-string* *E114* 327------ 328"string" string constant *expr-quote* 329 330Note that double quotes are used. 331 332A string constant accepts these special characters: 333\... three-digit octal number (e.g., "\316") 334\.. two-digit octal number (must be followed by non-digit) 335\. one-digit octal number (must be followed by non-digit) 336\x.. byte specified with two hex numbers (e.g., "\x1f") 337\x. byte specified with one hex number (must be followed by non-hex char) 338\X.. same as \x.. 339\X. same as \x. 340\u.... character specified with up to 4 hex numbers, stored according to the 341 current value of 'encoding' (e.g., "\u02a4") 342\U.... same as \u.... 343\b backspace <BS> 344\e escape <Esc> 345\f formfeed <FF> 346\n newline <NL> 347\r return <CR> 348\t tab <Tab> 349\\ backslash 350\" double quote 351\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W. 352 353Note that "\000" and "\x00" force the end of the string. 354 355 356literal-string *literal-string* *E115* 357--------------- 358'string' string constant *expr-'* 359 360Note that single quotes are used. 361 362This string is taken as it is. No backslashes are removed or have a special 363meaning. A literal-string cannot contain a single quote. Use a normal, 364double-quoted string for that. 365 366Single quoted strings are useful for patterns, so that backslashes do not need 367to be doubled. These two commands are equivalent: > 368 if a =~ "\\s*" 369 if a =~ '\s*' 370 371 372option *expr-option* *E112* *E113* 373------ 374&option option value, local value if possible 375&g:option global option value 376&l:option local option value 377 378Examples: > 379 echo "tabstop is " . &tabstop 380 if &insertmode 381 382Any option name can be used here. See |options|. When using the local value 383and there is no buffer-local or window-local value, the global value is used 384anyway. 385 386 387register *expr-register* 388-------- 389@r contents of register 'r' 390 391The result is the contents of the named register, as a single string. 392Newlines are inserted where required. To get the contents of the unnamed 393register use @" or @@. The '=' register can not be used here. See 394|registers| for an explanation of the available registers. 395 396 397nesting *expr-nesting* *E110* 398------- 399(expr1) nested expression 400 401 402environment variable *expr-env* 403-------------------- 404$VAR environment variable 405 406The String value of any environment variable. When it is not defined, the 407result is an empty string. 408 *expr-env-expand* 409Note that there is a difference between using $VAR directly and using 410expand("$VAR"). Using it directly will only expand environment variables that 411are known inside the current Vim session. Using expand() will first try using 412the environment variables known inside the current Vim session. If that 413fails, a shell will be used to expand the variable. This can be slow, but it 414does expand all variables that the shell knows about. Example: > 415 :echo $version 416 :echo expand("$version") 417The first one probably doesn't echo anything, the second echoes the $version 418variable (if your shell supports it). 419 420 421internal variable *expr-variable* 422----------------- 423variable internal variable 424See below |internal-variables|. 425 426 427function call *expr-function* *E116* *E117* *E118* *E119* *E120* 428------------- 429function(expr1, ...) function call 430See below |functions|. 431 432 433============================================================================== 4343. Internal variable *internal-variables* *E121* 435 *E461* 436An internal variable name can be made up of letters, digits and '_'. But it 437cannot start with a digit. It's also possible to use curly braces, see 438|curly-braces-names|. 439 440An internal variable is created with the ":let" command |:let|. 441An internal variable is destroyed with the ":unlet" command |:unlet|. 442Using a name that isn't an internal variable, or an internal variable that has 443been destroyed, results in an error. 444 445There are several name spaces for variables. Which one is to be used is 446specified by what is prepended: 447 448 (nothing) In a function: local to a function; otherwise: global 449|buffer-variable| b: Local to the current buffer. 450|window-variable| w: Local to the current window. 451|global-variable| g: Global. 452|local-variable| l: Local to a function. 453|script-variable| s: Local to a |:source|'ed Vim script. 454|function-argument| a: Function argument (only inside a function). 455|vim-variable| v: Global, predefined by Vim. 456 457 *buffer-variable* *b:var* 458A variable name that is preceded with "b:" is local to the current buffer. 459Thus you can have several "b:foo" variables, one for each buffer. 460This kind of variable is deleted when the buffer is wiped out or deleted with 461|:bdelete|. 462 463One local buffer variable is predefined: 464 *b:changedtick-variable* *changetick* 465b:changedtick The total number of changes to the current buffer. It is 466 incremented for each change. An undo command is also a change 467 in this case. This can be used to perform an action only when 468 the buffer has changed. Example: > 469 :if my_changedtick != b:changedtick 470 : let my_changedtick = b:changedtick 471 : call My_Update() 472 :endif 473< 474 *window-variable* *w:var* 475A variable name that is preceded with "w:" is local to the current window. It 476is deleted when the window is closed. 477 478 *global-variable* *g:var* 479Inside functions global variables are accessed with "g:". Omitting this will 480access a variable local to a function. But "g:" can also be used in any other 481place if you like. 482 483 *local-variable* *l:var* 484Inside functions local variables are accessed without prepending anything. 485But you can also prepend "l:" if you like. 486 487 *script-variable* *s:var* 488In a Vim script variables starting with "s:" can be used. They cannot be 489accessed from outside of the scripts, thus are local to the script. 490 491They can be used in: 492- commands executed while the script is sourced 493- functions defined in the script 494- autocommands defined in the script 495- functions and autocommands defined in functions and autocommands which were 496 defined in the script (recursively) 497- user defined commands defined in the script 498Thus not in: 499- other scripts sourced from this one 500- mappings 501- etc. 502 503script variables can be used to avoid conflicts with global variable names. 504Take this example: 505 506 let s:counter = 0 507 function MyCounter() 508 let s:counter = s:counter + 1 509 echo s:counter 510 endfunction 511 command Tick call MyCounter() 512 513You can now invoke "Tick" from any script, and the "s:counter" variable in 514that script will not be changed, only the "s:counter" in the script where 515"Tick" was defined is used. 516 517Another example that does the same: > 518 519 let s:counter = 0 520 command Tick let s:counter = s:counter + 1 | echo s:counter 521 522When calling a function and invoking a user-defined command, the context for 523script variables is set to the script where the function or command was 524defined. 525 526The script variables are also available when a function is defined inside a 527function that is defined in a script. Example: > 528 529 let s:counter = 0 530 function StartCounting(incr) 531 if a:incr 532 function MyCounter() 533 let s:counter = s:counter + 1 534 endfunction 535 else 536 function MyCounter() 537 let s:counter = s:counter - 1 538 endfunction 539 endif 540 endfunction 541 542This defines the MyCounter() function either for counting up or counting down 543when calling StartCounting(). It doesn't matter from where StartCounting() is 544called, the s:counter variable will be accessible in MyCounter(). 545 546When the same script is sourced again it will use the same script variables. 547They will remain valid as long as Vim is running. This can be used to 548maintain a counter: > 549 550 if !exists("s:counter") 551 let s:counter = 1 552 echo "script executed for the first time" 553 else 554 let s:counter = s:counter + 1 555 echo "script executed " . s:counter . " times now" 556 endif 557 558Note that this means that filetype plugins don't get a different set of script 559variables for each buffer. Use local buffer variables instead |b:var|. 560 561 562Predefined Vim variables: *vim-variable* *v:var* 563 564 *v:charconvert_from* *charconvert_from-variable* 565v:charconvert_from 566 The name of the character encoding of a file to be converted. 567 Only valid while evaluating the 'charconvert' option. 568 569 *v:charconvert_to* *charconvert_to-variable* 570v:charconvert_to 571 The name of the character encoding of a file after conversion. 572 Only valid while evaluating the 'charconvert' option. 573 574 *v:cmdarg* *cmdarg-variable* 575v:cmdarg This variable is used for two purposes: 576 1. The extra arguments given to a file read/write command. 577 Currently these are "++enc=" and "++ff=". This variable is 578 set before an autocommand event for a file read/write 579 command is triggered. There is a leading space to make it 580 possible to append this variable directly after the 581 read/write command. Note: The "+cmd" argument isn't 582 included here, because it will be executed anyway. 583 2. When printing a PostScript file with ":hardcopy" this is 584 the argument for the ":hardcopy" command. This can be used 585 in 'printexpr'. 586 587 *v:cmdbang* *cmdbang-variable* 588v:cmdbang Set like v:cmdarg for a file read/write command. When a "!" 589 was used the value is 1, otherwise it is 0. Note that this 590 can only be used in autocommands. For user commands |<bang>| 591 can be used. 592 593 *v:count* *count-variable* 594v:count The count given for the last Normal mode command. Can be used 595 to get the count before a mapping. Read-only. Example: > 596 :map _x :<C-U>echo "the count is " . v:count<CR> 597< Note: The <C-U> is required to remove the line range that you 598 get when typing ':' after a count. 599 "count" also works, for backwards compatibility. 600 601 *v:count1* *count1-variable* 602v:count1 Just like "v:count", but defaults to one when no count is 603 used. 604 605 *v:ctype* *ctype-variable* 606v:ctype The current locale setting for characters of the runtime 607 environment. This allows Vim scripts to be aware of the 608 current locale encoding. Technical: it's the value of 609 LC_CTYPE. When not using a locale the value is "C". 610 This variable can not be set directly, use the |:language| 611 command. 612 See |multi-lang|. 613 614 *v:dying* *dying-variable* 615v:dying Normally zero. When a deadly signal is caught it's set to 616 one. When multiple signals are caught the number increases. 617 Can be used in an autocommand to check if Vim didn't 618 terminate normally. {only works on Unix} 619 Example: > 620 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif 621< 622 *v:errmsg* *errmsg-variable* 623v:errmsg Last given error message. It's allowed to set this variable. 624 Example: > 625 :let v:errmsg = "" 626 :silent! next 627 :if v:errmsg != "" 628 : ... handle error 629< "errmsg" also works, for backwards compatibility. 630 631 *v:exception* *exception-variable* 632v:exception The value of the exception most recently caught and not 633 finished. See also |v:throwpoint| and |throw-variables|. 634 Example: > 635 :try 636 : throw "oops" 637 :catch /.*/ 638 : echo "caught" v:exception 639 :endtry 640< Output: "caught oops". 641 642 *v:fname_in* *fname_in-variable* 643v:fname_in The name of the input file. Only valid while evaluating: 644 option used for ~ 645 'charconvert' file to be converted 646 'diffexpr' original file 647 'patchexpr' original file 648 'printexpr' file to be printed 649 650 *v:fname_out* *fname_out-variable* 651v:fname_out The name of the output file. Only valid while 652 evaluating: 653 option used for ~ 654 'charconvert' resulting converted file (*) 655 'diffexpr' output of diff 656 'patchexpr' resulting patched file 657 (*) When doing conversion for a write command (e.g., ":w 658 file") it will be equal to v:fname_in. When doing conversion 659 for a read command (e.g., ":e file") it will be a temporary 660 file and different from v:fname_in. 661 662 *v:fname_new* *fname_new-variable* 663v:fname_new The name of the new version of the file. Only valid while 664 evaluating 'diffexpr'. 665 666 *v:fname_diff* *fname_diff-variable* 667v:fname_diff The name of the diff (patch) file. Only valid while 668 evaluating 'patchexpr'. 669 670 *v:folddashes* *folddashes-variable* 671v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed 672 fold. 673 Read-only in the |sandbox|. |fold-foldtext| 674 675 *v:foldlevel* *foldlevel-variable* 676v:foldlevel Used for 'foldtext': foldlevel of closed fold. 677 Read-only in the |sandbox|. |fold-foldtext| 678 679 *v:foldend* *foldend-variable* 680v:foldend Used for 'foldtext': last line of closed fold. 681 Read-only in the |sandbox|. |fold-foldtext| 682 683 *v:foldstart* *foldstart-variable* 684v:foldstart Used for 'foldtext': first line of closed fold. 685 Read-only in the |sandbox|. |fold-foldtext| 686 687 *v:insertmode* *insertmode-variable* 688v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand 689 events. Values: 690 i Insert mode 691 r Replace mode 692 v Virtual Replace mode 693 694 *v:lang* *lang-variable* 695v:lang The current locale setting for messages of the runtime 696 environment. This allows Vim scripts to be aware of the 697 current language. Technical: it's the value of LC_MESSAGES. 698 The value is system dependent. 699 This variable can not be set directly, use the |:language| 700 command. 701 It can be different from |v:ctype| when messages are desired 702 in a different language than what is used for character 703 encoding. See |multi-lang|. 704 705 *v:lc_time* *lc_time-variable* 706v:lc_time The current locale setting for time messages of the runtime 707 environment. This allows Vim scripts to be aware of the 708 current language. Technical: it's the value of LC_TIME. 709 This variable can not be set directly, use the |:language| 710 command. See |multi-lang|. 711 712 *v:lnum* *lnum-variable* 713v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr' 714 expressions. Only valid while one of these expressions is 715 being evaluated. Read-only when in the |sandbox|. 716 717 *v:prevcount* *prevcount-variable* 718v:prevcount The count given for the last but one Normal mode command. 719 This is the v:count value of the previous command. Useful if 720 you want to cancel Visual mode and then use the count. > 721 :vmap % <Esc>:call MyFilter(v:prevcount)<CR> 722< Read-only. 723 724 *v:progname* *progname-variable* 725v:progname Contains the name (with path removed) with which Vim was 726 invoked. Allows you to do special initialisations for "view", 727 "evim" etc., or any other name you might symlink to Vim. 728 Read-only. 729 730 *v:register* *register-variable* 731v:register The name of the register supplied to the last normal mode 732 command. Empty if none were supplied. |getreg()| |setreg()| 733 734 *v:servername* *servername-variable* 735v:servername The resulting registered |x11-clientserver| name if any. 736 Read-only. 737 738 *v:shell_error* *shell_error-variable* 739v:shell_error Result of the last shell command. When non-zero, the last 740 shell command had an error. When zero, there was no problem. 741 This only works when the shell returns the error code to Vim. 742 The value -1 is often used when the command could not be 743 executed. Read-only. 744 Example: > 745 :!mv foo bar 746 :if v:shell_error 747 : echo 'could not rename "foo" to "bar"!' 748 :endif 749< "shell_error" also works, for backwards compatibility. 750 751 *v:statusmsg* *statusmsg-variable* 752v:statusmsg Last given status message. It's allowed to set this variable. 753 754 *v:termresponse* *termresponse-variable* 755v:termresponse The escape sequence returned by the terminal for the |t_RV| 756 termcap entry. It is set when Vim receives an escape sequence 757 that starts with ESC [ or CSI and ends in a 'c', with only 758 digits, ';' and '.' in between. 759 When this option is set, the TermResponse autocommand event is 760 fired, so that you can react to the response from the 761 terminal. 762 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp 763 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the 764 patch level (since this was introduced in patch 95, it's 765 always 95 or bigger). Pc is always zero. 766 {only when compiled with |+termresponse| feature} 767 768 *v:this_session* *this_session-variable* 769v:this_session Full filename of the last loaded or saved session file. See 770 |:mksession|. It is allowed to set this variable. When no 771 session file has been saved, this variable is empty. 772 "this_session" also works, for backwards compatibility. 773 774 *v:throwpoint* *throwpoint-variable* 775v:throwpoint The point where the exception most recently caught and not 776 finished was thrown. Not set when commands are typed. See 777 also |v:exception| and |throw-variables|. 778 Example: > 779 :try 780 : throw "oops" 781 :catch /.*/ 782 : echo "Exception from" v:throwpoint 783 :endtry 784< Output: "Exception from test.vim, line 2" 785 786 *v:version* *version-variable* 787v:version Version number of Vim: Major version number times 100 plus 788 minor version number. Version 5.0 is 500. Version 5.1 (5.01) 789 is 501. Read-only. "version" also works, for backwards 790 compatibility. 791 Use |has()| to check if a certain patch was included, e.g.: > 792 if has("patch123") 793< Note that patch numbers are specific to the version, thus both 794 version 5.0 and 5.1 may have a patch 123, but these are 795 completely different. 796 797 *v:warningmsg* *warningmsg-variable* 798v:warningmsg Last given warning message. It's allowed to set this variable. 799 800============================================================================== 8014. Builtin Functions *functions* 802 803See |function-list| for a list grouped by what the function is used for. 804 805(Use CTRL-] on the function name to jump to the full explanation) 806 807USAGE RESULT DESCRIPTION ~ 808 809append( {lnum}, {string}) Number append {string} below line {lnum} 810argc() Number number of files in the argument list 811argidx() Number current index in the argument list 812argv( {nr}) String {nr} entry of the argument list 813browse( {save}, {title}, {initdir}, {default}) 814 String put up a file requester 815browsedir( {title}, {initdir}) String put up a directory requester 816bufexists( {expr}) Number TRUE if buffer {expr} exists 817buflisted( {expr}) Number TRUE if buffer {expr} is listed 818bufloaded( {expr}) Number TRUE if buffer {expr} is loaded 819bufname( {expr}) String Name of the buffer {expr} 820bufnr( {expr}) Number Number of the buffer {expr} 821bufwinnr( {expr}) Number window number of buffer {expr} 822byte2line( {byte}) Number line number at byte count {byte} 823byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr} 824char2nr( {expr}) Number ASCII value of first char in {expr} 825cindent( {lnum}) Number C indent for line {lnum} 826col( {expr}) Number column nr of cursor or mark 827confirm( {msg} [, {choices} [, {default} [, {type}]]]) 828 Number number of choice picked by user 829cscope_connection( [{num} , {dbpath} [, {prepend}]]) 830 Number checks existence of cscope connection 831cursor( {lnum}, {col}) Number position cursor at {lnum}, {col} 832delete( {fname}) Number delete file {fname} 833did_filetype() Number TRUE if FileType autocommand event used 834escape( {string}, {chars}) String escape {chars} in {string} with '\' 835eventhandler( ) Number TRUE if inside an event handler 836executable( {expr}) Number 1 if executable {expr} exists 837exists( {expr}) Number TRUE if {expr} exists 838expand( {expr}) String expand special keywords in {expr} 839filereadable( {file}) Number TRUE if {file} is a readable file 840findfile( {name}[, {path}[, {count}]]) 841 String Find fine {name} in {path} 842filewritable( {file}) Number TRUE if {file} is a writable file 843fnamemodify( {fname}, {mods}) String modify file name 844foldclosed( {lnum}) Number first line of fold at {lnum} if closed 845foldclosedend( {lnum}) Number last line of fold at {lnum} if closed 846foldlevel( {lnum}) Number fold level at {lnum} 847foldtext( ) String line displayed for closed fold 848foreground( ) Number bring the Vim window to the foreground 849getchar( [expr]) Number get one character from the user 850getcharmod( ) Number modifiers for the last typed character 851getbufvar( {expr}, {varname}) variable {varname} in buffer {expr} 852getcmdline() String return the current command-line 853getcmdpos() Number return cursor position in command-line 854getcwd() String the current working directory 855getfperm( {fname}) String file permissions of file {fname} 856getfsize( {fname}) Number size in bytes of file {fname} 857getftime( {fname}) Number last modification time of file 858getftype( {fname}) String description of type of file {fname} 859getline( {lnum}) String line {lnum} from current buffer 860getreg( [{regname}]) String contents of register 861getregtype( [{regname}]) String type of register 862getwinposx() Number X coord in pixels of GUI Vim window 863getwinposy() Number Y coord in pixels of GUI Vim window 864getwinvar( {nr}, {varname}) variable {varname} in window {nr} 865glob( {expr}) String expand file wildcards in {expr} 866globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path} 867has( {feature}) Number TRUE if feature {feature} supported 868hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists 869histadd( {history},{item}) String add an item to a history 870histdel( {history} [, {item}]) String remove an item from a history 871histget( {history} [, {index}]) String get the item {index} from a history 872histnr( {history}) Number highest index of a history 873hlexists( {name}) Number TRUE if highlight group {name} exists 874hlID( {name}) Number syntax ID of highlight group {name} 875hostname() String name of the machine Vim is running on 876iconv( {expr}, {from}, {to}) String convert encoding of {expr} 877indent( {lnum}) Number indent of line {lnum} 878input( {prompt} [, {text}]) String get input from the user 879inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog 880inputrestore() Number restore typeahead 881inputsave() Number save and clear typeahead 882inputsecret( {prompt} [, {text}]) String like input() but hiding the text 883isdirectory( {directory}) Number TRUE if {directory} is a directory 884libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg} 885libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number 886line( {expr}) Number line nr of cursor, last line or mark 887line2byte( {lnum}) Number byte count of line {lnum} 888lispindent( {lnum}) Number Lisp indent for line {lnum} 889localtime() Number current time 890maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode} 891mapcheck( {name}[, {mode}]) String check for mappings matching {name} 892match( {expr}, {pat}[, {start}[, {count}]]) 893 Number position where {pat} matches in {expr} 894matchend( {expr}, {pat}[, {start}[, {count}]]) 895 Number position where {pat} ends in {expr} 896matchstr( {expr}, {pat}[, {start}[, {count}]]) 897 String {count}'th match of {pat} in {expr} 898mode() String current editing mode 899nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum} 900nr2char( {expr}) String single char with ASCII value {expr} 901prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum} 902remote_expr( {server}, {string} [, {idvar}]) 903 String send expression 904remote_foreground( {server}) Number bring Vim server to the foreground 905remote_peek( {serverid} [, {retvar}]) 906 Number check for reply string 907remote_read( {serverid}) String read reply string 908remote_send( {server}, {string} [, {idvar}]) 909 String send key sequence 910rename( {from}, {to}) Number rename (move) file from {from} to {to} 911repeat( {expr}, {count}) String repeat {expr} {count} times 912resolve( {filename}) String get filename a shortcut points to 913search( {pattern} [, {flags}]) Number search for {pattern} 914searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]]) 915 Number search for other end of start/end pair 916server2client( {clientid}, {string}) 917 Number send reply string 918serverlist() String get a list of available servers 919setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val} 920setcmdpos( {pos}) Number set cursor position in command-line 921setline( {lnum}, {line}) Number set line {lnum} to {line} 922setreg( {n}, {v}[, {opt}]) Number set register to value and type 923setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val} 924simplify( {filename}) String simplify filename as much as possible 925strftime( {format}[, {time}]) String time in specified format 926stridx( {haystack}, {needle}) Number first index of {needle} in {haystack} 927strlen( {expr}) Number length of the String {expr} 928strpart( {src}, {start}[, {len}]) 929 String {len} characters of {src} at {start} 930strridx( {haystack}, {needle}) Number last index of {needle} in {haystack} 931strtrans( {expr}) String translate string to make it printable 932submatch( {nr}) String specific match in ":substitute" 933substitute( {expr}, {pat}, {sub}, {flags}) 934 String all {pat} in {expr} replaced with {sub} 935synID( {line}, {col}, {trans}) Number syntax ID at {line} and {col} 936synIDattr( {synID}, {what} [, {mode}]) 937 String attribute {what} of syntax ID {synID} 938synIDtrans( {synID}) Number translated syntax ID of {synID} 939system( {expr} [, {input}]) String output of shell command/filter {expr} 940tempname() String name for a temporary file 941tolower( {expr}) String the String {expr} switched to lowercase 942toupper( {expr}) String the String {expr} switched to uppercase 943tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr} 944 to chars in {tostr} 945type( {name}) Number type of variable {name} 946virtcol( {expr}) Number screen column of cursor or mark 947visualmode( [expr]) String last visual mode used 948winbufnr( {nr}) Number buffer number of window {nr} 949wincol() Number window column of the cursor 950winheight( {nr}) Number height of window {nr} 951winline() Number window line of the cursor 952winnr() Number number of current window 953winrestcmd() String returns command to restore window sizes 954winwidth( {nr}) Number width of window {nr} 955 956append({lnum}, {string}) *append()* 957 Append the text {string} after line {lnum} in the current 958 buffer. {lnum} can be zero, to insert a line before the first 959 one. Returns 1 for failure ({lnum} out of range) or 0 for 960 success. 961 962 *argc()* 963argc() The result is the number of files in the argument list of the 964 current window. See |arglist|. 965 966 *argidx()* 967argidx() The result is the current index in the argument list. 0 is 968 the first file. argc() - 1 is the last one. See |arglist|. 969 970 *argv()* 971argv({nr}) The result is the {nr}th file in the argument list of the 972 current window. See |arglist|. "argv(0)" is the first one. 973 Example: > 974 :let i = 0 975 :while i < argc() 976 : let f = escape(argv(i), '. ') 977 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>' 978 : let i = i + 1 979 :endwhile 980< 981 *browse()* 982browse({save}, {title}, {initdir}, {default}) 983 Put up a file requester. This only works when "has("browse")" 984 returns non-zero (only in some GUI versions). 985 The input fields are: 986 {save} when non-zero, select file to write 987 {title} title for the requester 988 {initdir} directory to start browsing in 989 {default} default file name 990 When the "Cancel" button is hit, something went wrong, or 991 browsing is not possible, an empty string is returned. 992 993 *browsedir()* 994browsedir({title}, {initdir}) 995 Put up a directory requester. This only works when 996 "has("browse")" returns non-zero (only in some GUI versions). 997 On systems where a directory browser is not supported a file 998 browser is used. In that case: select a file in the directory 999 to be used. 1000 The input fields are: 1001 {title} title for the requester 1002 {initdir} directory to start browsing in 1003 When the "Cancel" button is hit, something went wrong, or 1004 browsing is not possible, an empty string is returned. 1005 1006bufexists({expr}) *bufexists()* 1007 The result is a Number, which is non-zero if a buffer called 1008 {expr} exists. 1009 If the {expr} argument is a number, buffer numbers are used. 1010 If the {expr} argument is a string it must match a buffer name 1011 exactly. The name can be: 1012 - Relative to the current directory. 1013 - A full path. 1014 - The name of a buffer with 'filetype' set to "nofile". 1015 - A URL name. 1016 Unlisted buffers will be found. 1017 Note that help files are listed by their short name in the 1018 output of |:buffers|, but bufexists() requires using their 1019 long name to be able to find them. 1020 Use "bufexists(0)" to test for the existence of an alternate 1021 file name. 1022 *buffer_exists()* 1023 Obsolete name: buffer_exists(). 1024 1025buflisted({expr}) *buflisted()* 1026 The result is a Number, which is non-zero if a buffer called 1027 {expr} exists and is listed (has the 'buflisted' option set). 1028 The {expr} argument is used like with |bufexists()|. 1029 1030bufloaded({expr}) *bufloaded()* 1031 The result is a Number, which is non-zero if a buffer called 1032 {expr} exists and is loaded (shown in a window or hidden). 1033 The {expr} argument is used like with |bufexists()|. 1034 1035bufname({expr}) *bufname()* 1036 The result is the name of a buffer, as it is displayed by the 1037 ":ls" command. 1038 If {expr} is a Number, that buffer number's name is given. 1039 Number zero is the alternate buffer for the current window. 1040 If {expr} is a String, it is used as a |file-pattern| to match 1041 with the buffer names. This is always done like 'magic' is 1042 set and 'cpoptions' is empty. When there is more than one 1043 match an empty string is returned. 1044 "" or "%" can be used for the current buffer, "#" for the 1045 alternate buffer. 1046 A full match is preferred, otherwise a match at the start, end 1047 or middle of the buffer name is accepted. 1048 Listed buffers are found first. If there is a single match 1049 with a listed buffer, that one is returned. Next unlisted 1050 buffers are searched for. 1051 If the {expr} is a String, but you want to use it as a buffer 1052 number, force it to be a Number by adding zero to it: > 1053 :echo bufname("3" + 0) 1054< If the buffer doesn't exist, or doesn't have a name, an empty 1055 string is returned. > 1056 bufname("#") alternate buffer name 1057 bufname(3) name of buffer 3 1058 bufname("%") name of current buffer 1059 bufname("file2") name of buffer where "file2" matches. 1060< *buffer_name()* 1061 Obsolete name: buffer_name(). 1062 1063 *bufnr()* 1064bufnr({expr}) The result is the number of a buffer, as it is displayed by 1065 the ":ls" command. For the use of {expr}, see |bufname()| 1066 above. If the buffer doesn't exist, -1 is returned. 1067 bufnr("$") is the last buffer: > 1068 :let last_buffer = bufnr("$") 1069< The result is a Number, which is the highest buffer number 1070 of existing buffers. Note that not all buffers with a smaller 1071 number necessarily exist, because ":bwipeout" may have removed 1072 them. Use bufexists() to test for the existence of a buffer. 1073 *buffer_number()* 1074 Obsolete name: buffer_number(). 1075 *last_buffer_nr()* 1076 Obsolete name for bufnr("$"): last_buffer_nr(). 1077 1078bufwinnr({expr}) *bufwinnr()* 1079 The result is a Number, which is the number of the first 1080 window associated with buffer {expr}. For the use of {expr}, 1081 see |bufname()| above. If buffer {expr} doesn't exist or 1082 there is no such window, -1 is returned. Example: > 1083 1084 echo "A window containing buffer 1 is " . (bufwinnr(1)) 1085 1086< The number can be used with |CTRL-W_w| and ":wincmd w" 1087 |:wincmd|. 1088 1089 1090byte2line({byte}) *byte2line()* 1091 Return the line number that contains the character at byte 1092 count {byte} in the current buffer. This includes the 1093 end-of-line character, depending on the 'fileformat' option 1094 for the current buffer. The first character has byte count 1095 one. 1096 Also see |line2byte()|, |go| and |:goto|. 1097 {not available when compiled without the |+byte_offset| 1098 feature} 1099 1100byteidx({expr}, {nr}) *byteidx()* 1101 Return byte index of the {nr}'th character in the string 1102 {expr}. Use zero for the first character, it returns zero. 1103 This function is only useful when there are multibyte 1104 characters, otherwise the returned value is equal to {nr}. 1105 Composing characters are counted as a separate character. 1106 Example : > 1107 echo matchstr(str, ".", byteidx(str, 3)) 1108< will display the fourth character. Another way to do the 1109 same: > 1110 let s = strpart(str, byteidx(str, 3)) 1111 echo strpart(s, 0, byteidx(s, 1)) 1112< If there are less than {nr} characters -1 is returned. 1113 If there are exactly {nr} characters the length of the string 1114 is returned. 1115 1116char2nr({expr}) *char2nr()* 1117 Return number value of the first char in {expr}. Examples: > 1118 char2nr(" ") returns 32 1119 char2nr("ABC") returns 65 1120< The current 'encoding' is used. Example for "utf-8": > 1121 char2nr("�") returns 225 1122 char2nr("�"[0]) returns 195 1123 1124cindent({lnum}) *cindent()* 1125 Get the amount of indent for line {lnum} according the C 1126 indenting rules, as with 'cindent'. 1127 The indent is counted in spaces, the value of 'tabstop' is 1128 relevant. {lnum} is used just like in |getline()|. 1129 When {lnum} is invalid or Vim was not compiled the |+cindent| 1130 feature, -1 is returned. 1131 1132 *col()* 1133col({expr}) The result is a Number, which is the byte index of the column 1134 position given with {expr}. The accepted positions are: 1135 . the cursor position 1136 $ the end of the cursor line (the result is the 1137 number of characters in the cursor line plus one) 1138 'x position of mark x (if the mark is not set, 0 is 1139 returned) 1140 For the screen column position use |virtcol()|. 1141 Note that only marks in the current file can be used. 1142 Examples: > 1143 col(".") column of cursor 1144 col("$") length of cursor line plus one 1145 col("'t") column of mark t 1146 col("'" . markname) column of mark markname 1147< The first column is 1. 0 is returned for an error. 1148 For the cursor position, when 'virtualedit' is active, the 1149 column is one higher if the cursor is after the end of the 1150 line. This can be used to obtain the column in Insert mode: > 1151 :imap <F2> <C-O>:let save_ve = &ve<CR> 1152 \<C-O>:set ve=all<CR> 1153 \<C-O>:echo col(".") . "\n" <Bar> 1154 \let &ve = save_ve<CR> 1155< 1156 *confirm()* 1157confirm({msg} [, {choices} [, {default} [, {type}]]]) 1158 Confirm() offers the user a dialog, from which a choice can be 1159 made. It returns the number of the choice. For the first 1160 choice this is 1. 1161 Note: confirm() is only supported when compiled with dialog 1162 support, see |+dialog_con| and |+dialog_gui|. 1163 {msg} is displayed in a |dialog| with {choices} as the 1164 alternatives. When {choices} is missing or empty, "&OK" is 1165 used (and translated). 1166 {msg} is a String, use '\n' to include a newline. Only on 1167 some systems the string is wrapped when it doesn't fit. 1168 {choices} is a String, with the individual choices separated 1169 by '\n', e.g. > 1170 confirm("Save changes?", "&Yes\n&No\n&Cancel") 1171< The letter after the '&' is the shortcut key for that choice. 1172 Thus you can type 'c' to select "Cancel". The shortcut does 1173 not need to be the first letter: > 1174 confirm("file has been modified", "&Save\nSave &All") 1175< For the console, the first letter of each choice is used as 1176 the default shortcut key. 1177 The optional {default} argument is the number of the choice 1178 that is made if the user hits <CR>. Use 1 to make the first 1179 choice the default one. Use 0 to not set a default. If 1180 {default} is omitted, 1 is used. 1181 The optional {type} argument gives the type of dialog. This 1182 is only used for the icon of the Win32 GUI. It can be one of 1183 these values: "Error", "Question", "Info", "Warning" or 1184 "Generic". Only the first character is relevant. When {type} 1185 is omitted, "Generic" is used. 1186 If the user aborts the dialog by pressing <Esc>, CTRL-C, 1187 or another valid interrupt key, confirm() returns 0. 1188 1189 An example: > 1190 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2) 1191 :if choice == 0 1192 : echo "make up your mind!" 1193 :elseif choice == 3 1194 : echo "tasteful" 1195 :else 1196 : echo "I prefer bananas myself." 1197 :endif 1198< In a GUI dialog, buttons are used. The layout of the buttons 1199 depends on the 'v' flag in 'guioptions'. If it is included, 1200 the buttons are always put vertically. Otherwise, confirm() 1201 tries to put the buttons in one horizontal line. If they 1202 don't fit, a vertical layout is used anyway. For some systems 1203 the horizontal layout is always used. 1204 1205 *cscope_connection()* 1206cscope_connection([{num} , {dbpath} [, {prepend}]]) 1207 Checks for the existence of a |cscope| connection. If no 1208 parameters are specified, then the function returns: 1209 0, if cscope was not available (not compiled in), or 1210 if there are no cscope connections; 1211 1, if there is at least one cscope connection. 1212 1213 If parameters are specified, then the value of {num} 1214 determines how existence of a cscope connection is checked: 1215 1216 {num} Description of existence check 1217 ----- ------------------------------ 1218 0 Same as no parameters (e.g., "cscope_connection()"). 1219 1 Ignore {prepend}, and use partial string matches for 1220 {dbpath}. 1221 2 Ignore {prepend}, and use exact string matches for 1222 {dbpath}. 1223 3 Use {prepend}, use partial string matches for both 1224 {dbpath} and {prepend}. 1225 4 Use {prepend}, use exact string matches for both 1226 {dbpath} and {prepend}. 1227 1228 Note: All string comparisons are case sensitive! 1229 1230 Examples. Suppose we had the following (from ":cs show"): > 1231 1232 # pid database name prepend path 1233 0 27664 cscope.out /usr/local 1234< 1235 Invocation Return Val ~ 1236 ---------- ---------- > 1237 cscope_connection() 1 1238 cscope_connection(1, "out") 1 1239 cscope_connection(2, "out") 0 1240 cscope_connection(3, "out") 0 1241 cscope_connection(3, "out", "local") 1 1242 cscope_connection(4, "out") 0 1243 cscope_connection(4, "out", "local") 0 1244 cscope_connection(4, "cscope.out", "/usr/local") 1 1245< 1246cursor({lnum}, {col}) *cursor()* 1247 Positions the cursor at the column {col} in the line {lnum}. 1248 Does not change the jumplist. 1249 If {lnum} is greater than the number of lines in the buffer, 1250 the cursor will be positioned at the last line in the buffer. 1251 If {lnum} is zero, the cursor will stay in the current line. 1252 If {col} is greater than the number of characters in the line, 1253 the cursor will be positioned at the last character in the 1254 line. 1255 If {col} is zero, the cursor will stay in the current column. 1256 1257 *delete()* 1258delete({fname}) Deletes the file by the name {fname}. The result is a Number, 1259 which is 0 if the file was deleted successfully, and non-zero 1260 when the deletion failed. 1261 1262 *did_filetype()* 1263did_filetype() Returns non-zero when autocommands are being executed and the 1264 FileType event has been triggered at least once. Can be used 1265 to avoid triggering the FileType event again in the scripts 1266 that detect the file type. |FileType| 1267 When editing another file, the counter is reset, thus this 1268 really checks if the FileType event has been triggered for the 1269 current buffer. This allows an autocommand that starts 1270 editing another buffer to set 'filetype' and load a syntax 1271 file. 1272 1273escape({string}, {chars}) *escape()* 1274 Escape the characters in {chars} that occur in {string} with a 1275 backslash. Example: > 1276 :echo escape('c:\program files\vim', ' \') 1277< results in: > 1278 c:\\program\ files\\vim 1279< 1280eventhandler() *eventhandler()* 1281 Returns 1 when inside an event handler. That is that Vim got 1282 interrupted while waiting for the user to type a character, 1283 e.g., when dropping a file on Vim. This means interactive 1284 commands cannot be used. Otherwise zero is returned. 1285 1286executable({expr}) *executable()* 1287 This function checks if an executable with the name {expr} 1288 exists. {expr} must be the name of the program without any 1289 arguments. 1290 executable() uses the value of $PATH and/or the normal 1291 searchpath for programs. *PATHEXT* 1292 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can 1293 optionally be included. Then the extensions in $PATHEXT are 1294 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be 1295 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is 1296 used. A dot by itself can be used in $PATHEXT to try using 1297 the name without an extension. When 'shell' looks like a 1298 Unix shell, then the name is also tried without adding an 1299 extension. 1300 On MS-DOS and MS-Windows it only checks if the file exists and 1301 is not a directory, not if it's really executable. 1302 The result is a Number: 1303 1 exists 1304 0 does not exist 1305 -1 not implemented on this system 1306 1307 *exists()* 1308exists({expr}) The result is a Number, which is non-zero if {expr} is 1309 defined, zero otherwise. The {expr} argument is a string, 1310 which contains one of these: 1311 &option-name Vim option (only checks if it exists, 1312 not if it really works) 1313 +option-name Vim option that works. 1314 $ENVNAME environment variable (could also be 1315 done by comparing with an empty 1316 string) 1317 *funcname built-in function (see |functions|) 1318 or user defined function (see 1319 |user-functions|). 1320 varname internal variable (see 1321 |internal-variables|). Does not work 1322 for |curly-braces-names|. 1323 :cmdname Ex command: built-in command, user 1324 command or command modifier |:command|. 1325 Returns: 1326 1 for match with start of a command 1327 2 full match with a command 1328 3 matches several user commands 1329 To check for a supported command 1330 always check the return value to be 2. 1331 #event autocommand defined for this event 1332 #event#pattern autocommand defined for this event and 1333 pattern (the pattern is taken 1334 literally and compared to the 1335 autocommand patterns character by 1336 character) 1337 For checking for a supported feature use |has()|. 1338 1339 Examples: > 1340 exists("&shortname") 1341 exists("$HOSTNAME") 1342 exists("*strftime") 1343 exists("*s:MyFunc") 1344 exists("bufcount") 1345 exists(":Make") 1346 exists("#CursorHold"); 1347 exists("#BufReadPre#*.gz") 1348< There must be no space between the symbol (&/$/*/#) and the 1349 name. 1350 Note that the argument must be a string, not the name of the 1351 variable itself! For example: > 1352 exists(bufcount) 1353< This doesn't check for existence of the "bufcount" variable, 1354 but gets the contents of "bufcount", and checks if that 1355 exists. 1356 1357expand({expr} [, {flag}]) *expand()* 1358 Expand wildcards and the following special keywords in {expr}. 1359 The result is a String. 1360 1361 When there are several matches, they are separated by <NL> 1362 characters. [Note: in version 5.0 a space was used, which 1363 caused problems when a file name contains a space] 1364 1365 If the expansion fails, the result is an empty string. A name 1366 for a non-existing file is not included. 1367 1368 When {expr} starts with '%', '#' or '<', the expansion is done 1369 like for the |cmdline-special| variables with their associated 1370 modifiers. Here is a short overview: 1371 1372 % current file name 1373 # alternate file name 1374 #n alternate file name n 1375 <cfile> file name under the cursor 1376 <afile> autocmd file name 1377 <abuf> autocmd buffer number (as a String!) 1378 <amatch> autocmd matched name 1379 <sfile> sourced script file name 1380 <cword> word under the cursor 1381 <cWORD> WORD under the cursor 1382 <client> the {clientid} of the last received 1383 message |server2client()| 1384 Modifiers: 1385 :p expand to full path 1386 :h head (last path component removed) 1387 :t tail (last path component only) 1388 :r root (one extension removed) 1389 :e extension only 1390 1391 Example: > 1392 :let &tags = expand("%:p:h") . "/tags" 1393< Note that when expanding a string that starts with '%', '#' or 1394 '<', any following text is ignored. This does NOT work: > 1395 :let doesntwork = expand("%:h.bak") 1396< Use this: > 1397 :let doeswork = expand("%:h") . ".bak" 1398< Also note that expanding "<cfile>" and others only returns the 1399 referenced file name without further expansion. If "<cfile>" 1400 is "~/.cshrc", you need to do another expand() to have the 1401 "~/" expanded into the path of the home directory: > 1402 :echo expand(expand("<cfile>")) 1403< 1404 There cannot be white space between the variables and the 1405 following modifier. The |fnamemodify()| function can be used 1406 to modify normal file names. 1407 1408 When using '%' or '#', and the current or alternate file name 1409 is not defined, an empty string is used. Using "%:p" in a 1410 buffer with no name, results in the current directory, with a 1411 '/' added. 1412 1413 When {expr} does not start with '%', '#' or '<', it is 1414 expanded like a file name is expanded on the command line. 1415 'suffixes' and 'wildignore' are used, unless the optional 1416 {flag} argument is given and it is non-zero. Names for 1417 non-existing files are included. 1418 1419 Expand() can also be used to expand variables and environment 1420 variables that are only known in a shell. But this can be 1421 slow, because a shell must be started. See |expr-env-expand|. 1422 The expanded variable is still handled like a list of file 1423 names. When an environment variable cannot be expanded, it is 1424 left unchanged. Thus ":echo expand('$FOOBAR')" results in 1425 "$FOOBAR". 1426 1427 See |glob()| for finding existing files. See |system()| for 1428 getting the raw output of an external command. 1429 1430filereadable({file}) *filereadable()* 1431 The result is a Number, which is TRUE when a file with the 1432 name {file} exists, and can be read. If {file} doesn't exist, 1433 or is a directory, the result is FALSE. {file} is any 1434 expression, which is used as a String. 1435 *file_readable()* 1436 Obsolete name: file_readable(). 1437 1438finddir({name}[, {path}[, {count}]]) *finddir()* 1439 Find directory {name} in {path}. 1440 If {path} is omitted or empty then 'path' is used. 1441 If the optional {count} is given, find {count}'s occurrence of 1442 {name} in {path}. 1443 This is quite similar to the ex-command |:find|. 1444 When the found directory is below the current directory a 1445 relative path is returned. Otherwise a full path is returned. 1446 Example: > 1447 :echo findfile("tags.vim", ".;") 1448< Searches from the current directory upwards until it finds 1449 the file "tags.vim". 1450 {only available when compiled with the +file_in_path feature} 1451 1452findfile({name}[, {path}[, {count}]]) *findfile()* 1453 Just like |finddir()|, but find a file instead of a directory. 1454 1455filewritable({file}) *filewritable()* 1456 The result is a Number, which is 1 when a file with the 1457 name {file} exists, and can be written. If {file} doesn't 1458 exist, or is not writable, the result is 0. If (file) is a 1459 directory, and we can write to it, the result is 2. 1460 1461fnamemodify({fname}, {mods}) *fnamemodify()* 1462 Modify file name {fname} according to {mods}. {mods} is a 1463 string of characters like it is used for file names on the 1464 command line. See |filename-modifiers|. 1465 Example: > 1466 :echo fnamemodify("main.c", ":p:h") 1467< results in: > 1468 /home/mool/vim/vim/src 1469< Note: Environment variables and "~" don't work in {fname}, use 1470 |expand()| first then. 1471 1472foldclosed({lnum}) *foldclosed()* 1473 The result is a Number. If the line {lnum} is in a closed 1474 fold, the result is the number of the first line in that fold. 1475 If the line {lnum} is not in a closed fold, -1 is returned. 1476 1477foldclosedend({lnum}) *foldclosedend()* 1478 The result is a Number. If the line {lnum} is in a closed 1479 fold, the result is the number of the last line in that fold. 1480 If the line {lnum} is not in a closed fold, -1 is returned. 1481 1482foldlevel({lnum}) *foldlevel()* 1483 The result is a Number, which is the foldlevel of line {lnum} 1484 in the current buffer. For nested folds the deepest level is 1485 returned. If there is no fold at line {lnum}, zero is 1486 returned. It doesn't matter if the folds are open or closed. 1487 When used while updating folds (from 'foldexpr') -1 is 1488 returned for lines where folds are still to be updated and the 1489 foldlevel is unknown. As a special case the level of the 1490 previous line is usually available. 1491 1492 *foldtext()* 1493foldtext() Returns a String, to be displayed for a closed fold. This is 1494 the default function used for the 'foldtext' option and should 1495 only be called from evaluating 'foldtext'. It uses the 1496 |v:foldstart|, |v:foldend| and |v:folddashes| variables. 1497 The returned string looks like this: > 1498 +-- 45 lines: abcdef 1499< The number of dashes depends on the foldlevel. The "45" is 1500 the number of lines in the fold. "abcdef" is the text in the 1501 first non-blank line of the fold. Leading white space, "//" 1502 or "/*" and the text from the 'foldmarker' and 'commentstring' 1503 options is removed. 1504 {not available when compiled without the |+folding| feature} 1505 1506foldtextresult({lnum}) *foldtextresult()* 1507 Returns the text that is displayed for the closed fold at line 1508 {lnum}. Evaluates 'foldtext' in the appropriate context. 1509 When there is no closed fold at {lnum} an empty string is 1510 returned. 1511 {lnum} is used like with |getline()|. Thus "." is the current 1512 line, "'m" mark m, etc. 1513 Useful when exporting folded text, e.g., to HTML. 1514 {not available when compiled without the |+folding| feature} 1515 1516 *foreground()* 1517foreground() Move the Vim window to the foreground. Useful when sent from 1518 a client to a Vim server. |remote_send()| 1519 On Win32 systems this might not work, the OS does not always 1520 allow a window to bring itself to the foreground. Use 1521 |remote_foreground()| instead. 1522 {only in the Win32, Athena, Motif and GTK GUI versions and the 1523 Win32 console version} 1524 1525getchar([expr]) *getchar()* 1526 Get a single character from the user. If it is an 8-bit 1527 character, the result is a number. Otherwise a String is 1528 returned with the encoded character. For a special key it's a 1529 sequence of bytes starting with 0x80 (decimal: 128). 1530 If [expr] is omitted, wait until a character is available. 1531 If [expr] is 0, only get a character when one is available. 1532 If [expr] is 1, only check if a character is available, it is 1533 not consumed. If a normal character is 1534 available, it is returned, otherwise a 1535 non-zero value is returned. 1536 If a normal character available, it is returned as a Number. 1537 Use nr2char() to convert it to a String. 1538 The returned value is zero if no character is available. 1539 The returned value is a string of characters for special keys 1540 and when a modifier (shift, control, alt) was used. 1541 There is no prompt, you will somehow have to make clear to the 1542 user that a character has to be typed. 1543 There is no mapping for the character. 1544 Key codes are replaced, thus when the user presses the <Del> 1545 key you get the code for the <Del> key, not the raw character 1546 sequence. Examples: > 1547 getchar() == "\<Del>" 1548 getchar() == "\<S-Left>" 1549< This example redefines "f" to ignore case: > 1550 :nmap f :call FindChar()<CR> 1551 :function FindChar() 1552 : let c = nr2char(getchar()) 1553 : while col('.') < col('$') - 1 1554 : normal l 1555 : if getline('.')[col('.') - 1] ==? c 1556 : break 1557 : endif 1558 : endwhile 1559 :endfunction 1560 1561getcharmod() *getcharmod()* 1562 The result is a Number which is the state of the modifiers for 1563 the last obtained character with getchar() or in another way. 1564 These values are added together: 1565 2 shift 1566 4 control 1567 8 alt (meta) 1568 16 mouse double click 1569 32 mouse triple click 1570 64 mouse quadruple click 1571 128 Macintosh only: command 1572 Only the modifiers that have not been included in the 1573 character itself are obtained. Thus Shift-a results in "A" 1574 with no modifier. 1575 1576getbufvar({expr}, {varname}) *getbufvar()* 1577 The result is the value of option or local buffer variable 1578 {varname} in buffer {expr}. Note that the name without "b:" 1579 must be used. 1580 This also works for a global or local window option, but it 1581 doesn't work for a global or local window variable. 1582 For the use of {expr}, see |bufname()| above. 1583 When the buffer or variable doesn't exist an empty string is 1584 returned, there is no error message. 1585 Examples: > 1586 :let bufmodified = getbufvar(1, "&mod") 1587 :echo "todo myvar = " . getbufvar("todo", "myvar") 1588< 1589getcmdline() *getcmdline()* 1590 Return the current command-line. Only works when the command 1591 line is being edited, thus requires use of |c_CTRL-\_e| or 1592 |c_CTRL-R_=|. 1593 Example: > 1594 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR> 1595< Also see |getcmdpos()| and |setcmdpos()|. 1596 1597getcmdpos({pos}) *getcmdpos()* 1598 Return the position of the cursor in the command line as a 1599 byte count. The first column is 1. 1600 Only works when editing the command line, thus requires use of 1601 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise. 1602 Also see |setcmdpos()| and |getcmdline()|. 1603 1604 *getcwd()* 1605getcwd() The result is a String, which is the name of the current 1606 working directory. 1607 1608getfsize({fname}) *getfsize()* 1609 The result is a Number, which is the size in bytes of the 1610 given file {fname}. 1611 If {fname} is a directory, 0 is returned. 1612 If the file {fname} can't be found, -1 is returned. 1613 1614getfperm({fname}) *getfperm()* 1615 The result is a String, which is the read, write, and execute 1616 permissions of the given file {fname}. 1617 If {fname} does not exist or its directory cannot be read, an 1618 empty string is returned. 1619 The result is of the form "rwxrwxrwx", where each group of 1620 "rwx" flags represent, in turn, the permissions of the owner 1621 of the file, the group the file belongs to, and other users. 1622 If a user does not have a given permission the flag for this 1623 is replaced with the string "-". Example: > 1624 :echo getfperm("/etc/passwd") 1625< This will hopefully (from a security point of view) display 1626 the string "rw-r--r--" or even "rw-------". 1627 1628getftime({fname}) *getftime()* 1629 The result is a Number, which is the last modification time of 1630 the given file {fname}. The value is measured as seconds 1631 since 1st Jan 1970, and may be passed to strftime(). See also 1632 |localtime()| and |strftime()|. 1633 If the file {fname} can't be found -1 is returned. 1634 1635getftype({fname}) *getftype()* 1636 The result is a String, which is a description of the kind of 1637 file of the given file {fname}. 1638 If {fname} does not exist an empty string is returned. 1639 Here is a table over different kinds of files and their 1640 results: 1641 Normal file "file" 1642 Directory "dir" 1643 Symbolic link "link" 1644 Block device "bdev" 1645 Character device "cdev" 1646 Socket "socket" 1647 FIFO "fifo" 1648 All other "other" 1649 Example: > 1650 getftype("/home") 1651< Note that a type such as "link" will only be returned on 1652 systems that support it. On some systems only "dir" and 1653 "file" are returned. 1654 1655 *getline()* 1656getline({lnum}) The result is a String, which is line {lnum} from the current 1657 buffer. Example: > 1658 getline(1) 1659< When {lnum} is a String that doesn't start with a 1660 digit, line() is called to translate the String into a Number. 1661 To get the line under the cursor: > 1662 getline(".") 1663< When {lnum} is smaller than 1 or bigger than the number of 1664 lines in the buffer, an empty string is returned. 1665 1666getreg([{regname}]) *getreg()* 1667 The result is a String, which is the contents of register 1668 {regname}. Example: > 1669 :let cliptext = getreg('*') 1670< getreg('=') returns the last evaluated value of the expression 1671 register. (For use in maps). 1672 If {regname} is not specified, |v:register| is used. 1673 1674getregtype([{regname}]) *getregtype()* 1675 The result is a String, which is type of register {regname}. 1676 The value will be one of: 1677 "v" for |characterwise| text 1678 "V" for |linewise| text 1679 "<CTRL-V>{width}" for |blockwise-visual| text 1680 0 for an empty or unknown register 1681 <CTRL-V> is one character with value 0x16. 1682 If {regname} is not specified, |v:register| is used. 1683 1684 *getwinposx()* 1685getwinposx() The result is a Number, which is the X coordinate in pixels of 1686 the left hand side of the GUI Vim window. The result will be 1687 -1 if the information is not available. 1688 1689 *getwinposy()* 1690getwinposy() The result is a Number, which is the Y coordinate in pixels of 1691 the top of the GUI Vim window. The result will be -1 if the 1692 information is not available. 1693 1694getwinvar({nr}, {varname}) *getwinvar()* 1695 The result is the value of option or local window variable 1696 {varname} in window {nr}. 1697 This also works for a global or local buffer option, but it 1698 doesn't work for a global or local buffer variable. 1699 Note that the name without "w:" must be used. 1700 Examples: > 1701 :let list_is_on = getwinvar(2, '&list') 1702 :echo "myvar = " . getwinvar(1, 'myvar') 1703< 1704 *glob()* 1705glob({expr}) Expand the file wildcards in {expr}. The result is a String. 1706 When there are several matches, they are separated by <NL> 1707 characters. 1708 If the expansion fails, the result is an empty string. 1709 A name for a non-existing file is not included. 1710 1711 For most systems backticks can be used to get files names from 1712 any external command. Example: > 1713 :let tagfiles = glob("`find . -name tags -print`") 1714 :let &tags = substitute(tagfiles, "\n", ",", "g") 1715< The result of the program inside the backticks should be one 1716 item per line. Spaces inside an item are allowed. 1717 1718 See |expand()| for expanding special Vim variables. See 1719 |system()| for getting the raw output of an external command. 1720 1721globpath({path}, {expr}) *globpath()* 1722 Perform glob() on all directories in {path} and concatenate 1723 the results. Example: > 1724 :echo globpath(&rtp, "syntax/c.vim") 1725< {path} is a comma-separated list of directory names. Each 1726 directory name is prepended to {expr} and expanded like with 1727 glob(). A path separator is inserted when needed. 1728 To add a comma inside a directory name escape it with a 1729 backslash. Note that on MS-Windows a directory may have a 1730 trailing backslash, remove it if you put a comma after it. 1731 If the expansion fails for one of the directories, there is no 1732 error message. 1733 The 'wildignore' option applies: Names matching one of the 1734 patterns in 'wildignore' will be skipped. 1735 1736 *has()* 1737has({feature}) The result is a Number, which is 1 if the feature {feature} is 1738 supported, zero otherwise. The {feature} argument is a 1739 string. See |feature-list| below. 1740 Also see |exists()|. 1741 1742hasmapto({what} [, {mode}]) *hasmapto()* 1743 The result is a Number, which is 1 if there is a mapping that 1744 contains {what} in somewhere in the rhs (what it is mapped to) 1745 and this mapping exists in one of the modes indicated by 1746 {mode}. 1747 Both the global mappings and the mappings local to the current 1748 buffer are checked for a match. 1749 If no matching mapping is found 0 is returned. 1750 The following characters are recognized in {mode}: 1751 n Normal mode 1752 v Visual mode 1753 o Operator-pending mode 1754 i Insert mode 1755 l Language-Argument ("r", "f", "t", etc.) 1756 c Command-line mode 1757 When {mode} is omitted, "nvo" is used. 1758 1759 This function is useful to check if a mapping already exists 1760 to a function in a Vim script. Example: > 1761 :if !hasmapto('\ABCdoit') 1762 : map <Leader>d \ABCdoit 1763 :endif 1764< This installs the mapping to "\ABCdoit" only if there isn't 1765 already a mapping to "\ABCdoit". 1766 1767histadd({history}, {item}) *histadd()* 1768 Add the String {item} to the history {history} which can be 1769 one of: *hist-names* 1770 "cmd" or ":" command line history 1771 "search" or "/" search pattern history 1772 "expr" or "=" typed expression history 1773 "input" or "@" input line history 1774 If {item} does already exist in the history, it will be 1775 shifted to become the newest entry. 1776 The result is a Number: 1 if the operation was successful, 1777 otherwise 0 is returned. 1778 1779 Example: > 1780 :call histadd("input", strftime("%Y %b %d")) 1781 :let date=input("Enter date: ") 1782< This function is not available in the |sandbox|. 1783 1784histdel({history} [, {item}]) *histdel()* 1785 Clear {history}, ie. delete all its entries. See |hist-names| 1786 for the possible values of {history}. 1787 1788 If the parameter {item} is given as String, this is seen 1789 as regular expression. All entries matching that expression 1790 will be removed from the history (if there are any). 1791 Upper/lowercase must match, unless "\c" is used |/\c|. 1792 If {item} is a Number, it will be interpreted as index, see 1793 |:history-indexing|. The respective entry will be removed 1794 if it exists. 1795 1796 The result is a Number: 1 for a successful operation, 1797 otherwise 0 is returned. 1798 1799 Examples: 1800 Clear expression register history: > 1801 :call histdel("expr") 1802< 1803 Remove all entries starting with "*" from the search history: > 1804 :call histdel("/", '^\*') 1805< 1806 The following three are equivalent: > 1807 :call histdel("search", histnr("search")) 1808 :call histdel("search", -1) 1809 :call histdel("search", '^'.histget("search", -1).'$') 1810< 1811 To delete the last search pattern and use the last-but-one for 1812 the "n" command and 'hlsearch': > 1813 :call histdel("search", -1) 1814 :let @/ = histget("search", -1) 1815 1816histget({history} [, {index}]) *histget()* 1817 The result is a String, the entry with Number {index} from 1818 {history}. See |hist-names| for the possible values of 1819 {history}, and |:history-indexing| for {index}. If there is 1820 no such entry, an empty String is returned. When {index} is 1821 omitted, the most recent item from the history is used. 1822 1823 Examples: 1824 Redo the second last search from history. > 1825 :execute '/' . histget("search", -2) 1826 1827< Define an Ex command ":H {num}" that supports re-execution of 1828 the {num}th entry from the output of |:history|. > 1829 :command -nargs=1 H execute histget("cmd", 0+<args>) 1830< 1831histnr({history}) *histnr()* 1832 The result is the Number of the current entry in {history}. 1833 See |hist-names| for the possible values of {history}. 1834 If an error occurred, -1 is returned. 1835 1836 Example: > 1837 :let inp_index = histnr("expr") 1838< 1839hlexists({name}) *hlexists()* 1840 The result is a Number, which is non-zero if a highlight group 1841 called {name} exists. This is when the group has been 1842 defined in some way. Not necessarily when highlighting has 1843 been defined for it, it may also have been used for a syntax 1844 item. 1845 *highlight_exists()* 1846 Obsolete name: highlight_exists(). 1847 1848 *hlID()* 1849hlID({name}) The result is a Number, which is the ID of the highlight group 1850 with name {name}. When the highlight group doesn't exist, 1851 zero is returned. 1852 This can be used to retrieve information about the highlight 1853 group. For example, to get the background color of the 1854 "Comment" group: > 1855 :echo synIDattr(synIDtrans(hlID("Comment")), "bg") 1856< *highlightID()* 1857 Obsolete name: highlightID(). 1858 1859hostname() *hostname()* 1860 The result is a String, which is the name of the machine on 1861 which Vim is currently running. Machine names greater than 1862 256 characters long are truncated. 1863 1864iconv({expr}, {from}, {to}) *iconv()* 1865 The result is a String, which is the text {expr} converted 1866 from encoding {from} to encoding {to}. 1867 When the conversion fails an empty string is returned. 1868 The encoding names are whatever the iconv() library function 1869 can accept, see ":!man 3 iconv". 1870 Most conversions require Vim to be compiled with the |+iconv| 1871 feature. Otherwise only UTF-8 to latin1 conversion and back 1872 can be done. 1873 This can be used to display messages with special characters, 1874 no matter what 'encoding' is set to. Write the message in 1875 UTF-8 and use: > 1876 echo iconv(utf8_str, "utf-8", &enc) 1877< Note that Vim uses UTF-8 for all Unicode encodings, conversion 1878 from/to UCS-2 is automatically changed to use UTF-8. You 1879 cannot use UCS-2 in a string anyway, because of the NUL bytes. 1880 {only available when compiled with the +multi_byte feature} 1881 1882 *indent()* 1883indent({lnum}) The result is a Number, which is indent of line {lnum} in the 1884 current buffer. The indent is counted in spaces, the value 1885 of 'tabstop' is relevant. {lnum} is used just like in 1886 |getline()|. 1887 When {lnum} is invalid -1 is returned. 1888 1889input({prompt} [, {text}]) *input()* 1890 The result is a String, which is whatever the user typed on 1891 the command-line. The parameter is either a prompt string, or 1892 a blank string (for no prompt). A '\n' can be used in the 1893 prompt to start a new line. The highlighting set with 1894 |:echohl| is used for the prompt. The input is entered just 1895 like a command-line, with the same editing commands and 1896 mappings. There is a separate history for lines typed for 1897 input(). 1898 If the optional {text} is present, this is used for the 1899 default reply, as if the user typed this. 1900 NOTE: This must not be used in a startup file, for the 1901 versions that only run in GUI mode (e.g., the Win32 GUI). 1902 Note: When input() is called from within a mapping it will 1903 consume remaining characters from that mapping, because a 1904 mapping is handled like the characters were typed. 1905 Use |inputsave()| before input() and |inputrestore()| 1906 after input() to avoid that. Another solution is to avoid 1907 that further characters follow in the mapping, e.g., by using 1908 |:execute| or |:normal|. 1909 1910 Example: > 1911 :if input("Coffee or beer? ") == "beer" 1912 : echo "Cheers!" 1913 :endif 1914< Example with default text: > 1915 :let color = input("Color? ", "white") 1916< Example with a mapping: > 1917 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR> 1918 :function GetFoo() 1919 : call inputsave() 1920 : let g:Foo = input("enter search pattern: ") 1921 : call inputrestore() 1922 :endfunction 1923 1924inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()* 1925 Like input(), but when the GUI is running and text dialogs are 1926 supported, a dialog window pops up to input the text. 1927 Example: > 1928 :let n = inputdialog("value for shiftwidth", &sw) 1929 :if n != "" 1930 : let &sw = n 1931 :endif 1932< When the dialog is cancelled {cancelreturn} is returned. When 1933 omitted an empty string is returned. 1934 Hitting <Enter> works like pressing the OK button. Hitting 1935 <Esc> works like pressing the Cancel button. 1936 1937inputrestore() *inputrestore()* 1938 Restore typeahead that was saved with a previous inputsave(). 1939 Should be called the same number of times inputsave() is 1940 called. Calling it more often is harmless though. 1941 Returns 1 when there is nothing to restore, 0 otherwise. 1942 1943inputsave() *inputsave()* 1944 Preserve typeahead (also from mappings) and clear it, so that 1945 a following prompt gets input from the user. Should be 1946 followed by a matching inputrestore() after the prompt. Can 1947 be used several times, in which case there must be just as 1948 many inputrestore() calls. 1949 Returns 1 when out of memory, 0 otherwise. 1950 1951inputsecret({prompt} [, {text}]) *inputsecret()* 1952 This function acts much like the |input()| function with but 1953 two exceptions: 1954 a) the user's response will be displayed as a sequence of 1955 asterisks ("*") thereby keeping the entry secret, and 1956 b) the user's response will not be recorded on the input 1957 |history| stack. 1958 The result is a String, which is whatever the user actually 1959 typed on the command-line in response to the issued prompt. 1960 1961isdirectory({directory}) *isdirectory()* 1962 The result is a Number, which is non-zero when a directory 1963 with the name {directory} exists. If {directory} doesn't 1964 exist, or isn't a directory, the result is FALSE. {directory} 1965 is any expression, which is used as a String. 1966 1967 *libcall()* *E364* *E368* 1968libcall({libname}, {funcname}, {argument}) 1969 Call function {funcname} in the run-time library {libname} 1970 with single argument {argument}. 1971 This is useful to call functions in a library that you 1972 especially made to be used with Vim. Since only one argument 1973 is possible, calling standard library functions is rather 1974 limited. 1975 The result is the String returned by the function. If the 1976 function returns NULL, this will appear as an empty string "" 1977 to Vim. 1978 If the function returns a number, use libcallnr()! 1979 If {argument} is a number, it is passed to the function as an 1980 int; if {argument} is a string, it is passed as a 1981 null-terminated string. 1982 This function will fail in |restricted-mode|. 1983 1984 libcall() allows you to write your own 'plug-in' extensions to 1985 Vim without having to recompile the program. It is NOT a 1986 means to call system functions! If you try to do so Vim will 1987 very probably crash. 1988 1989 For Win32, the functions you write must be placed in a DLL 1990 and use the normal C calling convention (NOT Pascal which is 1991 used in Windows System DLLs). The function must take exactly 1992 one parameter, either a character pointer or a long integer, 1993 and must return a character pointer or NULL. The character 1994 pointer returned must point to memory that will remain valid 1995 after the function has returned (e.g. in static data in the 1996 DLL). If it points to allocated memory, that memory will 1997 leak away. Using a static buffer in the function should work, 1998 it's then freed when the DLL is unloaded. 1999 2000 WARNING: If the function returns a non-valid pointer, Vim may 2001 crash! This also happens if the function returns a number, 2002 because Vim thinks it's a pointer. 2003 For Win32 systems, {libname} should be the filename of the DLL 2004 without the ".DLL" suffix. A full path is only required if 2005 the DLL is not in the usual places. 2006 For Unix: When compiling your own plugins, remember that the 2007 object code must be compiled as position-independent ('PIC'). 2008 {only in Win32 on some Unix versions, when the |+libcall| 2009 feature is present} 2010 Examples: > 2011 :echo libcall("libc.so", "getenv", "HOME") 2012 :echo libcallnr("/usr/lib/libc.so", "getpid", "") 2013< 2014 *libcallnr()* 2015libcallnr({libname}, {funcname}, {argument}) 2016 Just like libcall(), but used for a function that returns an 2017 int instead of a string. 2018 {only in Win32 on some Unix versions, when the |+libcall| 2019 feature is present} 2020 Example (not very useful...): > 2021 :call libcallnr("libc.so", "printf", "Hello World!\n") 2022 :call libcallnr("libc.so", "sleep", 10) 2023< 2024 *line()* 2025line({expr}) The result is a Number, which is the line number of the file 2026 position given with {expr}. The accepted positions are: 2027 . the cursor position 2028 $ the last line in the current buffer 2029 'x position of mark x (if the mark is not set, 0 is 2030 returned) 2031 Note that only marks in the current file can be used. 2032 Examples: > 2033 line(".") line number of the cursor 2034 line("'t") line number of mark t 2035 line("'" . marker) line number of mark marker 2036< *last-position-jump* 2037 This autocommand jumps to the last known position in a file 2038 just after opening it, if the '" mark is set: > 2039 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif 2040 2041line2byte({lnum}) *line2byte()* 2042 Return the byte count from the start of the buffer for line 2043 {lnum}. This includes the end-of-line character, depending on 2044 the 'fileformat' option for the current buffer. The first 2045 line returns 1. 2046 This can also be used to get the byte count for the line just 2047 below the last line: > 2048 line2byte(line("$") + 1) 2049< This is the file size plus one. 2050 When {lnum} is invalid, or the |+byte_offset| feature has been 2051 disabled at compile time, -1 is returned. 2052 Also see |byte2line()|, |go| and |:goto|. 2053 2054lispindent({lnum}) *lispindent()* 2055 Get the amount of indent for line {lnum} according the lisp 2056 indenting rules, as with 'lisp'. 2057 The indent is counted in spaces, the value of 'tabstop' is 2058 relevant. {lnum} is used just like in |getline()|. 2059 When {lnum} is invalid or Vim was not compiled the 2060 |+lispindent| feature, -1 is returned. 2061 2062localtime() *localtime()* 2063 Return the current time, measured as seconds since 1st Jan 2064 1970. See also |strftime()| and |getftime()|. 2065 2066maparg({name}[, {mode}]) *maparg()* 2067 Return the rhs of mapping {name} in mode {mode}. When there 2068 is no mapping for {name}, an empty String is returned. 2069 These characters can be used for {mode}: 2070 "n" Normal 2071 "v" Visual 2072 "o" Operator-pending 2073 "i" Insert 2074 "c" Cmd-line 2075 "l" langmap |language-mapping| 2076 "" Normal, Visual and Operator-pending 2077 When {mode} is omitted, the modes from "" are used. 2078 The {name} can have special key names, like in the ":map" 2079 command. The returned String has special characters 2080 translated like in the output of the ":map" command listing. 2081 The mappings local to the current buffer are checked first, 2082 then the global mappings. 2083 2084mapcheck({name}[, {mode}]) *mapcheck()* 2085 Check if there is a mapping that matches with {name} in mode 2086 {mode}. See |maparg()| for {mode} and special names in 2087 {name}. 2088 A match happens with a mapping that starts with {name} and 2089 with a mapping which is equal to the start of {name}. 2090 2091 matches mapping "a" "ab" "abc" ~ 2092 mapcheck("a") yes yes yes 2093 mapcheck("abc") yes yes yes 2094 mapcheck("ax") yes no no 2095 mapcheck("b") no no no 2096 2097 The difference with maparg() is that mapcheck() finds a 2098 mapping that matches with {name}, while maparg() only finds a 2099 mapping for {name} exactly. 2100 When there is no mapping that starts with {name}, an empty 2101 String is returned. If there is one, the rhs of that mapping 2102 is returned. If there are several mappings that start with 2103 {name}, the rhs of one of them is returned. 2104 The mappings local to the current buffer are checked first, 2105 then the global mappings. 2106 This function can be used to check if a mapping can be added 2107 without being ambiguous. Example: > 2108 :if mapcheck("_vv") == "" 2109 : map _vv :set guifont=7x13<CR> 2110 :endif 2111< This avoids adding the "_vv" mapping when there already is a 2112 mapping for "_v" or for "_vvv". 2113 2114match({expr}, {pat}[, {start}[, {count}]]) *match()* 2115 The result is a Number, which gives the index (byte offset) in 2116 {expr} where {pat} matches. 2117 A match at the first character returns zero. 2118 If there is no match -1 is returned. 2119 Example: > 2120 :echo match("testing", "ing") 2121< results in "4". 2122 See |string-match| for how {pat} is used. 2123 When {count} is given use the {count}'th match. When a match 2124 is found the search for the next one starts on character 2125 further. Thus this example results in 1: > 2126 echo match("testing", "..", 0, 2) 2127< If {start} is given, the search starts from index {start}. 2128 The result, however, is still the index counted from the 2129 first character. Example: > 2130 :echo match("testing", "ing", 2) 2131< result is again "4". > 2132 :echo match("testing", "ing", 4) 2133< result is again "4". > 2134 :echo match("testing", "t", 2) 2135< result is "3". 2136 If {start} < 0, it will be set to 0. 2137 If {start} > strlen({expr}) -1 is returned. 2138 See |pattern| for the patterns that are accepted. 2139 The 'ignorecase' option is used to set the ignore-caseness of 2140 the pattern. 'smartcase' is NOT used. The matching is always 2141 done like 'magic' is set and 'cpoptions' is empty. 2142 2143matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()* 2144 Same as match(), but return the index of first character after 2145 the match. Example: > 2146 :echo matchend("testing", "ing") 2147< results in "7". 2148 The {start}, if given, has the same meaning as for match(). > 2149 :echo matchend("testing", "ing", 2) 2150< results in "7". > 2151 :echo matchend("testing", "ing", 5) 2152< result is "-1". 2153 2154matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()* 2155 Same as match(), but return the matched string. Example: > 2156 :echo matchstr("testing", "ing") 2157< results in "ing". 2158 When there is no match "" is returned. 2159 The {start}, if given, has the same meaning as for match(). > 2160 :echo matchstr("testing", "ing", 2) 2161< results in "ing". > 2162 :echo matchstr("testing", "ing", 5) 2163< result is "". 2164 2165 *mode()* 2166mode() Return a string that indicates the current mode: 2167 n Normal 2168 v Visual by character 2169 V Visual by line 2170 CTRL-V Visual blockwise 2171 s Select by character 2172 S Select by line 2173 CTRL-S Select blockwise 2174 i Insert 2175 R Replace 2176 c Command-line 2177 r Hit-enter prompt 2178 This is useful in the 'statusline' option. In most other 2179 places it always returns "c" or "n". 2180 2181nextnonblank({lnum}) *nextnonblank()* 2182 Return the line number of the first line at or below {lnum} 2183 that is not blank. Example: > 2184 if getline(nextnonblank(1)) =~ "Java" 2185< When {lnum} is invalid or there is no non-blank line at or 2186 below it, zero is returned. 2187 See also |prevnonblank()|. 2188 2189nr2char({expr}) *nr2char()* 2190 Return a string with a single character, which has the number 2191 value {expr}. Examples: > 2192 nr2char(64) returns "@" 2193 nr2char(32) returns " " 2194< The current 'encoding' is used. Example for "utf-8": > 2195 nr2char(300) returns I with bow character 2196< Note that a NUL character in the file is specified with 2197 nr2char(10), because NULs are represented with newline 2198 characters. nr2char(0) is a real NUL and terminates the 2199 string, thus isn't very useful. 2200 2201prevnonblank({lnum}) *prevnonblank()* 2202 Return the line number of the first line at or above {lnum} 2203 that is not blank. Example: > 2204 let ind = indent(prevnonblank(v:lnum - 1)) 2205< When {lnum} is invalid or there is no non-blank line at or 2206 above it, zero is returned. 2207 Also see |nextnonblank()|. 2208 2209 *remote_expr()* *E449* 2210remote_expr({server}, {string} [, {idvar}]) 2211 Send the {string} to {server}. The string is sent as an 2212 expression and the result is returned after evaluation. 2213 If {idvar} is present, it is taken as the name of a 2214 variable and a {serverid} for later use with 2215 remote_read() is stored there. 2216 See also |clientserver| |RemoteReply|. 2217 This function is not available in the |sandbox|. 2218 {only available when compiled with the |+clientserver| feature} 2219 Note: Any errors will cause a local error message to be issued 2220 and the result will be the empty string. 2221 Examples: > 2222 :echo remote_expr("gvim", "2+2") 2223 :echo remote_expr("gvim1", "b:current_syntax") 2224< 2225 2226remote_foreground({server}) *remote_foreground()* 2227 Move the Vim server with the name {server} to the foreground. 2228 This works like: > 2229 remote_expr({server}, "foreground()") 2230< Except that on Win32 systems the client does the work, to work 2231 around the problem that the OS doesn't always allow the server 2232 to bring itself to the foreground. 2233 This function is not available in the |sandbox|. 2234 {only in the Win32, Athena, Motif and GTK GUI versions and the 2235 Win32 console version} 2236 2237 2238remote_peek({serverid} [, {retvar}]) *remote_peek()* 2239 Returns a positive number if there are available strings 2240 from {serverid}. Copies any reply string into the variable 2241 {retvar} if specified. {retvar} must be a string with the 2242 name of a variable. 2243 Returns zero if none are available. 2244 Returns -1 if something is wrong. 2245 See also |clientserver|. 2246 This function is not available in the |sandbox|. 2247 {only available when compiled with the |+clientserver| feature} 2248 Examples: > 2249 :let repl = "" 2250 :echo "PEEK: ".remote_peek(id, "repl").": ".repl 2251 2252remote_read({serverid}) *remote_read()* 2253 Return the oldest available reply from {serverid} and consume 2254 it. It blocks until a reply is available. 2255 See also |clientserver|. 2256 This function is not available in the |sandbox|. 2257 {only available when compiled with the |+clientserver| feature} 2258 Example: > 2259 :echo remote_read(id) 2260< 2261 *remote_send()* *E241* 2262remote_send({server}, {string} [, {idvar}]) 2263 Send the {string} to {server}. The string is sent as input 2264 keys and the function returns immediately. At the Vim server 2265 the keys are not mapped |:map|. 2266 If {idvar} is present, it is taken as the name of a 2267 variable and a {serverid} for later use with 2268 remote_read() is stored there. 2269 See also |clientserver| |RemoteReply|. 2270 This function is not available in the |sandbox|. 2271 {only available when compiled with the |+clientserver| feature} 2272 Note: Any errors will be reported in the server and may mess 2273 up the display. 2274 Examples: > 2275 :echo remote_send("gvim", ":DropAndReply ".file, "serverid"). 2276 \ remote_read(serverid) 2277 2278 :autocmd NONE RemoteReply * 2279 \ echo remote_read(expand("<amatch>")) 2280 :echo remote_send("gvim", ":sleep 10 | echo ". 2281 \ 'server2client(expand("<client>"), "HELLO")<CR>') 2282 2283 2284rename({from}, {to}) *rename()* 2285 Rename the file by the name {from} to the name {to}. This 2286 should also work to move files across file systems. The 2287 result is a Number, which is 0 if the file was renamed 2288 successfully, and non-zero when the renaming failed. 2289 This function is not available in the |sandbox|. 2290 2291repeat({expr}, {count}) *repeat()* 2292 Repeat {expr} {count} times and return the concatenated 2293 result. Example: > 2294 :let seperator = repeat('-', 80) 2295< When {count} is zero or negative the result is empty. 2296 2297resolve({filename}) *resolve()* *E655* 2298 On MS-Windows, when {filename} is a shortcut (a .lnk file), 2299 returns the path the shortcut points to in a simplified form. 2300 On Unix, repeat resolving symbolic links in all path 2301 components of {filename} and return the simplified result. 2302 To cope with link cycles, resolving of symbolic links is 2303 stopped after 100 iterations. 2304 On other systems, return the simplified {filename}. 2305 The simplification step is done as by |simplify()|. 2306 resolve() keeps a leading path component specifying the 2307 current directory (provided the result is still a relative 2308 path name) and also keeps a trailing path separator. 2309 2310search({pattern} [, {flags}]) *search()* 2311 Search for regexp pattern {pattern}. The search starts at the 2312 cursor position. 2313 {flags} is a String, which can contain these character flags: 2314 'b' search backward instead of forward 2315 'n' do Not move the cursor 2316 'w' wrap around the end of the file 2317 'W' don't wrap around the end of the file 2318 If neither 'w' or 'W' is given, the 'wrapscan' option applies. 2319 2320 When a match has been found its line number is returned. 2321 The cursor will be positioned at the match, unless the 'n' 2322 flag is used). 2323 If there is no match a 0 is returned and the cursor doesn't 2324 move. No error message is given. 2325 2326 Example (goes over all files in the argument list): > 2327 :let n = 1 2328 :while n <= argc() " loop over all files in arglist 2329 : exe "argument " . n 2330 : " start at the last char in the file and wrap for the 2331 : " first search to find match at start of file 2332 : normal G$ 2333 : let flags = "w" 2334 : while search("foo", flags) > 0 2335 : s/foo/bar/g 2336 : let flags = "W" 2337 : endwhile 2338 : update " write the file if modified 2339 : let n = n + 1 2340 :endwhile 2341< 2342 *searchpair()* 2343searchpair({start}, {middle}, {end} [, {flags} [, {skip}]]) 2344 Search for the match of a nested start-end pair. This can be 2345 used to find the "endif" that matches an "if", while other 2346 if/endif pairs in between are ignored. 2347 The search starts at the cursor. If a match is found, the 2348 cursor is positioned at it and the line number is returned. 2349 If no match is found 0 or -1 is returned and the cursor 2350 doesn't move. No error message is given. 2351 2352 {start}, {middle} and {end} are patterns, see |pattern|. They 2353 must not contain \( \) pairs. Use of \%( \) is allowed. When 2354 {middle} is not empty, it is found when searching from either 2355 direction, but only when not in a nested start-end pair. A 2356 typical use is: > 2357 searchpair('\<if\>', '\<else\>', '\<endif\>') 2358< By leaving {middle} empty the "else" is skipped. 2359 2360 {flags} are used like with |search()|. Additionally: 2361 'n' do Not move the cursor 2362 'r' Repeat until no more matches found; will find the 2363 outer pair 2364 'm' return number of Matches instead of line number with 2365 the match; will only be > 1 when 'r' is used. 2366 2367 When a match for {start}, {middle} or {end} is found, the 2368 {skip} expression is evaluated with the cursor positioned on 2369 the start of the match. It should return non-zero if this 2370 match is to be skipped. E.g., because it is inside a comment 2371 or a string. 2372 When {skip} is omitted or empty, every match is accepted. 2373 When evaluating {skip} causes an error the search is aborted 2374 and -1 returned. 2375 2376 The value of 'ignorecase' is used. 'magic' is ignored, the 2377 patterns are used like it's on. 2378 2379 The search starts exactly at the cursor. A match with 2380 {start}, {middle} or {end} at the next character, in the 2381 direction of searching, is the first one found. Example: > 2382 if 1 2383 if 2 2384 endif 2 2385 endif 1 2386< When starting at the "if 2", with the cursor on the "i", and 2387 searching forwards, the "endif 2" is found. When starting on 2388 the character just before the "if 2", the "endif 1" will be 2389 found. That's because the "if 2" will be found first, and 2390 then this is considered to be a nested if/endif from "if 2" to 2391 "endif 2". 2392 When searching backwards and {end} is more than one character, 2393 it may be useful to put "\zs" at the end of the pattern, so 2394 that when the cursor is inside a match with the end it finds 2395 the matching start. 2396 2397 Example, to find the "endif" command in a Vim script: > 2398 2399 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W', 2400 \ 'getline(".") =~ "^\\s*\""') 2401 2402< The cursor must be at or after the "if" for which a match is 2403 to be found. Note that single-quote strings are used to avoid 2404 having to double the backslashes. The skip expression only 2405 catches comments at the start of a line, not after a command. 2406 Also, a word "en" or "if" halfway a line is considered a 2407 match. 2408 Another example, to search for the matching "{" of a "}": > 2409 2410 :echo searchpair('{', '', '}', 'bW') 2411 2412< This works when the cursor is at or before the "}" for which a 2413 match is to be found. To reject matches that syntax 2414 highlighting recognized as strings: > 2415 2416 :echo searchpair('{', '', '}', 'bW', 2417 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"') 2418< 2419server2client( {clientid}, {string}) *server2client()* 2420 Send a reply string to {clientid}. The most recent {clientid} 2421 that sent a string can be retrieved with expand("<client>"). 2422 {only available when compiled with the |+clientserver| feature} 2423 Note: 2424 This id has to be stored before the next command can be 2425 received. Ie. before returning from the received command and 2426 before calling any commands that waits for input. 2427 See also |clientserver|. 2428 Example: > 2429 :echo server2client(expand("<client>"), "HELLO") 2430< 2431serverlist() *serverlist()* 2432 Return a list of available server names, one per line. 2433 When there are no servers or the information is not available 2434 an empty string is returned. See also |clientserver|. 2435 {only available when compiled with the |+clientserver| feature} 2436 Example: > 2437 :echo serverlist() 2438< 2439setbufvar({expr}, {varname}, {val}) *setbufvar()* 2440 Set option or local variable {varname} in buffer {expr} to 2441 {val}. 2442 This also works for a global or local window option, but it 2443 doesn't work for a global or local window variable. 2444 For a local window option the global value is unchanged. 2445 For the use of {expr}, see |bufname()| above. 2446 Note that the variable name without "b:" must be used. 2447 Examples: > 2448 :call setbufvar(1, "&mod", 1) 2449 :call setbufvar("todo", "myvar", "foobar") 2450< This function is not available in the |sandbox|. 2451 2452setcmdpos({pos}) *setcmdpos()* 2453 Set the cursor position in the command line to byte position 2454 {pos}. The first position is 1. 2455 Use |getcmdpos()| to obtain the current position. 2456 Only works while editing the command line, thus you must use 2457 |c_CTRL-\_e| or |c_CTRL-R_=|. The position is set after the 2458 command line is set to the expression. 2459 When the number is too big the cursor is put at the end of the 2460 line. A number smaller than one has undefined results. 2461 Returns 0 when successful, 1 when not editing the command 2462 line. 2463 2464setline({lnum}, {line}) *setline()* 2465 Set line {lnum} of the current buffer to {line}. If this 2466 succeeds, 0 is returned. If this fails (most likely because 2467 {lnum} is invalid) 1 is returned. Example: > 2468 :call setline(5, strftime("%c")) 2469< Note: The '[ and '] marks are not set. 2470 2471 *setreg()* 2472setreg({regname}, {value} [,{options}]) 2473 Set the register {regname} to {value}. 2474 If {options} contains "a" or {regname} is upper case, 2475 then the value is appended. 2476 {options} can also contains a register type specification: 2477 "c" or "v" |characterwise| mode 2478 "l" or "V" |linewise| mode 2479 "b" or "<CTRL-V>" |blockwise-visual| mode 2480 If a number immediately follows "b" or "<CTRL-V>" then this is 2481 used as the width of the selection - if it is not specified 2482 then the width of the block is set to the number of characters 2483 in the longest line (counting a <TAB> as 1 character). 2484 2485 If {options} contains no register settings, then the default 2486 is to use character mode unless {value} ends in a <NL>. 2487 Setting the '=' register is not possible. 2488 Returns zero for success, non-zero for failure. 2489 2490 Examples: > 2491 :call setreg(v:register, @*) 2492 :call setreg('*', @%, 'ac') 2493 :call setreg('a', "1\n2\n3", 'b5') 2494 2495< This example shows using the functions to save and restore a 2496 register. > 2497 :let var_a = getreg('a') 2498 :let var_amode = getregtype('a') 2499 .... 2500 :call setreg('a', var_a, var_amode) 2501 2502< You can also change the type of a register by appending 2503 nothing: > 2504 :call setreg('a', '', 'al') 2505 2506setwinvar({nr}, {varname}, {val}) *setwinvar()* 2507 Set option or local variable {varname} in window {nr} to 2508 {val}. 2509 This also works for a global or local buffer option, but it 2510 doesn't work for a global or local buffer variable. 2511 For a local buffer option the global value is unchanged. 2512 Note that the variable name without "w:" must be used. 2513 Examples: > 2514 :call setwinvar(1, "&list", 0) 2515 :call setwinvar(2, "myvar", "foobar") 2516< This function is not available in the |sandbox|. 2517 2518simplify({filename}) *simplify()* 2519 Simplify the file name as much as possible without changing 2520 the meaning. Shortcuts (on MS-Windows) or symbolic links (on 2521 Unix) are not resolved. If the first path component in 2522 {filename} designates the current directory, this will be 2523 valid for the result as well. A trailing path separator is 2524 not removed either. 2525 Example: > 2526 simplify("./dir/.././/file/") == "./file/" 2527< Note: The combination "dir/.." is only removed if "dir" is 2528 a searchable directory or does not exist. On Unix, it is also 2529 removed when "dir" is a symbolic link within the same 2530 directory. In order to resolve all the involved symbolic 2531 links before simplifying the path name, use |resolve()|. 2532 2533strftime({format} [, {time}]) *strftime()* 2534 The result is a String, which is a formatted date and time, as 2535 specified by the {format} string. The given {time} is used, 2536 or the current time if no time is given. The accepted 2537 {format} depends on your system, thus this is not portable! 2538 See the manual page of the C function strftime() for the 2539 format. The maximum length of the result is 80 characters. 2540 See also |localtime()| and |getftime()|. 2541 The language can be changed with the |:language| command. 2542 Examples: > 2543 :echo strftime("%c") Sun Apr 27 11:49:23 1997 2544 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25 2545 :echo strftime("%y%m%d %T") 970427 11:53:55 2546 :echo strftime("%H:%M") 11:55 2547 :echo strftime("%c", getftime("file.c")) 2548 Show mod time of file.c. 2549< 2550stridx({haystack}, {needle}) *stridx()* 2551 The result is a Number, which gives the index in {haystack} of 2552 the first occurrence of the String {needle} in the String 2553 {haystack}. The search is done case-sensitive. For advanced 2554 searches use |match()|. 2555 If the {needle} does not occur in {haystack} it returns -1. 2556 See also |strridx()|. Examples: > 2557 :echo stridx("An Example", "Example") 3 2558 :echo stridx("Starting point", "Start") 0 2559 :echo stridx("Starting point", "start") -1 2560< 2561 *strlen()* 2562strlen({expr}) The result is a Number, which is the length of the String 2563 {expr} in bytes. If you want to count the number of 2564 multi-byte characters use something like this: > 2565 2566 :let len = strlen(substitute(str, ".", "x", "g")) 2567 2568< Composing characters are not counted. 2569 2570strpart({src}, {start}[, {len}]) *strpart()* 2571 The result is a String, which is part of {src}, starting from 2572 byte {start}, with the length {len}. 2573 When non-existing bytes are included, this doesn't result in 2574 an error, the bytes are simply omitted. 2575 If {len} is missing, the copy continues from {start} till the 2576 end of the {src}. > 2577 strpart("abcdefg", 3, 2) == "de" 2578 strpart("abcdefg", -2, 4) == "ab" 2579 strpart("abcdefg", 5, 4) == "fg" 2580 strpart("abcdefg", 3) == "defg" 2581< Note: To get the first character, {start} must be 0. For 2582 example, to get three bytes under and after the cursor: > 2583 strpart(getline(line(".")), col(".") - 1, 3) 2584< 2585strridx({haystack}, {needle}) *strridx()* 2586 The result is a Number, which gives the index in {haystack} of 2587 the last occurrence of the String {needle} in the String 2588 {haystack}. The search is done case-sensitive. For advanced 2589 searches use |match()|. 2590 If the {needle} does not occur in {haystack} it returns -1. 2591 If the {needle} is empty the length of {haystack} is returned. 2592 See also |stridx()|. Examples: > 2593 :echo strridx("an angry armadillo", "an") 3 2594< 2595strtrans({expr}) *strtrans()* 2596 The result is a String, which is {expr} with all unprintable 2597 characters translated into printable characters |'isprint'|. 2598 Like they are shown in a window. Example: > 2599 echo strtrans(@a) 2600< This displays a newline in register a as "^@" instead of 2601 starting a new line. 2602 2603submatch({nr}) *submatch()* 2604 Only for an expression in a |:substitute| command. Returns 2605 the {nr}'th submatch of the matched text. When {nr} is 0 2606 the whole matched text is returned. 2607 Example: > 2608 :s/\d\+/\=submatch(0) + 1/ 2609< This finds the first number in the line and adds one to it. 2610 A line break is included as a newline character. 2611 2612substitute({expr}, {pat}, {sub}, {flags}) *substitute()* 2613 The result is a String, which is a copy of {expr}, in which 2614 the first match of {pat} is replaced with {sub}. This works 2615 like the ":substitute" command (without any flags). But the 2616 matching with {pat} is always done like the 'magic' option is 2617 set and 'cpoptions' is empty (to make scripts portable). 2618 See |string-match| for how {pat} is used. 2619 And a "~" in {sub} is not replaced with the previous {sub}. 2620 Note that some codes in {sub} have a special meaning 2621 |sub-replace-special|. For example, to replace something with 2622 "\n" (two characters), use "\\\\n" or '\\n'. 2623 When {pat} does not match in {expr}, {expr} is returned 2624 unmodified. 2625 When {flags} is "g", all matches of {pat} in {expr} are 2626 replaced. Otherwise {flags} should be "". 2627 Example: > 2628 :let &path = substitute(&path, ",\\=[^,]*$", "", "") 2629< This removes the last component of the 'path' option. > 2630 :echo substitute("testing", ".*", "\\U\\0", "") 2631< results in "TESTING". 2632 2633synID({line}, {col}, {trans}) *synID()* 2634 The result is a Number, which is the syntax ID at the position 2635 {line} and {col} in the current window. 2636 The syntax ID can be used with |synIDattr()| and 2637 |synIDtrans()| to obtain syntax information about text. 2638 {col} is 1 for the leftmost column, {line} is 1 for the first 2639 line. 2640 When {trans} is non-zero, transparent items are reduced to the 2641 item that they reveal. This is useful when wanting to know 2642 the effective color. When {trans} is zero, the transparent 2643 item is returned. This is useful when wanting to know which 2644 syntax item is effective (e.g. inside parens). 2645 Warning: This function can be very slow. Best speed is 2646 obtained by going through the file in forward direction. 2647 2648 Example (echoes the name of the syntax item under the cursor): > 2649 :echo synIDattr(synID(line("."), col("."), 1), "name") 2650< 2651synIDattr({synID}, {what} [, {mode}]) *synIDattr()* 2652 The result is a String, which is the {what} attribute of 2653 syntax ID {synID}. This can be used to obtain information 2654 about a syntax item. 2655 {mode} can be "gui", "cterm" or "term", to get the attributes 2656 for that mode. When {mode} is omitted, or an invalid value is 2657 used, the attributes for the currently active highlighting are 2658 used (GUI, cterm or term). 2659 Use synIDtrans() to follow linked highlight groups. 2660 {what} result 2661 "name" the name of the syntax item 2662 "fg" foreground color (GUI: color name used to set 2663 the color, cterm: color number as a string, 2664 term: empty string) 2665 "bg" background color (like "fg") 2666 "fg#" like "fg", but for the GUI and the GUI is 2667 running the name in "#RRGGBB" form 2668 "bg#" like "fg#" for "bg" 2669 "bold" "1" if bold 2670 "italic" "1" if italic 2671 "reverse" "1" if reverse 2672 "inverse" "1" if inverse (= reverse) 2673 "underline" "1" if underlined 2674 2675 Example (echoes the color of the syntax item under the 2676 cursor): > 2677 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg") 2678< 2679synIDtrans({synID}) *synIDtrans()* 2680 The result is a Number, which is the translated syntax ID of 2681 {synID}. This is the syntax group ID of what is being used to 2682 highlight the character. Highlight links given with 2683 ":highlight link" are followed. 2684 2685system({expr} [, {input}]) *system()* *E677* 2686 Get the output of the shell command {expr}. 2687 When {input} is given, this string is written to a file and 2688 passed as stdin to the command. The string is written as-is, 2689 you need to take care of using the correct line separators 2690 yourself. 2691 Note: newlines in {expr} may cause the command to fail. The 2692 characters in 'shellquote' and 'shellxquote' may also cause 2693 trouble. 2694 This is not to be used for interactive commands. 2695 The result is a String. Example: > 2696 2697 :let files = system("ls") 2698 2699< To make the result more system-independent, the shell output 2700 is filtered to replace <CR> with <NL> for Macintosh, and 2701 <CR><NL> with <NL> for DOS-like systems. 2702 The command executed is constructed using several options: 2703 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote' 2704 ({tmp} is an automatically generated file name). 2705 For Unix and OS/2 braces are put around {expr} to allow for 2706 concatenated commands. 2707 2708 The resulting error code can be found in |v:shell_error|. 2709 This function will fail in |restricted-mode|. 2710 Unlike ":!cmd" there is no automatic check for changed files. 2711 Use |:checktime| to force a check. 2712 2713tempname() *tempname()* *temp-file-name* 2714 The result is a String, which is the name of a file that 2715 doesn't exist. It can be used for a temporary file. The name 2716 is different for at least 26 consecutive calls. Example: > 2717 :let tmpfile = tempname() 2718 :exe "redir > " . tmpfile 2719< For Unix, the file will be in a private directory (only 2720 accessible by the current user) to avoid security problems 2721 (e.g., a symlink attack or other people reading your file). 2722 When Vim exits the directory and all files in it are deleted. 2723 For MS-Windows forward slashes are used when the 'shellslash' 2724 option is set or when 'shellcmdflag' starts with '-'. 2725 2726tolower({expr}) *tolower()* 2727 The result is a copy of the String given, with all uppercase 2728 characters turned into lowercase (just like applying |gu| to 2729 the string). 2730 2731toupper({expr}) *toupper()* 2732 The result is a copy of the String given, with all lowercase 2733 characters turned into uppercase (just like applying |gU| to 2734 the string). 2735 2736tr({src}, {fromstr}, {tostr}) *tr()* 2737 The result is a copy of the {src} string with all characters 2738 which appear in {fromstr} replaced by the character in that 2739 position in the {tostr} string. Thus the first character in 2740 {fromstr} is translated into the first character in {tostr} 2741 and so on. Exactly like the unix "tr" command. 2742 This code also deals with multibyte characters properly. 2743 2744 Examples: > 2745 echo tr("hello there", "ht", "HT") 2746< returns "Hello THere" > 2747 echo tr("<blob>", "<>", "{}") 2748< returns "{blob}" 2749 2750type({expr}) *type()* 2751 The result is a Number: 2752 0 if {expr} has the type Number 2753 1 if {expr} has the type String 2754 2755virtcol({expr}) *virtcol()* 2756 The result is a Number, which is the screen column of the file 2757 position given with {expr}. That is, the last screen position 2758 occupied by the character at that position, when the screen 2759 would be of unlimited width. When there is a <Tab> at the 2760 position, the returned Number will be the column at the end of 2761 the <Tab>. For example, for a <Tab> in column 1, with 'ts' 2762 set to 8, it returns 8. 2763 For the byte position use |col()|. 2764 When Virtual editing is active in the current mode, a position 2765 beyond the end of the line can be returned. |'virtualedit'| 2766 The accepted positions are: 2767 . the cursor position 2768 $ the end of the cursor line (the result is the 2769 number of displayed characters in the cursor line 2770 plus one) 2771 'x position of mark x (if the mark is not set, 0 is 2772 returned) 2773 Note that only marks in the current file can be used. 2774 Examples: > 2775 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5 2776 virtcol("$") with text "foo^Lbar", returns 9 2777 virtcol("'t") with text " there", with 't at 'h', returns 6 2778< The first column is 1. 0 is returned for an error. 2779 2780visualmode([expr]) *visualmode()* 2781 The result is a String, which describes the last Visual mode 2782 used. Initially it returns an empty string, but once Visual 2783 mode has been used, it returns "v", "V", or "<CTRL-V>" (a 2784 single CTRL-V character) for character-wise, line-wise, or 2785 block-wise Visual mode respectively. 2786 Example: > 2787 :exe "normal " . visualmode() 2788< This enters the same Visual mode as before. It is also useful 2789 in scripts if you wish to act differently depending on the 2790 Visual mode that was used. 2791 2792 If an expression is supplied that results in a non-zero number 2793 or a non-empty string, then the Visual mode will be cleared 2794 and the old value is returned. Note that " " and "0" are also 2795 non-empty strings, thus cause the mode to be cleared. 2796 2797 *winbufnr()* 2798winbufnr({nr}) The result is a Number, which is the number of the buffer 2799 associated with window {nr}. When {nr} is zero, the number of 2800 the buffer in the current window is returned. When window 2801 {nr} doesn't exist, -1 is returned. 2802 Example: > 2803 :echo "The file in the current window is " . bufname(winbufnr(0)) 2804< 2805 *wincol()* 2806wincol() The result is a Number, which is the virtual column of the 2807 cursor in the window. This is counting screen cells from the 2808 left side of the window. The leftmost column is one. 2809 2810winheight({nr}) *winheight()* 2811 The result is a Number, which is the height of window {nr}. 2812 When {nr} is zero, the height of the current window is 2813 returned. When window {nr} doesn't exist, -1 is returned. 2814 An existing window always has a height of zero or more. 2815 Examples: > 2816 :echo "The current window has " . winheight(0) . " lines." 2817< 2818 *winline()* 2819winline() The result is a Number, which is the screen line of the cursor 2820 in the window. This is counting screen lines from the top of 2821 the window. The first line is one. 2822 2823 *winnr()* 2824winnr([{arg}]) The result is a Number, which is the number of the current 2825 window. The top window has number 1. 2826 When the optional argument is "$", the number of the 2827 last window is returnd (the window count). 2828 When the optional argument is "#", the number of the last 2829 accessed window is returned (where |CTRL-W_p| goes to). 2830 If there is no previous window 0 is returned. 2831 The number can be used with |CTRL-W_w| and ":wincmd w" 2832 |:wincmd|. 2833 2834 *winrestcmd()* 2835winrestcmd() Returns a sequence of |:resize| commands that should restore 2836 the current window sizes. Only works properly when no windows 2837 are opened or closed and the current window is unchanged. 2838 Example: > 2839 :let cmd = winrestcmd() 2840 :call MessWithWindowSizes() 2841 :exe cmd 2842 2843winwidth({nr}) *winwidth()* 2844 The result is a Number, which is the width of window {nr}. 2845 When {nr} is zero, the width of the current window is 2846 returned. When window {nr} doesn't exist, -1 is returned. 2847 An existing window always has a width of zero or more. 2848 Examples: > 2849 :echo "The current window has " . winwidth(0) . " columns." 2850 :if winwidth(0) <= 50 2851 : exe "normal 50\<C-W>|" 2852 :endif 2853< 2854 2855 *feature-list* 2856There are three types of features: 28571. Features that are only supported when they have been enabled when Vim 2858 was compiled |+feature-list|. Example: > 2859 :if has("cindent") 28602. Features that are only supported when certain conditions have been met. 2861 Example: > 2862 :if has("gui_running") 2863< *has-patch* 28643. Included patches. First check |v:version| for the version of Vim. 2865 Then the "patch123" feature means that patch 123 has been included for 2866 this version. Example (checking version 6.2.148 or later): > 2867 :if v:version > 602 || v:version == 602 && has("patch148") 2868 2869all_builtin_terms Compiled with all builtin terminals enabled. 2870amiga Amiga version of Vim. 2871arabic Compiled with Arabic support |Arabic|. 2872arp Compiled with ARP support (Amiga). 2873autocmd Compiled with autocommands support. 2874balloon_eval Compiled with |balloon-eval| support. 2875beos BeOS version of Vim. 2876browse Compiled with |:browse| support, and browse() will 2877 work. 2878builtin_terms Compiled with some builtin terminals. 2879byte_offset Compiled with support for 'o' in 'statusline' 2880cindent Compiled with 'cindent' support. 2881clientserver Compiled with remote invocation support |clientserver|. 2882clipboard Compiled with 'clipboard' support. 2883cmdline_compl Compiled with |cmdline-completion| support. 2884cmdline_hist Compiled with |cmdline-history| support. 2885cmdline_info Compiled with 'showcmd' and 'ruler' support. 2886comments Compiled with |'comments'| support. 2887cryptv Compiled with encryption support |encryption|. 2888cscope Compiled with |cscope| support. 2889compatible Compiled to be very Vi compatible. 2890debug Compiled with "DEBUG" defined. 2891dialog_con Compiled with console dialog support. 2892dialog_gui Compiled with GUI dialog support. 2893diff Compiled with |vimdiff| and 'diff' support. 2894digraphs Compiled with support for digraphs. 2895dnd Compiled with support for the "~ register |quote_~|. 2896dos32 32 bits DOS (DJGPP) version of Vim. 2897dos16 16 bits DOS version of Vim. 2898ebcdic Compiled on a machine with ebcdic character set. 2899emacs_tags Compiled with support for Emacs tags. 2900eval Compiled with expression evaluation support. Always 2901 true, of course! 2902ex_extra Compiled with extra Ex commands |+ex_extra|. 2903extra_search Compiled with support for |'incsearch'| and 2904 |'hlsearch'| 2905farsi Compiled with Farsi support |farsi|. 2906file_in_path Compiled with support for |gf| and |<cfile>| 2907find_in_path Compiled with support for include file searches 2908 |+find_in_path|. 2909fname_case Case in file names matters (for Amiga, MS-DOS, and 2910 Windows this is not present). 2911folding Compiled with |folding| support. 2912footer Compiled with GUI footer support. |gui-footer| 2913fork Compiled to use fork()/exec() instead of system(). 2914gettext Compiled with message translation |multi-lang| 2915gui Compiled with GUI enabled. 2916gui_athena Compiled with Athena GUI. 2917gui_beos Compiled with BeOS GUI. 2918gui_gtk Compiled with GTK+ GUI (any version). 2919gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined). 2920gui_kde Compiled with KDE GUI |KVim| 2921gui_mac Compiled with Macintosh GUI. 2922gui_motif Compiled with Motif GUI. 2923gui_photon Compiled with Photon GUI. 2924gui_win32 Compiled with MS Windows Win32 GUI. 2925gui_win32s idem, and Win32s system being used (Windows 3.1) 2926gui_running Vim is running in the GUI, or it will start soon. 2927hangul_input Compiled with Hangul input support. |hangul| 2928iconv Can use iconv() for conversion. 2929insert_expand Compiled with support for CTRL-X expansion commands in 2930 Insert mode. 2931jumplist Compiled with |jumplist| support. 2932keymap Compiled with 'keymap' support. 2933langmap Compiled with 'langmap' support. 2934libcall Compiled with |libcall()| support. 2935linebreak Compiled with 'linebreak', 'breakat' and 'showbreak' 2936 support. 2937lispindent Compiled with support for lisp indenting. 2938listcmds Compiled with commands for the buffer list |:files| 2939 and the argument list |arglist|. 2940localmap Compiled with local mappings and abbr. |:map-local| 2941mac Macintosh version of Vim. 2942macunix Macintosh version of Vim, using Unix files (OS-X). 2943menu Compiled with support for |:menu|. 2944mksession Compiled with support for |:mksession|. 2945modify_fname Compiled with file name modifiers. |filename-modifiers| 2946mouse Compiled with support mouse. 2947mouseshape Compiled with support for 'mouseshape'. 2948mouse_dec Compiled with support for Dec terminal mouse. 2949mouse_gpm Compiled with support for gpm (Linux console mouse) 2950mouse_netterm Compiled with support for netterm mouse. 2951mouse_pterm Compiled with support for qnx pterm mouse. 2952mouse_xterm Compiled with support for xterm mouse. 2953multi_byte Compiled with support for editing Korean et al. 2954multi_byte_ime Compiled with support for IME input method. 2955multi_lang Compiled with support for multiple languages. 2956mzscheme Compiled with MzScheme interface |mzscheme|. 2957netbeans_intg Compiled with support for |netbeans|. 2958ole Compiled with OLE automation support for Win32. 2959os2 OS/2 version of Vim. 2960osfiletype Compiled with support for osfiletypes |+osfiletype| 2961path_extra Compiled with up/downwards search in 'path' and 'tags' 2962perl Compiled with Perl interface. 2963postscript Compiled with PostScript file printing. 2964printer Compiled with |:hardcopy| support. 2965python Compiled with Python interface. 2966qnx QNX version of Vim. 2967quickfix Compiled with |quickfix| support. 2968rightleft Compiled with 'rightleft' support. 2969ruby Compiled with Ruby interface |ruby|. 2970scrollbind Compiled with 'scrollbind' support. 2971showcmd Compiled with 'showcmd' support. 2972signs Compiled with |:sign| support. 2973smartindent Compiled with 'smartindent' support. 2974sniff Compiled with SNiFF interface support. 2975statusline Compiled with support for 'statusline', 'rulerformat' 2976 and special formats of 'titlestring' and 'iconstring'. 2977sun_workshop Compiled with support for Sun |workshop|. 2978syntax Compiled with syntax highlighting support. 2979syntax_items There are active syntax highlighting items for the 2980 current buffer. 2981system Compiled to use system() instead of fork()/exec(). 2982tag_binary Compiled with binary searching in tags files 2983 |tag-binary-search|. 2984tag_old_static Compiled with support for old static tags 2985 |tag-old-static|. 2986tag_any_white Compiled with support for any white characters in tags 2987 files |tag-any-white|. 2988tcl Compiled with Tcl interface. 2989terminfo Compiled with terminfo instead of termcap. 2990termresponse Compiled with support for |t_RV| and |v:termresponse|. 2991textobjects Compiled with support for |text-objects|. 2992tgetent Compiled with tgetent support, able to use a termcap 2993 or terminfo file. 2994title Compiled with window title support |'title'|. 2995toolbar Compiled with support for |gui-toolbar|. 2996unix Unix version of Vim. 2997user_commands User-defined commands. 2998viminfo Compiled with viminfo support. 2999vim_starting True while initial source'ing takes place. 3000vertsplit Compiled with vertically split windows |:vsplit|. 3001virtualedit Compiled with 'virtualedit' option. 3002visual Compiled with Visual mode. 3003visualextra Compiled with extra Visual mode commands. 3004 |blockwise-operators|. 3005vms VMS version of Vim. 3006vreplace Compiled with |gR| and |gr| commands. 3007wildignore Compiled with 'wildignore' option. 3008wildmenu Compiled with 'wildmenu' option. 3009windows Compiled with support for more than one window. 3010winaltkeys Compiled with 'winaltkeys' option. 3011win16 Win16 version of Vim (MS-Windows 3.1). 3012win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP). 3013win64 Win64 version of Vim (MS-Windows 64 bit). 3014win32unix Win32 version of Vim, using Unix files (Cygwin) 3015win95 Win32 version for MS-Windows 95/98/ME. 3016writebackup Compiled with 'writebackup' default on. 3017xfontset Compiled with X fontset support |xfontset|. 3018xim Compiled with X input method support |xim|. 3019xsmp Compiled with X session management support. 3020xsmp_interact Compiled with interactive X session management support. 3021xterm_clipboard Compiled with support for xterm clipboard. 3022xterm_save Compiled with support for saving and restoring the 3023 xterm screen. 3024x11 Compiled with X11 support. 3025 3026 *string-match* 3027Matching a pattern in a String 3028 3029A regexp pattern as explained at |pattern| is normally used to find a match in 3030the buffer lines. When a pattern is used to find a match in a String, almost 3031everything works in the same way. The difference is that a String is handled 3032like it is one line. When it contains a "\n" character, this is not seen as a 3033line break for the pattern. It can be matched with a "\n" in the pattern, or 3034with ".". Example: > 3035 :let a = "aaaa\nxxxx" 3036 :echo matchstr(a, "..\n..") 3037 aa 3038 xx 3039 :echo matchstr(a, "a.x") 3040 a 3041 x 3042 3043Don't forget that "^" will only match at the first character of the String and 3044"$" at the last character of the string. They don't match after or before a 3045"\n". 3046 3047============================================================================== 30485. Defining functions *user-functions* 3049 3050New functions can be defined. These can be called just like builtin 3051functions. The function executes a sequence of Ex commands. Normal mode 3052commands can be executed with the |:normal| command. 3053 3054The function name must start with an uppercase letter, to avoid confusion with 3055builtin functions. To prevent from using the same name in different scripts 3056avoid obvious, short names. A good habit is to start the function name with 3057the name of the script, e.g., "HTMLcolor()". 3058 3059It's also possible to use curly braces, see |curly-braces-names|. 3060 3061 *local-function* 3062A function local to a script must start with "s:". A local script function 3063can only be called from within the script and from functions, user commands 3064and autocommands defined in the script. It is also possible to call the 3065function from a mappings defined in the script, but then |<SID>| must be used 3066instead of "s:" when the mapping is expanded outside of the script. 3067 3068 *:fu* *:function* *E128* *E129* *E123* 3069:fu[nction] List all functions and their arguments. 3070 3071:fu[nction] {name} List function {name}. 3072 *E124* *E125* 3073:fu[nction][!] {name}([arguments]) [range] [abort] 3074 Define a new function by the name {name}. The name 3075 must be made of alphanumeric characters and '_', and 3076 must start with a capital or "s:" (see above). 3077 *function-argument* *a:var* 3078 An argument can be defined by giving its name. In the 3079 function this can then be used as "a:name" ("a:" for 3080 argument). 3081 Up to 20 arguments can be given, separated by commas. 3082 Finally, an argument "..." can be specified, which 3083 means that more arguments may be following. In the 3084 function they can be used as "a:1", "a:2", etc. "a:0" 3085 is set to the number of extra arguments (which can be 3086 0). 3087 When not using "...", the number of arguments in a 3088 function call must be equal to the number of named 3089 arguments. When using "...", the number of arguments 3090 may be larger. 3091 It is also possible to define a function without any 3092 arguments. You must still supply the () then. 3093 The body of the function follows in the next lines, 3094 until the matching |:endfunction|. It is allowed to 3095 define another function inside a function body. 3096 *E127* *E122* 3097 When a function by this name already exists and [!] is 3098 not used an error message is given. When [!] is used, 3099 an existing function is silently replaced. Unless it 3100 is currently being executed, that is an error. 3101 *a:firstline* *a:lastline* 3102 When the [range] argument is added, the function is 3103 expected to take care of a range itself. The range is 3104 passed as "a:firstline" and "a:lastline". If [range] 3105 is excluded, ":{range}call" will call the function for 3106 each line in the range, with the cursor on the start 3107 of each line. See |function-range-example|. 3108 When the [abort] argument is added, the function will 3109 abort as soon as an error is detected. 3110 The last used search pattern and the redo command "." 3111 will not be changed by the function. 3112 3113 *:endf* *:endfunction* *E126* *E193* 3114:endf[unction] The end of a function definition. Must be on a line 3115 by its own, without other commands. 3116 3117 *:delf* *:delfunction* *E130* *E131* 3118:delf[unction] {name} Delete function {name}. 3119 3120 *:retu* *:return* *E133* 3121:retu[rn] [expr] Return from a function. When "[expr]" is given, it is 3122 evaluated and returned as the result of the function. 3123 If "[expr]" is not given, the number 0 is returned. 3124 When a function ends without an explicit ":return", 3125 the number 0 is returned. 3126 Note that there is no check for unreachable lines, 3127 thus there is no warning if commands follow ":return". 3128 3129 If the ":return" is used after a |:try| but before the 3130 matching |:finally| (if present), the commands 3131 following the ":finally" up to the matching |:endtry| 3132 are executed first. This process applies to all 3133 nested ":try"s inside the function. The function 3134 returns at the outermost ":endtry". 3135 3136 3137Inside a function variables can be used. These are local variables, which 3138will disappear when the function returns. Global variables need to be 3139accessed with "g:". 3140 3141Example: > 3142 :function Table(title, ...) 3143 : echohl Title 3144 : echo a:title 3145 : echohl None 3146 : let idx = 1 3147 : while idx <= a:0 3148 : echo a:{idx} . ' ' 3149 : let idx = idx + 1 3150 : endwhile 3151 : return idx 3152 :endfunction 3153 3154This function can then be called with: > 3155 let lines = Table("Table", "line1", "line2") 3156 let lines = Table("Empty Table") 3157 3158To return more than one value, pass the name of a global variable: > 3159 :function Compute(n1, n2, divname) 3160 : if a:n2 == 0 3161 : return "fail" 3162 : endif 3163 : let g:{a:divname} = a:n1 / a:n2 3164 : return "ok" 3165 :endfunction 3166 3167This function can then be called with: > 3168 :let success = Compute(13, 1324, "div") 3169 :if success == "ok" 3170 : echo div 3171 :endif 3172 3173An alternative is to return a command that can be executed. This also works 3174with local variables in a calling function. Example: > 3175 :function Foo() 3176 : execute Bar() 3177 : echo "line " . lnum . " column " . col 3178 :endfunction 3179 3180 :function Bar() 3181 : return "let lnum = " . line(".") . " | let col = " . col(".") 3182 :endfunction 3183 3184The names "lnum" and "col" could also be passed as argument to Bar(), to allow 3185the caller to set the names. 3186 3187 *:cal* *:call* *E107* 3188:[range]cal[l] {name}([arguments]) 3189 Call a function. The name of the function and its arguments 3190 are as specified with |:function|. Up to 20 arguments can be 3191 used. 3192 Without a range and for functions that accept a range, the 3193 function is called once. When a range is given the cursor is 3194 positioned at the start of the first line before executing the 3195 function. 3196 When a range is given and the function doesn't handle it 3197 itself, the function is executed for each line in the range, 3198 with the cursor in the first column of that line. The cursor 3199 is left at the last line (possibly moved by the last function 3200 call). The arguments are re-evaluated for each line. Thus 3201 this works: 3202 *function-range-example* > 3203 :function Mynumber(arg) 3204 : echo line(".") . " " . a:arg 3205 :endfunction 3206 :1,5call Mynumber(getline(".")) 3207< 3208 The "a:firstline" and "a:lastline" are defined anyway, they 3209 can be used to do something different at the start or end of 3210 the range. 3211 3212 Example of a function that handles the range itself: > 3213 3214 :function Cont() range 3215 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ ' 3216 :endfunction 3217 :4,8call Cont() 3218< 3219 This function inserts the continuation character "\" in front 3220 of all the lines in the range, except the first one. 3221 3222 *E132* 3223The recursiveness of user functions is restricted with the |'maxfuncdepth'| 3224option. 3225 3226 *autoload-functions* 3227When using many or large functions, it's possible to automatically define them 3228only when they are used. Use the FuncUndefined autocommand event with a 3229pattern that matches the function(s) to be defined. Example: > 3230 3231 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim 3232 3233The file "~/vim/bufnetfuncs.vim" should then define functions that start with 3234"BufNet". Also see |FuncUndefined|. 3235 3236============================================================================== 32376. Curly braces names *curly-braces-names* 3238 3239Wherever you can use a variable, you can use a "curly braces name" variable. 3240This is a regular variable name with one or more expressions wrapped in braces 3241{} like this: > 3242 my_{adjective}_variable 3243 3244When Vim encounters this, it evaluates the expression inside the braces, puts 3245that in place of the expression, and re-interprets the whole as a variable 3246name. So in the above example, if the variable "adjective" was set to 3247"noisy", then the reference would be to "my_noisy_variable", whereas if 3248"adjective" was set to "quiet", then it would be to "my_quiet_variable". 3249 3250One application for this is to create a set of variables governed by an option 3251value. For example, the statement > 3252 echo my_{&background}_message 3253 3254would output the contents of "my_dark_message" or "my_light_message" depending 3255on the current value of 'background'. 3256 3257You can use multiple brace pairs: > 3258 echo my_{adverb}_{adjective}_message 3259..or even nest them: > 3260 echo my_{ad{end_of_word}}_message 3261where "end_of_word" is either "verb" or "jective". 3262 3263However, the expression inside the braces must evaluate to a valid single 3264variable name. e.g. this is invalid: > 3265 :let foo='a + b' 3266 :echo c{foo}d 3267.. since the result of expansion is "ca + bd", which is not a variable name. 3268 3269 *curly-braces-function-names* 3270You can call and define functions by an evaluated name in a similar way. 3271Example: > 3272 :let func_end='whizz' 3273 :call my_func_{func_end}(parameter) 3274 3275This would call the function "my_func_whizz(parameter)". 3276 3277============================================================================== 32787. Commands *expression-commands* 3279 3280:let {var-name} = {expr1} *:let* *E18* 3281 Set internal variable {var-name} to the result of the 3282 expression {expr1}. The variable will get the type 3283 from the {expr}. If {var-name} didn't exist yet, it 3284 is created. 3285 3286:let ${env-name} = {expr1} *:let-environment* *:let-$* 3287 Set environment variable {env-name} to the result of 3288 the expression {expr1}. The type is always String. 3289 3290:let @{reg-name} = {expr1} *:let-register* *:let-@* 3291 Write the result of the expression {expr1} in register 3292 {reg-name}. {reg-name} must be a single letter, and 3293 must be the name of a writable register (see 3294 |registers|). "@@" can be used for the unnamed 3295 register, "@/" for the search pattern. 3296 If the result of {expr1} ends in a <CR> or <NL>, the 3297 register will be linewise, otherwise it will be set to 3298 characterwise. 3299 This can be used to clear the last search pattern: > 3300 :let @/ = "" 3301< This is different from searching for an empty string, 3302 that would match everywhere. 3303 3304:let &{option-name} = {expr1} *:let-option* *:let-star* 3305 Set option {option-name} to the result of the 3306 expression {expr1}. The value is always converted to 3307 the type of the option. 3308 For an option local to a window or buffer the effect 3309 is just like using the |:set| command: both the local 3310 value and the global value is changed. 3311 3312:let &l:{option-name} = {expr1} 3313 Like above, but only set the local value of an option 3314 (if there is one). Works like |:setlocal|. 3315 3316:let &g:{option-name} = {expr1} 3317 Like above, but only set the global value of an option 3318 (if there is one). Works like |:setglobal|. 3319 3320 *E106* 3321:let {var-name} .. List the value of variable {var-name}. Several 3322 variable names may be given. 3323 3324:let List the values of all variables. 3325 3326 *:unlet* *:unl* *E108* 3327:unl[et][!] {var-name} ... 3328 Remove the internal variable {var-name}. Several 3329 variable names can be given, they are all removed. 3330 With [!] no error message is given for non-existing 3331 variables. 3332 3333:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580* 3334:en[dif] Execute the commands until the next matching ":else" 3335 or ":endif" if {expr1} evaluates to non-zero. 3336 3337 From Vim version 4.5 until 5.0, every Ex command in 3338 between the ":if" and ":endif" is ignored. These two 3339 commands were just to allow for future expansions in a 3340 backwards compatible way. Nesting was allowed. Note 3341 that any ":else" or ":elseif" was ignored, the "else" 3342 part was not executed either. 3343 3344 You can use this to remain compatible with older 3345 versions: > 3346 :if version >= 500 3347 : version-5-specific-commands 3348 :endif 3349< The commands still need to be parsed to find the 3350 "endif". Sometimes an older Vim has a problem with a 3351 new command. For example, ":silent" is recognized as 3352 a ":substitute" command. In that case ":execute" can 3353 avoid problems: > 3354 :if version >= 600 3355 : execute "silent 1,$delete" 3356 :endif 3357< 3358 NOTE: The ":append" and ":insert" commands don't work 3359 properly in between ":if" and ":endif". 3360 3361 *:else* *:el* *E581* *E583* 3362:el[se] Execute the commands until the next matching ":else" 3363 or ":endif" if they previously were not being 3364 executed. 3365 3366 *:elseif* *:elsei* *E582* *E584* 3367:elsei[f] {expr1} Short for ":else" ":if", with the addition that there 3368 is no extra ":endif". 3369 3370:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw* 3371 *E170* *E585* *E588* 3372:endw[hile] Repeat the commands between ":while" and ":endwhile", 3373 as long as {expr1} evaluates to non-zero. 3374 When an error is detected from a command inside the 3375 loop, execution continues after the "endwhile". 3376 3377 NOTE: The ":append" and ":insert" commands don't work 3378 properly inside a ":while" loop. 3379 3380 *:continue* *:con* *E586* 3381:con[tinue] When used inside a ":while", jumps back to the 3382 ":while". If it is used after a |:try| inside the 3383 ":while" but before the matching |:finally| (if 3384 present), the commands following the ":finally" up to 3385 the matching |:endtry| are executed first. This 3386 process applies to all nested ":try"s inside the 3387 ":while". The outermost ":endtry" then jumps back to 3388 the ":while". 3389 3390 *:break* *:brea* *E587* 3391:brea[k] When used inside a ":while", skips to the command 3392 after the matching ":endwhile". If it is used after 3393 a |:try| inside the ":while" but before the matching 3394 |:finally| (if present), the commands following the 3395 ":finally" up to the matching |:endtry| are executed 3396 first. This process applies to all nested ":try"s 3397 inside the ":while". The outermost ":endtry" then 3398 jumps to the command after the ":endwhile". 3399 3400:try *:try* *:endt* *:endtry* *E600* *E601* *E602* 3401:endt[ry] Change the error handling for the commands between 3402 ":try" and ":endtry" including everything being 3403 executed across ":source" commands, function calls, 3404 or autocommand invocations. 3405 3406 When an error or interrupt is detected and there is 3407 a |:finally| command following, execution continues 3408 after the ":finally". Otherwise, or when the 3409 ":endtry" is reached thereafter, the next 3410 (dynamically) surrounding ":try" is checked for 3411 a corresponding ":finally" etc. Then the script 3412 processing is terminated. (Whether a function 3413 definition has an "abort" argument does not matter.) 3414 Example: > 3415 :try | edit too much | finally | echo "cleanup" | endtry 3416 :echo "impossible" " not reached, script terminated above 3417< 3418 Moreover, an error or interrupt (dynamically) inside 3419 ":try" and ":endtry" is converted to an exception. It 3420 can be caught as if it were thrown by a |:throw| 3421 command (see |:catch|). In this case, the script 3422 processing is not terminated. 3423 3424 The value "Vim:Interrupt" is used for an interrupt 3425 exception. An error in a Vim command is converted 3426 to a value of the form "Vim({command}):{errmsg}", 3427 other errors are converted to a value of the form 3428 "Vim:{errmsg}". {command} is the full command name, 3429 and {errmsg} is the message that is displayed if the 3430 error exception is not caught, always beginning with 3431 the error number. 3432 Examples: > 3433 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry 3434 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry 3435< 3436 *:cat* *:catch* *E603* *E604* *E605* 3437:cat[ch] /{pattern}/ The following commands until the next ":catch", 3438 |:finally|, or |:endtry| that belongs to the same 3439 |:try| as the ":catch" are executed when an exception 3440 matching {pattern} is being thrown and has not yet 3441 been caught by a previous ":catch". Otherwise, these 3442 commands are skipped. 3443 When {pattern} is omitted all errors are caught. 3444 Examples: > 3445 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C) 3446 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors 3447 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts 3448 :catch /^Vim(write):/ " catch all errors in :write 3449 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123 3450 :catch /my-exception/ " catch user exception 3451 :catch /.*/ " catch everything 3452 :catch " same as /.*/ 3453< 3454 Another character can be used instead of / around the 3455 {pattern}, so long as it does not have a special 3456 meaning (e.g., '|' or '"') and doesn't occur inside 3457 {pattern}. 3458 NOTE: It is not reliable to ":catch" the TEXT of 3459 an error message because it may vary in different 3460 locales. 3461 3462 *:fina* *:finally* *E606* *E607* 3463:fina[lly] The following commands until the matching |:endtry| 3464 are executed whenever the part between the matching 3465 |:try| and the ":finally" is left: either by falling 3466 through to the ":finally" or by a |:continue|, 3467 |:break|, |:finish|, or |:return|, or by an error or 3468 interrupt or exception (see |:throw|). 3469 3470 *:th* *:throw* *E608* 3471:th[row] {expr1} The {expr1} is evaluated and thrown as an exception. 3472 If the ":throw" is used after a |:try| but before the 3473 first corresponding |:catch|, commands are skipped 3474 until the first ":catch" matching {expr1} is reached. 3475 If there is no such ":catch" or if the ":throw" is 3476 used after a ":catch" but before the |:finally|, the 3477 commands following the ":finally" (if present) up to 3478 the matching |:endtry| are executed. If the ":throw" 3479 is after the ":finally", commands up to the ":endtry" 3480 are skipped. At the ":endtry", this process applies 3481 again for the next dynamically surrounding ":try" 3482 (which may be found in a calling function or sourcing 3483 script), until a matching ":catch" has been found. 3484 If the exception is not caught, the command processing 3485 is terminated. 3486 Example: > 3487 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry 3488< 3489 3490 *:ec* *:echo* 3491:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The 3492 first {expr1} starts on a new line. 3493 Also see |:comment|. 3494 Use "\n" to start a new line. Use "\r" to move the 3495 cursor to the first column. 3496 Uses the highlighting set by the |:echohl| command. 3497 Cannot be followed by a comment. 3498 Example: > 3499 :echo "the value of 'shell' is" &shell 3500< A later redraw may make the message disappear again. 3501 To avoid that a command from before the ":echo" causes 3502 a redraw afterwards (redraws are often postponed until 3503 you type something), force a redraw with the |:redraw| 3504 command. Example: > 3505 :new | redraw | echo "there is a new window" 3506< 3507 *:echon* 3508:echon {expr1} .. Echoes each {expr1}, without anything added. Also see 3509 |:comment|. 3510 Uses the highlighting set by the |:echohl| command. 3511 Cannot be followed by a comment. 3512 Example: > 3513 :echon "the value of 'shell' is " &shell 3514< 3515 Note the difference between using ":echo", which is a 3516 Vim command, and ":!echo", which is an external shell 3517 command: > 3518 :!echo % --> filename 3519< The arguments of ":!" are expanded, see |:_%|. > 3520 :!echo "%" --> filename or "filename" 3521< Like the previous example. Whether you see the double 3522 quotes or not depends on your 'shell'. > 3523 :echo % --> nothing 3524< The '%' is an illegal character in an expression. > 3525 :echo "%" --> % 3526< This just echoes the '%' character. > 3527 :echo expand("%") --> filename 3528< This calls the expand() function to expand the '%'. 3529 3530 *:echoh* *:echohl* 3531:echoh[l] {name} Use the highlight group {name} for the following 3532 |:echo|, |:echon| and |:echomsg| commands. Also used 3533 for the |input()| prompt. Example: > 3534 :echohl WarningMsg | echo "Don't panic!" | echohl None 3535< Don't forget to set the group back to "None", 3536 otherwise all following echo's will be highlighted. 3537 3538 *:echom* *:echomsg* 3539:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the 3540 message in the |message-history|. 3541 Spaces are placed between the arguments as with the 3542 |:echo| command. But unprintable characters are 3543 displayed, not interpreted. 3544 Uses the highlighting set by the |:echohl| command. 3545 Example: > 3546 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see." 3547< 3548 *:echoe* *:echoerr* 3549:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the 3550 message in the |message-history|. When used in a 3551 script or function the line number will be added. 3552 Spaces are placed between the arguments as with the 3553 :echo command. When used inside a try conditional, 3554 the message is raised as an error exception instead 3555 (see |try-echoerr|). 3556 Example: > 3557 :echoerr "This script just failed!" 3558< If you just want a highlighted message use |:echohl|. 3559 And to get a beep: > 3560 :exe "normal \<Esc>" 3561< 3562 *:exe* *:execute* 3563:exe[cute] {expr1} .. Executes the string that results from the evaluation 3564 of {expr1} as an Ex command. Multiple arguments are 3565 concatenated, with a space in between. {expr1} is 3566 used as the processed command, command line editing 3567 keys are not recognized. 3568 Cannot be followed by a comment. 3569 Examples: > 3570 :execute "buffer " nextbuf 3571 :execute "normal " count . "w" 3572< 3573 ":execute" can be used to append a command to commands 3574 that don't accept a '|'. Example: > 3575 :execute '!ls' | echo "theend" 3576 3577< ":execute" is also a nice way to avoid having to type 3578 control characters in a Vim script for a ":normal" 3579 command: > 3580 :execute "normal ixxx\<Esc>" 3581< This has an <Esc> character, see |expr-string|. 3582 3583 Note: The executed string may be any command-line, but 3584 you cannot start or end a "while" or "if" command. 3585 Thus this is illegal: > 3586 :execute 'while i > 5' 3587 :execute 'echo "test" | break' 3588< 3589 It is allowed to have a "while" or "if" command 3590 completely in the executed string: > 3591 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile' 3592< 3593 3594 *:comment* 3595 ":execute", ":echo" and ":echon" cannot be followed by 3596 a comment directly, because they see the '"' as the 3597 start of a string. But, you can use '|' followed by a 3598 comment. Example: > 3599 :echo "foo" | "this is a comment 3600 3601============================================================================== 36028. Exception handling *exception-handling* 3603 3604The Vim script language comprises an exception handling feature. This section 3605explains how it can be used in a Vim script. 3606 3607Exceptions may be raised by Vim on an error or on interrupt, see 3608|catch-errors| and |catch-interrupt|. You can also explicitly throw an 3609exception by using the ":throw" command, see |throw-catch|. 3610 3611 3612TRY CONDITIONALS *try-conditionals* 3613 3614Exceptions can be caught or can cause cleanup code to be executed. You can 3615use a try conditional to specify catch clauses (that catch exceptions) and/or 3616a finally clause (to be executed for cleanup). 3617 A try conditional begins with a |:try| command and ends at the matching 3618|:endtry| command. In between, you can use a |:catch| command to start 3619a catch clause, or a |:finally| command to start a finally clause. There may 3620be none or multiple catch clauses, but there is at most one finally clause, 3621which must not be followed by any catch clauses. The lines before the catch 3622clauses and the finally clause is called a try block. > 3623 3624 :try 3625 : ... 3626 : ... TRY BLOCK 3627 : ... 3628 :catch /{pattern}/ 3629 : ... 3630 : ... CATCH CLAUSE 3631 : ... 3632 :catch /{pattern}/ 3633 : ... 3634 : ... CATCH CLAUSE 3635 : ... 3636 :finally 3637 : ... 3638 : ... FINALLY CLAUSE 3639 : ... 3640 :endtry 3641 3642The try conditional allows to watch code for exceptions and to take the 3643appropriate actions. Exceptions from the try block may be caught. Exceptions 3644from the try block and also the catch clauses may cause cleanup actions. 3645 When no exception is thrown during execution of the try block, the control 3646is transferred to the finally clause, if present. After its execution, the 3647script continues with the line following the ":endtry". 3648 When an exception occurs during execution of the try block, the remaining 3649lines in the try block are skipped. The exception is matched against the 3650patterns specified as arguments to the ":catch" commands. The catch clause 3651after the first matching ":catch" is taken, other catch clauses are not 3652executed. The catch clause ends when the next ":catch", ":finally", or 3653":endtry" command is reached - whatever is first. Then, the finally clause 3654(if present) is executed. When the ":endtry" is reached, the script execution 3655continues in the following line as usual. 3656 When an exception that does not match any of the patterns specified by the 3657":catch" commands is thrown in the try block, the exception is not caught by 3658that try conditional and none of the catch clauses is executed. Only the 3659finally clause, if present, is taken. The exception pends during execution of 3660the finally clause. It is resumed at the ":endtry", so that commands after 3661the ":endtry" are not executed and the exception might be caught elsewhere, 3662see |try-nesting|. 3663 When during execution of a catch clause another exception is thrown, the 3664remaining lines in that catch clause are not executed. The new exception is 3665not matched against the patterns in any of the ":catch" commands of the same 3666try conditional and none of its catch clauses is taken. If there is, however, 3667a finally clause, it is executed, and the exception pends during its 3668execution. The commands following the ":endtry" are not executed. The new 3669exception might, however, be caught elsewhere, see |try-nesting|. 3670 When during execution of the finally clause (if present) an exception is 3671thrown, the remaining lines in the finally clause are skipped. If the finally 3672clause has been taken because of an exception from the try block or one of the 3673catch clauses, the original (pending) exception is discarded. The commands 3674following the ":endtry" are not executed, and the exception from the finally 3675clause is propagated and can be caught elsewhere, see |try-nesting|. 3676 3677The finally clause is also executed, when a ":break" or ":continue" for 3678a ":while" loop enclosing the complete try conditional is executed from the 3679try block or a catch clause. Or when a ":return" or ":finish" is executed 3680from the try block or a catch clause of a try conditional in a function or 3681sourced script, respectively. The ":break", ":continue", ":return", or 3682":finish" pends during execution of the finally clause and is resumed when the 3683":endtry" is reached. It is, however, discarded when an exception is thrown 3684from the finally clause. 3685 When a ":break" or ":continue" for a ":while" loop enclosing the complete 3686try conditional or when a ":return" or ":finish" is encountered in the finally 3687clause, the rest of the finally clause is skipped, and the ":break", 3688":continue", ":return" or ":finish" is executed as usual. If the finally 3689clause has been taken because of an exception or an earlier ":break", 3690":continue", ":return", or ":finish" from the try block or a catch clause, 3691this pending exception or command is discarded. 3692 3693For examples see |throw-catch| and |try-finally|. 3694 3695 3696NESTING OF TRY CONDITIONALS *try-nesting* 3697 3698Try conditionals can be nested arbitrarily. That is, a complete try 3699conditional can be put into the try block, a catch clause, or the finally 3700clause of another try conditional. If the inner try conditional does not 3701catch an exception thrown in its try block or throws a new exception from one 3702of its catch clauses or its finally clause, the outer try conditional is 3703checked according to the rules above. If the inner try conditional is in the 3704try block of the outer try conditional, its catch clauses are checked, but 3705otherwise only the finally clause is executed. It does not matter for 3706nesting, whether the inner try conditional is directly contained in the outer 3707one, or whether the outer one sources a script or calls a function containing 3708the inner try conditional. 3709 3710When none of the active try conditionals catches an exception, just their 3711finally clauses are executed. Thereafter, the script processing terminates. 3712An error message is displayed in case of an uncaught exception explicitly 3713thrown by a ":throw" command. For uncaught error and interrupt exceptions 3714implicitly raised by Vim, the error message(s) or interrupt message are shown 3715as usual. 3716 3717For examples see |throw-catch|. 3718 3719 3720EXAMINING EXCEPTION HANDLING CODE *except-examine* 3721 3722Exception handling code can get tricky. If you are in doubt what happens, set 3723'verbose' to 13 or use the ":13verbose" command modifier when sourcing your 3724script file. Then you see when an exception is thrown, discarded, caught, or 3725finished. When using a verbosity level of at least 14, things pending in 3726a finally clause are also shown. This information is also given in debug mode 3727(see |debug-scripts|). 3728 3729 3730THROWING AND CATCHING EXCEPTIONS *throw-catch* 3731 3732You can throw any number or string as an exception. Use the |:throw| command 3733and pass the value to be thrown as argument: > 3734 :throw 4711 3735 :throw "string" 3736< *throw-expression* 3737You can also specify an expression argument. The expression is then evaluated 3738first, and the result is thrown: > 3739 :throw 4705 + strlen("string") 3740 :throw strpart("strings", 0, 6) 3741 3742An exception might be thrown during evaluation of the argument of the ":throw" 3743command. Unless it is caught there, the expression evaluation is abandoned. 3744The ":throw" command then does not throw a new exception. 3745 Example: > 3746 3747 :function! Foo(arg) 3748 : try 3749 : throw a:arg 3750 : catch /foo/ 3751 : endtry 3752 : return 1 3753 :endfunction 3754 : 3755 :function! Bar() 3756 : echo "in Bar" 3757 : return 4710 3758 :endfunction 3759 : 3760 :throw Foo("arrgh") + Bar() 3761 3762This throws "arrgh", and "in Bar" is not displayed since Bar() is not 3763executed. > 3764 :throw Foo("foo") + Bar() 3765however displays "in Bar" and throws 4711. 3766 3767Any other command that takes an expression as argument might also be 3768abandoned by an (uncaught) exception during the expression evaluation. The 3769exception is then propagated to the caller of the command. 3770 Example: > 3771 3772 :if Foo("arrgh") 3773 : echo "then" 3774 :else 3775 : echo "else" 3776 :endif 3777 3778Here neither of "then" or "else" is displayed. 3779 3780 *catch-order* 3781Exceptions can be caught by a try conditional with one or more |:catch| 3782commands, see |try-conditionals|. The values to be caught by each ":catch" 3783command can be specified as a pattern argument. The subsequent catch clause 3784gets executed when a matching exception is caught. 3785 Example: > 3786 3787 :function! Foo(value) 3788 : try 3789 : throw a:value 3790 : catch /^\d\+$/ 3791 : echo "Number thrown" 3792 : catch /.*/ 3793 : echo "String thrown" 3794 : endtry 3795 :endfunction 3796 : 3797 :call Foo(0x1267) 3798 :call Foo('string') 3799 3800The first call to Foo() displays "Number thrown", the second "String thrown". 3801An exception is matched against the ":catch" commands in the order they are 3802specified. Only the first match counts. So you should place the more 3803specific ":catch" first. The following order does not make sense: > 3804 3805 : catch /.*/ 3806 : echo "String thrown" 3807 : catch /^\d\+$/ 3808 : echo "Number thrown" 3809 3810The first ":catch" here matches always, so that the second catch clause is 3811never taken. 3812 3813 *throw-variables* 3814If you catch an exception by a general pattern, you may access the exact value 3815in the variable |v:exception|: > 3816 3817 : catch /^\d\+$/ 3818 : echo "Number thrown. Value is" v:exception 3819 3820You may also be interested where an exception was thrown. This is stored in 3821|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the 3822exception most recently caught as long it is not finished. 3823 Example: > 3824 3825 :function! Caught() 3826 : if v:exception != "" 3827 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint 3828 : else 3829 : echo 'Nothing caught' 3830 : endif 3831 :endfunction 3832 : 3833 :function! Foo() 3834 : try 3835 : try 3836 : try 3837 : throw 4711 3838 : finally 3839 : call Caught() 3840 : endtry 3841 : catch /.*/ 3842 : call Caught() 3843 : throw "oops" 3844 : endtry 3845 : catch /.*/ 3846 : call Caught() 3847 : finally 3848 : call Caught() 3849 : endtry 3850 :endfunction 3851 : 3852 :call Foo() 3853 3854This displays > 3855 3856 Nothing caught 3857 Caught "4711" in function Foo, line 4 3858 Caught "oops" in function Foo, line 10 3859 Nothing caught 3860 3861A practical example: The following command ":LineNumber" displays the line 3862number in the script or function where it has been used: > 3863 3864 :function! LineNumber() 3865 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "") 3866 :endfunction 3867 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry 3868< 3869 *try-nested* 3870An exception that is not caught by a try conditional can be caught by 3871a surrounding try conditional: > 3872 3873 :try 3874 : try 3875 : throw "foo" 3876 : catch /foobar/ 3877 : echo "foobar" 3878 : finally 3879 : echo "inner finally" 3880 : endtry 3881 :catch /foo/ 3882 : echo "foo" 3883 :endtry 3884 3885The inner try conditional does not catch the exception, just its finally 3886clause is executed. The exception is then caught by the outer try 3887conditional. The example displays "inner finally" and then "foo". 3888 3889 *throw-from-catch* 3890You can catch an exception and throw a new one to be caught elsewhere from the 3891catch clause: > 3892 3893 :function! Foo() 3894 : throw "foo" 3895 :endfunction 3896 : 3897 :function! Bar() 3898 : try 3899 : call Foo() 3900 : catch /foo/ 3901 : echo "Caught foo, throw bar" 3902 : throw "bar" 3903 : endtry 3904 :endfunction 3905 : 3906 :try 3907 : call Bar() 3908 :catch /.*/ 3909 : echo "Caught" v:exception 3910 :endtry 3911 3912This displays "Caught foo, throw bar" and then "Caught bar". 3913 3914 *rethrow* 3915There is no real rethrow in the Vim script language, but you may throw 3916"v:exception" instead: > 3917 3918 :function! Bar() 3919 : try 3920 : call Foo() 3921 : catch /.*/ 3922 : echo "Rethrow" v:exception 3923 : throw v:exception 3924 : endtry 3925 :endfunction 3926< *try-echoerr* 3927Note that this method cannot be used to "rethrow" Vim error or interrupt 3928exceptions, because it is not possible to fake Vim internal exceptions. 3929Trying so causes an error exception. You should throw your own exception 3930denoting the situation. If you want to cause a Vim error exception containing 3931the original error exception value, you can use the |:echoerr| command: > 3932 3933 :try 3934 : try 3935 : asdf 3936 : catch /.*/ 3937 : echoerr v:exception 3938 : endtry 3939 :catch /.*/ 3940 : echo v:exception 3941 :endtry 3942 3943This code displays 3944 3945 Vim(echoerr):Vim:E492: Not an editor command: asdf ~ 3946 3947 3948CLEANUP CODE *try-finally* 3949 3950Scripts often change global settings and restore them at their end. If the 3951user however interrupts the script by pressing CTRL-C, the settings remain in 3952an inconsistent state. The same may happen to you in the development phase of 3953a script when an error occurs or you explicitly throw an exception without 3954catching it. You can solve these problems by using a try conditional with 3955a finally clause for restoring the settings. Its execution is guaranteed on 3956normal control flow, on error, on an explicit ":throw", and on interrupt. 3957(Note that errors and interrupts from inside the try conditional are converted 3958to exceptions. When not caught, they terminate the script after the finally 3959clause has been executed.) 3960Example: > 3961 3962 :try 3963 : let s:saved_ts = &ts 3964 : set ts=17 3965 : 3966 : " Do the hard work here. 3967 : 3968 :finally 3969 : let &ts = s:saved_ts 3970 : unlet s:saved_ts 3971 :endtry 3972 3973This method should be used locally whenever a function or part of a script 3974changes global settings which need to be restored on failure or normal exit of 3975that function or script part. 3976 3977 *break-finally* 3978Cleanup code works also when the try block or a catch clause is left by 3979a ":continue", ":break", ":return", or ":finish". 3980 Example: > 3981 3982 :let first = 1 3983 :while 1 3984 : try 3985 : if first 3986 : echo "first" 3987 : let first = 0 3988 : continue 3989 : else 3990 : throw "second" 3991 : endif 3992 : catch /.*/ 3993 : echo v:exception 3994 : break 3995 : finally 3996 : echo "cleanup" 3997 : endtry 3998 : echo "still in while" 3999 :endwhile 4000 :echo "end" 4001 4002This displays "first", "cleanup", "second", "cleanup", and "end". > 4003 4004 :function! Foo() 4005 : try 4006 : return 4711 4007 : finally 4008 : echo "cleanup\n" 4009 : endtry 4010 : echo "Foo still active" 4011 :endfunction 4012 : 4013 :echo Foo() "returned by Foo" 4014 4015This displays "cleanup" and "4711 returned by Foo". You don't need to add an 4016extra ":return" in the finally clause. (Above all, this would override the 4017return value.) 4018 4019 *except-from-finally* 4020Using either of ":continue", ":break", ":return", ":finish", or ":throw" in 4021a finally clause is possible, but not recommended since it abandons the 4022cleanup actions for the try conditional. But, of course, interrupt and error 4023exceptions might get raised from a finally clause. 4024 Example where an error in the finally clause stops an interrupt from 4025working correctly: > 4026 4027 :try 4028 : try 4029 : echo "Press CTRL-C for interrupt" 4030 : while 1 4031 : endwhile 4032 : finally 4033 : unlet novar 4034 : endtry 4035 :catch /novar/ 4036 :endtry 4037 :echo "Script still running" 4038 :sleep 1 4039 4040If you need to put commands that could fail into a finally clause, you should 4041think about catching or ignoring the errors in these commands, see 4042|catch-errors| and |ignore-errors|. 4043 4044 4045CATCHING ERRORS *catch-errors* 4046 4047If you want to catch specific errors, you just have to put the code to be 4048watched in a try block and add a catch clause for the error message. The 4049presence of the try conditional causes all errors to be converted to an 4050exception. No message is displayed and |v:errmsg| is not set then. To find 4051the right pattern for the ":catch" command, you have to know how the format of 4052the error exception is. 4053 Error exceptions have the following format: > 4054 4055 Vim({cmdname}):{errmsg} 4056or > 4057 Vim:{errmsg} 4058 4059{cmdname} is the name of the command that failed; the second form is used when 4060the command name is not known. {errmsg} is the error message usually produced 4061when the error occurs outside try conditionals. It always begins with 4062a capital "E", followed by a two or three-digit error number, a colon, and 4063a space. 4064 4065Examples: 4066 4067The command > 4068 :unlet novar 4069normally produces the error message > 4070 E108: No such variable: "novar" 4071which is converted inside try conditionals to an exception > 4072 Vim(unlet):E108: No such variable: "novar" 4073 4074The command > 4075 :dwim 4076normally produces the error message > 4077 E492: Not an editor command: dwim 4078which is converted inside try conditionals to an exception > 4079 Vim:E492: Not an editor command: dwim 4080 4081You can catch all ":unlet" errors by a > 4082 :catch /^Vim(unlet):/ 4083or all errors for misspelled command names by a > 4084 :catch /^Vim:E492:/ 4085 4086Some error messages may be produced by different commands: > 4087 :function nofunc 4088and > 4089 :delfunction nofunc 4090both produce the error message > 4091 E128: Function name must start with a capital: nofunc 4092which is converted inside try conditionals to an exception > 4093 Vim(function):E128: Function name must start with a capital: nofunc 4094or > 4095 Vim(delfunction):E128: Function name must start with a capital: nofunc 4096respectively. You can catch the error by its number independently on the 4097command that caused it if you use the following pattern: > 4098 :catch /^Vim(\a\+):E128:/ 4099 4100Some commands like > 4101 :let x = novar 4102produce multiple error messages, here: > 4103 E121: Undefined variable: novar 4104 E15: Invalid expression: novar 4105Only the first is used for the exception value, since it is the most specific 4106one (see |except-several-errors|). So you can catch it by > 4107 :catch /^Vim(\a\+):E121:/ 4108 4109You can catch all errors related to the name "nofunc" by > 4110 :catch /\<nofunc\>/ 4111 4112You can catch all Vim errors in the ":write" and ":read" commands by > 4113 :catch /^Vim(\(write\|read\)):E\d\+:/ 4114 4115You can catch all Vim errors by the pattern > 4116 :catch /^Vim\((\a\+)\)\=:E\d\+:/ 4117< 4118 *catch-text* 4119NOTE: You should never catch the error message text itself: > 4120 :catch /No such variable/ 4121only works in the english locale, but not when the user has selected 4122a different language by the |:language| command. It is however helpful to 4123cite the message text in a comment: > 4124 :catch /^Vim(\a\+):E108:/ " No such variable 4125 4126 4127IGNORING ERRORS *ignore-errors* 4128 4129You can ignore errors in a specific Vim command by catching them locally: > 4130 4131 :try 4132 : write 4133 :catch 4134 :endtry 4135 4136But you are strongly recommended NOT to use this simple form, since it could 4137catch more than you want. With the ":write" command, some autocommands could 4138be executed and cause errors not related to writing, for instance: > 4139 4140 :au BufWritePre * unlet novar 4141 4142There could even be such errors you are not responsible for as a script 4143writer: a user of your script might have defined such autocommands. You would 4144then hide the error from the user. 4145 It is much better to use > 4146 4147 :try 4148 : write 4149 :catch /^Vim(write):/ 4150 :endtry 4151 4152which only catches real write errors. So catch only what you'd like to ignore 4153intentionally. 4154 4155For a single command that does not cause execution of autocommands, you could 4156even suppress the conversion of errors to exceptions by the ":silent!" 4157command: > 4158 :silent! nunmap k 4159This works also when a try conditional is active. 4160 4161 4162CATCHING INTERRUPTS *catch-interrupt* 4163 4164When there are active try conditionals, an interrupt (CTRL-C) is converted to 4165the exception "Vim:Interrupt". You can catch it like every exception. The 4166script is not terminated, then. 4167 Example: > 4168 4169 :function! TASK1() 4170 : sleep 10 4171 :endfunction 4172 4173 :function! TASK2() 4174 : sleep 20 4175 :endfunction 4176 4177 :while 1 4178 : let command = input("Type a command: ") 4179 : try 4180 : if command == "" 4181 : continue 4182 : elseif command == "END" 4183 : break 4184 : elseif command == "TASK1" 4185 : call TASK1() 4186 : elseif command == "TASK2" 4187 : call TASK2() 4188 : else 4189 : echo "\nIllegal command:" command 4190 : continue 4191 : endif 4192 : catch /^Vim:Interrupt$/ 4193 : echo "\nCommand interrupted" 4194 : " Caught the interrupt. Continue with next prompt. 4195 : endtry 4196 :endwhile 4197 4198You can interrupt a task here by pressing CTRL-C; the script then asks for 4199a new command. If you press CTRL-C at the prompt, the script is terminated. 4200 4201For testing what happens when CTRL-C would be pressed on a specific line in 4202your script, use the debug mode and execute the |>quit| or |>interrupt| 4203command on that line. See |debug-scripts|. 4204 4205 4206CATCHING ALL *catch-all* 4207 4208The commands > 4209 4210 :catch /.*/ 4211 :catch // 4212 :catch 4213 4214catch everything, error exceptions, interrupt exceptions and exceptions 4215explicitly thrown by the |:throw| command. This is useful at the top level of 4216a script in order to catch unexpected things. 4217 Example: > 4218 4219 :try 4220 : 4221 : " do the hard work here 4222 : 4223 :catch /MyException/ 4224 : 4225 : " handle known problem 4226 : 4227 :catch /^Vim:Interrupt$/ 4228 : echo "Script interrupted" 4229 :catch /.*/ 4230 : echo "Internal error (" . v:exception . ")" 4231 : echo " - occurred at " . v:throwpoint 4232 :endtry 4233 :" end of script 4234 4235Note: Catching all might catch more things than you want. Thus, you are 4236strongly encouraged to catch only for problems that you can really handle by 4237specifying a pattern argument to the ":catch". 4238 Example: Catching all could make it nearly impossible to interrupt a script 4239by pressing CTRL-C: > 4240 4241 :while 1 4242 : try 4243 : sleep 1 4244 : catch 4245 : endtry 4246 :endwhile 4247 4248 4249EXCEPTIONS AND AUTOCOMMANDS *except-autocmd* 4250 4251Exceptions may be used during execution of autocommands. Example: > 4252 4253 :autocmd User x try 4254 :autocmd User x throw "Oops!" 4255 :autocmd User x catch 4256 :autocmd User x echo v:exception 4257 :autocmd User x endtry 4258 :autocmd User x throw "Arrgh!" 4259 :autocmd User x echo "Should not be displayed" 4260 : 4261 :try 4262 : doautocmd User x 4263 :catch 4264 : echo v:exception 4265 :endtry 4266 4267This displays "Oops!" and "Arrgh!". 4268 4269 *except-autocmd-Pre* 4270For some commands, autocommands get executed before the main action of the 4271command takes place. If an exception is thrown and not caught in the sequence 4272of autocommands, the sequence and the command that caused its execution are 4273abandoned and the exception is propagated to the caller of the command. 4274 Example: > 4275 4276 :autocmd BufWritePre * throw "FAIL" 4277 :autocmd BufWritePre * echo "Should not be displayed" 4278 : 4279 :try 4280 : write 4281 :catch 4282 : echo "Caught:" v:exception "from" v:throwpoint 4283 :endtry 4284 4285Here, the ":write" command does not write the file currently being edited (as 4286you can see by checking 'modified'), since the exception from the BufWritePre 4287autocommand abandons the ":write". The exception is then caught and the 4288script displays: > 4289 4290 Caught: FAIL from BufWrite Auto commands for "*" 4291< 4292 *except-autocmd-Post* 4293For some commands, autocommands get executed after the main action of the 4294command has taken place. If this main action fails and the command is inside 4295an active try conditional, the autocommands are skipped and an error exception 4296is thrown that can be caught by the caller of the command. 4297 Example: > 4298 4299 :autocmd BufWritePost * echo "File successfully written!" 4300 : 4301 :try 4302 : write /i/m/p/o/s/s/i/b/l/e 4303 :catch 4304 : echo v:exception 4305 :endtry 4306 4307This just displays: > 4308 4309 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e) 4310 4311If you really need to execute the autocommands even when the main action 4312fails, trigger the event from the catch clause. 4313 Example: > 4314 4315 :autocmd BufWritePre * set noreadonly 4316 :autocmd BufWritePost * set readonly 4317 : 4318 :try 4319 : write /i/m/p/o/s/s/i/b/l/e 4320 :catch 4321 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e 4322 :endtry 4323< 4324You can also use ":silent!": > 4325 4326 :let x = "ok" 4327 :let v:errmsg = "" 4328 :autocmd BufWritePost * if v:errmsg != "" 4329 :autocmd BufWritePost * let x = "after fail" 4330 :autocmd BufWritePost * endif 4331 :try 4332 : silent! write /i/m/p/o/s/s/i/b/l/e 4333 :catch 4334 :endtry 4335 :echo x 4336 4337This displays "after fail". 4338 4339If the main action of the command does not fail, exceptions from the 4340autocommands will be catchable by the caller of the command: > 4341 4342 :autocmd BufWritePost * throw ":-(" 4343 :autocmd BufWritePost * echo "Should not be displayed" 4344 : 4345 :try 4346 : write 4347 :catch 4348 : echo v:exception 4349 :endtry 4350< 4351 *except-autocmd-Cmd* 4352For some commands, the normal action can be replaced by a sequence of 4353autocommands. Exceptions from that sequence will be catchable by the caller 4354of the command. 4355 Example: For the ":write" command, the caller cannot know whether the file 4356had actually been written when the exception occurred. You need to tell it in 4357some way. > 4358 4359 :if !exists("cnt") 4360 : let cnt = 0 4361 : 4362 : autocmd BufWriteCmd * if &modified 4363 : autocmd BufWriteCmd * let cnt = cnt + 1 4364 : autocmd BufWriteCmd * if cnt % 3 == 2 4365 : autocmd BufWriteCmd * throw "BufWriteCmdError" 4366 : autocmd BufWriteCmd * endif 4367 : autocmd BufWriteCmd * write | set nomodified 4368 : autocmd BufWriteCmd * if cnt % 3 == 0 4369 : autocmd BufWriteCmd * throw "BufWriteCmdError" 4370 : autocmd BufWriteCmd * endif 4371 : autocmd BufWriteCmd * echo "File successfully written!" 4372 : autocmd BufWriteCmd * endif 4373 :endif 4374 : 4375 :try 4376 : write 4377 :catch /^BufWriteCmdError$/ 4378 : if &modified 4379 : echo "Error on writing (file contents not changed)" 4380 : else 4381 : echo "Error after writing" 4382 : endif 4383 :catch /^Vim(write):/ 4384 : echo "Error on writing" 4385 :endtry 4386 4387When this script is sourced several times after making changes, it displays 4388first > 4389 File successfully written! 4390then > 4391 Error on writing (file contents not changed) 4392then > 4393 Error after writing 4394etc. 4395 4396 *except-autocmd-ill* 4397You cannot spread a try conditional over autocommands for different events. 4398The following code is ill-formed: > 4399 4400 :autocmd BufWritePre * try 4401 : 4402 :autocmd BufWritePost * catch 4403 :autocmd BufWritePost * echo v:exception 4404 :autocmd BufWritePost * endtry 4405 : 4406 :write 4407 4408 4409EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param* 4410 4411Some programming languages allow to use hierarchies of exception classes or to 4412pass additional information with the object of an exception class. You can do 4413similar things in Vim. 4414 In order to throw an exception from a hierarchy, just throw the complete 4415class name with the components separated by a colon, for instance throw the 4416string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library. 4417 When you want to pass additional information with your exception class, add 4418it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)" 4419for an error when writing "myfile". 4420 With the appropriate patterns in the ":catch" command, you can catch for 4421base classes or derived classes of your hierarchy. Additional information in 4422parentheses can be cut out from |v:exception| with the ":substitute" command. 4423 Example: > 4424 4425 :function! CheckRange(a, func) 4426 : if a:a < 0 4427 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")" 4428 : endif 4429 :endfunction 4430 : 4431 :function! Add(a, b) 4432 : call CheckRange(a:a, "Add") 4433 : call CheckRange(a:b, "Add") 4434 : let c = a:a + a:b 4435 : if c < 0 4436 : throw "EXCEPT:MATHERR:OVERFLOW" 4437 : endif 4438 : return c 4439 :endfunction 4440 : 4441 :function! Div(a, b) 4442 : call CheckRange(a:a, "Div") 4443 : call CheckRange(a:b, "Div") 4444 : if (a:b == 0) 4445 : throw "EXCEPT:MATHERR:ZERODIV" 4446 : endif 4447 : return a:a / a:b 4448 :endfunction 4449 : 4450 :function! Write(file) 4451 : try 4452 : execute "write" a:file 4453 : catch /^Vim(write):/ 4454 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR" 4455 : endtry 4456 :endfunction 4457 : 4458 :try 4459 : 4460 : " something with arithmetics and I/O 4461 : 4462 :catch /^EXCEPT:MATHERR:RANGE/ 4463 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "") 4464 : echo "Range error in" function 4465 : 4466 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV 4467 : echo "Math error" 4468 : 4469 :catch /^EXCEPT:IO/ 4470 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "") 4471 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "") 4472 : if file !~ '^/' 4473 : let file = dir . "/" . file 4474 : endif 4475 : echo 'I/O error for "' . file . '"' 4476 : 4477 :catch /^EXCEPT/ 4478 : echo "Unspecified error" 4479 : 4480 :endtry 4481 4482The exceptions raised by Vim itself (on error or when pressing CTRL-C) use 4483a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself 4484exceptions with the "Vim" prefix; they are reserved for Vim. 4485 Vim error exceptions are parameterized with the name of the command that 4486failed, if known. See |catch-errors|. 4487 4488 4489PECULIARITIES 4490 *except-compat* 4491The exception handling concept requires that the command sequence causing the 4492exception is aborted immediately and control is transferred to finally clauses 4493and/or a catch clause. 4494 4495In the Vim script language there are cases where scripts and functions 4496continue after an error: in functions without the "abort" flag or in a command 4497after ":silent!", control flow goes to the following line, and outside 4498functions, control flow goes to the line following the outermost ":endwhile" 4499or ":endif". On the other hand, errors should be catchable as exceptions 4500(thus, requiring the immediate abortion). 4501 4502This problem has been solved by converting errors to exceptions and using 4503immediate abortion (if not suppressed by ":silent!") only when a try 4504conditional is active. This is no restriction since an (error) exception can 4505be caught only from an active try conditional. If you want an immediate 4506termination without catching the error, just use a try conditional without 4507catch clause. (You can cause cleanup code being executed before termination 4508by specifying a finally clause.) 4509 4510When no try conditional is active, the usual abortion and continuation 4511behavior is used instead of immediate abortion. This ensures compatibility of 4512scripts written for Vim 6.1 and earlier. 4513 4514However, when sourcing an existing script that does not use exception handling 4515commands (or when calling one of its functions) from inside an active try 4516conditional of a new script, you might change the control flow of the existing 4517script on error. You get the immediate abortion on error and can catch the 4518error in the new script. If however the sourced script suppresses error 4519messages by using the ":silent!" command (checking for errors by testing 4520|v:errmsg| if appropriate), its execution path is not changed. The error is 4521not converted to an exception. (See |:silent|.) So the only remaining cause 4522where this happens is for scripts that don't care about errors and produce 4523error messages. You probably won't want to use such code from your new 4524scripts. 4525 4526 *except-syntax-err* 4527Syntax errors in the exception handling commands are never caught by any of 4528the ":catch" commands of the try conditional they belong to. Its finally 4529clauses, however, is executed. 4530 Example: > 4531 4532 :try 4533 : try 4534 : throw 4711 4535 : catch /\(/ 4536 : echo "in catch with syntax error" 4537 : catch 4538 : echo "inner catch-all" 4539 : finally 4540 : echo "inner finally" 4541 : endtry 4542 :catch 4543 : echo 'outer catch-all caught "' . v:exception . '"' 4544 : finally 4545 : echo "outer finally" 4546 :endtry 4547 4548This displays: > 4549 inner finally 4550 outer catch-all caught "Vim(catch):E54: Unmatched \(" 4551 outer finally 4552The original exception is discarded and an error exception is raised, instead. 4553 4554 *except-single-line* 4555The ":try", ":catch", ":finally", and ":endtry" commands can be put on 4556a single line, but then syntax errors may make it difficult to recognize the 4557"catch" line, thus you better avoid this. 4558 Example: > 4559 :try | unlet! foo # | catch | endtry 4560raises an error exception for the trailing characters after the ":unlet!" 4561argument, but does not see the ":catch" and ":endtry" commands, so that the 4562error exception is discarded and the "E488: Trailing characters" message gets 4563displayed. 4564 4565 *except-several-errors* 4566When several errors appear in a single command, the first error message is 4567usually the most specific one and therefor converted to the error exception. 4568 Example: > 4569 echo novar 4570causes > 4571 E121: Undefined variable: novar 4572 E15: Invalid expression: novar 4573The value of the error exception inside try conditionals is: > 4574 Vim(echo):E121: Undefined variable: novar 4575< *except-syntax-error* 4576But when a syntax error is detected after a normal error in the same command, 4577the syntax error is used for the exception being thrown. 4578 Example: > 4579 unlet novar # 4580causes > 4581 E108: No such variable: "novar" 4582 E488: Trailing characters 4583The value of the error exception inside try conditionals is: > 4584 Vim(unlet):E488: Trailing characters 4585This is done because the syntax error might change the execution path in a way 4586not intended by the user. Example: > 4587 try 4588 try | unlet novar # | catch | echo v:exception | endtry 4589 catch /.*/ 4590 echo "outer catch:" v:exception 4591 endtry 4592This displays "outer catch: Vim(unlet):E488: Trailing characters", and then 4593a "E600: Missing :endtry" error message is given, see |except-single-line|. 4594 4595============================================================================== 45969. Examples *eval-examples* 4597 4598Printing in Hex ~ 4599> 4600 :" The function Nr2Hex() returns the Hex string of a number. 4601 :func Nr2Hex(nr) 4602 : let n = a:nr 4603 : let r = "" 4604 : while n 4605 : let r = '0123456789ABCDEF'[n % 16] . r 4606 : let n = n / 16 4607 : endwhile 4608 : return r 4609 :endfunc 4610 4611 :" The function String2Hex() converts each character in a string to a two 4612 :" character Hex string. 4613 :func String2Hex(str) 4614 : let out = '' 4615 : let ix = 0 4616 : while ix < strlen(a:str) 4617 : let out = out . Nr2Hex(char2nr(a:str[ix])) 4618 : let ix = ix + 1 4619 : endwhile 4620 : return out 4621 :endfunc 4622 4623Example of its use: > 4624 :echo Nr2Hex(32) 4625result: "20" > 4626 :echo String2Hex("32") 4627result: "3332" 4628 4629 4630Sorting lines (by Robert Webb) ~ 4631 4632Here is a Vim script to sort lines. Highlight the lines in Vim and type 4633":Sort". This doesn't call any external programs so it'll work on any 4634platform. The function Sort() actually takes the name of a comparison 4635function as its argument, like qsort() does in C. So you could supply it 4636with different comparison functions in order to sort according to date etc. 4637> 4638 :" Function for use with Sort(), to compare two strings. 4639 :func! Strcmp(str1, str2) 4640 : if (a:str1 < a:str2) 4641 : return -1 4642 : elseif (a:str1 > a:str2) 4643 : return 1 4644 : else 4645 : return 0 4646 : endif 4647 :endfunction 4648 4649 :" Sort lines. SortR() is called recursively. 4650 :func! SortR(start, end, cmp) 4651 : if (a:start >= a:end) 4652 : return 4653 : endif 4654 : let partition = a:start - 1 4655 : let middle = partition 4656 : let partStr = getline((a:start + a:end) / 2) 4657 : let i = a:start 4658 : while (i <= a:end) 4659 : let str = getline(i) 4660 : exec "let result = " . a:cmp . "(str, partStr)" 4661 : if (result <= 0) 4662 : " Need to put it before the partition. Swap lines i and partition. 4663 : let partition = partition + 1 4664 : if (result == 0) 4665 : let middle = partition 4666 : endif 4667 : if (i != partition) 4668 : let str2 = getline(partition) 4669 : call setline(i, str2) 4670 : call setline(partition, str) 4671 : endif 4672 : endif 4673 : let i = i + 1 4674 : endwhile 4675 4676 : " Now we have a pointer to the "middle" element, as far as partitioning 4677 : " goes, which could be anywhere before the partition. Make sure it is at 4678 : " the end of the partition. 4679 : if (middle != partition) 4680 : let str = getline(middle) 4681 : let str2 = getline(partition) 4682 : call setline(middle, str2) 4683 : call setline(partition, str) 4684 : endif 4685 : call SortR(a:start, partition - 1, a:cmp) 4686 : call SortR(partition + 1, a:end, a:cmp) 4687 :endfunc 4688 4689 :" To Sort a range of lines, pass the range to Sort() along with the name of a 4690 :" function that will compare two lines. 4691 :func! Sort(cmp) range 4692 : call SortR(a:firstline, a:lastline, a:cmp) 4693 :endfunc 4694 4695 :" :Sort takes a range of lines and sorts them. 4696 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp") 4697< 4698 *sscanf* 4699There is no sscanf() function in Vim. If you need to extract parts from a 4700line, you can use matchstr() and substitute() to do it. This example shows 4701how to get the file name, line number and column number out of a line like 4702"foobar.txt, 123, 45". > 4703 :" Set up the match bit 4704 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)' 4705 :"get the part matching the whole expression 4706 :let l = matchstr(line, mx) 4707 :"get each item out of the match 4708 :let file = substitute(l, mx, '\1', '') 4709 :let lnum = substitute(l, mx, '\2', '') 4710 :let col = substitute(l, mx, '\3', '') 4711 4712The input is in the variable "line", the results in the variables "file", 4713"lnum" and "col". (idea from Michael Geddes) 4714 4715============================================================================== 471610. No +eval feature *no-eval-feature* 4717 4718When the |+eval| feature was disabled at compile time, none of the expression 4719evaluation commands are available. To prevent this from causing Vim scripts 4720to generate all kinds of errors, the ":if" and ":endif" commands are still 4721recognized, though the argument of the ":if" and everything between the ":if" 4722and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but 4723only if the commands are at the start of the line. The ":else" command is not 4724recognized. 4725 4726Example of how to avoid executing commands when the |+eval| feature is 4727missing: > 4728 4729 :if 1 4730 : echo "Expression evaluation is compiled in" 4731 :else 4732 : echo "You will _never_ see this message" 4733 :endif 4734 4735============================================================================== 473611. The sandbox *eval-sandbox* *sandbox* *E48* 4737 4738The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext' 4739options are evaluated in a sandbox. This means that you are protected from 4740these expressions having nasty side effects. This gives some safety for when 4741these options are set from a modeline. It is also used when the command from 4742a tags file is executed. 4743The sandbox is also used for the |:sandbox| command. 4744 4745These items are not allowed in the sandbox: 4746 - changing the buffer text 4747 - defining or changing mapping, autocommands, functions, user commands 4748 - setting certain options (see |option-summary|) 4749 - executing a shell command 4750 - reading or writing a file 4751 - jumping to another buffer or editing a file 4752This is not guaranteed 100% secure, but it should block most attacks. 4753 4754 *:san* *:sandbox* 4755:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an 4756 option that may have been set from a modeline, e.g. 4757 'foldexpr'. 4758 4759 4760 vim:tw=78:ts=8:ft=help:norl: 4761