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