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