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