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