comparison runtime/doc/eval.txt @ 7:3fc0f57ecb91 v7.0001

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