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