blob: e71380e0f15c28be7f0fae257a6ecd61cf0361af [file] [log] [blame]
Bram Moolenaar12805862005-01-05 22:16:17 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Jan 05
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Expression evaluation *expression* *expr* *E15* *eval*
8
9Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|.
10
11Note: Expression evaluation can be disabled at compile time. If this has been
12done, the features in this document are not available. See |+eval| and the
13last chapter below.
14
151. Variables |variables|
162. Expression syntax |expression-syntax|
173. Internal variable |internal-variables|
184. Builtin Functions |functions|
195. Defining functions |user-functions|
206. Curly braces names |curly-braces-names|
217. Commands |expression-commands|
228. Exception handling |exception-handling|
239. Examples |eval-examples|
2410. No +eval feature |no-eval-feature|
2511. The sandbox |eval-sandbox|
26
27{Vi does not have any of these commands}
28
29==============================================================================
301. Variables *variables*
31
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
Bram Moolenaar12805862005-01-05 22:16:17 +00002777 List "[item, item]" form
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002778
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 *strlen()*
2780strlen({expr}) The result is a Number, which is the length of the String
2781 {expr} in bytes. If you want to count the number of
2782 multi-byte characters use something like this: >
2783
2784 :let len = strlen(substitute(str, ".", "x", "g"))
2785
2786< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002787 If the argument is a Number it is first converted to a String.
2788 For other types an error is given.
2789 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790
2791strpart({src}, {start}[, {len}]) *strpart()*
2792 The result is a String, which is part of {src}, starting from
2793 byte {start}, with the length {len}.
2794 When non-existing bytes are included, this doesn't result in
2795 an error, the bytes are simply omitted.
2796 If {len} is missing, the copy continues from {start} till the
2797 end of the {src}. >
2798 strpart("abcdefg", 3, 2) == "de"
2799 strpart("abcdefg", -2, 4) == "ab"
2800 strpart("abcdefg", 5, 4) == "fg"
2801 strpart("abcdefg", 3) == "defg"
2802< Note: To get the first character, {start} must be 0. For
2803 example, to get three bytes under and after the cursor: >
2804 strpart(getline(line(".")), col(".") - 1, 3)
2805<
2806strridx({haystack}, {needle}) *strridx()*
2807 The result is a Number, which gives the index in {haystack} of
2808 the last occurrence of the String {needle} in the String
2809 {haystack}. The search is done case-sensitive. For advanced
2810 searches use |match()|.
2811 If the {needle} does not occur in {haystack} it returns -1.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002812 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 See also |stridx()|. Examples: >
2814 :echo strridx("an angry armadillo", "an") 3
2815<
2816strtrans({expr}) *strtrans()*
2817 The result is a String, which is {expr} with all unprintable
2818 characters translated into printable characters |'isprint'|.
2819 Like they are shown in a window. Example: >
2820 echo strtrans(@a)
2821< This displays a newline in register a as "^@" instead of
2822 starting a new line.
2823
2824submatch({nr}) *submatch()*
2825 Only for an expression in a |:substitute| command. Returns
2826 the {nr}'th submatch of the matched text. When {nr} is 0
2827 the whole matched text is returned.
2828 Example: >
2829 :s/\d\+/\=submatch(0) + 1/
2830< This finds the first number in the line and adds one to it.
2831 A line break is included as a newline character.
2832
2833substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
2834 The result is a String, which is a copy of {expr}, in which
2835 the first match of {pat} is replaced with {sub}. This works
2836 like the ":substitute" command (without any flags). But the
2837 matching with {pat} is always done like the 'magic' option is
2838 set and 'cpoptions' is empty (to make scripts portable).
2839 See |string-match| for how {pat} is used.
2840 And a "~" in {sub} is not replaced with the previous {sub}.
2841 Note that some codes in {sub} have a special meaning
2842 |sub-replace-special|. For example, to replace something with
2843 "\n" (two characters), use "\\\\n" or '\\n'.
2844 When {pat} does not match in {expr}, {expr} is returned
2845 unmodified.
2846 When {flags} is "g", all matches of {pat} in {expr} are
2847 replaced. Otherwise {flags} should be "".
2848 Example: >
2849 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
2850< This removes the last component of the 'path' option. >
2851 :echo substitute("testing", ".*", "\\U\\0", "")
2852< results in "TESTING".
2853
Bram Moolenaar47136d72004-10-12 20:02:24 +00002854synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00002856 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 The syntax ID can be used with |synIDattr()| and
2858 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00002859 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 line.
2861 When {trans} is non-zero, transparent items are reduced to the
2862 item that they reveal. This is useful when wanting to know
2863 the effective color. When {trans} is zero, the transparent
2864 item is returned. This is useful when wanting to know which
2865 syntax item is effective (e.g. inside parens).
2866 Warning: This function can be very slow. Best speed is
2867 obtained by going through the file in forward direction.
2868
2869 Example (echoes the name of the syntax item under the cursor): >
2870 :echo synIDattr(synID(line("."), col("."), 1), "name")
2871<
2872synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
2873 The result is a String, which is the {what} attribute of
2874 syntax ID {synID}. This can be used to obtain information
2875 about a syntax item.
2876 {mode} can be "gui", "cterm" or "term", to get the attributes
2877 for that mode. When {mode} is omitted, or an invalid value is
2878 used, the attributes for the currently active highlighting are
2879 used (GUI, cterm or term).
2880 Use synIDtrans() to follow linked highlight groups.
2881 {what} result
2882 "name" the name of the syntax item
2883 "fg" foreground color (GUI: color name used to set
2884 the color, cterm: color number as a string,
2885 term: empty string)
2886 "bg" background color (like "fg")
2887 "fg#" like "fg", but for the GUI and the GUI is
2888 running the name in "#RRGGBB" form
2889 "bg#" like "fg#" for "bg"
2890 "bold" "1" if bold
2891 "italic" "1" if italic
2892 "reverse" "1" if reverse
2893 "inverse" "1" if inverse (= reverse)
2894 "underline" "1" if underlined
2895
2896 Example (echoes the color of the syntax item under the
2897 cursor): >
2898 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
2899<
2900synIDtrans({synID}) *synIDtrans()*
2901 The result is a Number, which is the translated syntax ID of
2902 {synID}. This is the syntax group ID of what is being used to
2903 highlight the character. Highlight links given with
2904 ":highlight link" are followed.
2905
Bram Moolenaarc0197e22004-09-13 20:26:32 +00002906system({expr} [, {input}]) *system()* *E677*
2907 Get the output of the shell command {expr}.
2908 When {input} is given, this string is written to a file and
2909 passed as stdin to the command. The string is written as-is,
2910 you need to take care of using the correct line separators
2911 yourself.
2912 Note: newlines in {expr} may cause the command to fail. The
2913 characters in 'shellquote' and 'shellxquote' may also cause
2914 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 This is not to be used for interactive commands.
2916 The result is a String. Example: >
2917
2918 :let files = system("ls")
2919
2920< To make the result more system-independent, the shell output
2921 is filtered to replace <CR> with <NL> for Macintosh, and
2922 <CR><NL> with <NL> for DOS-like systems.
2923 The command executed is constructed using several options:
2924 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
2925 ({tmp} is an automatically generated file name).
2926 For Unix and OS/2 braces are put around {expr} to allow for
2927 concatenated commands.
2928
2929 The resulting error code can be found in |v:shell_error|.
2930 This function will fail in |restricted-mode|.
2931 Unlike ":!cmd" there is no automatic check for changed files.
2932 Use |:checktime| to force a check.
2933
2934tempname() *tempname()* *temp-file-name*
2935 The result is a String, which is the name of a file that
2936 doesn't exist. It can be used for a temporary file. The name
2937 is different for at least 26 consecutive calls. Example: >
2938 :let tmpfile = tempname()
2939 :exe "redir > " . tmpfile
2940< For Unix, the file will be in a private directory (only
2941 accessible by the current user) to avoid security problems
2942 (e.g., a symlink attack or other people reading your file).
2943 When Vim exits the directory and all files in it are deleted.
2944 For MS-Windows forward slashes are used when the 'shellslash'
2945 option is set or when 'shellcmdflag' starts with '-'.
2946
2947tolower({expr}) *tolower()*
2948 The result is a copy of the String given, with all uppercase
2949 characters turned into lowercase (just like applying |gu| to
2950 the string).
2951
2952toupper({expr}) *toupper()*
2953 The result is a copy of the String given, with all lowercase
2954 characters turned into uppercase (just like applying |gU| to
2955 the string).
2956
Bram Moolenaar8299df92004-07-10 09:47:34 +00002957tr({src}, {fromstr}, {tostr}) *tr()*
2958 The result is a copy of the {src} string with all characters
2959 which appear in {fromstr} replaced by the character in that
2960 position in the {tostr} string. Thus the first character in
2961 {fromstr} is translated into the first character in {tostr}
2962 and so on. Exactly like the unix "tr" command.
2963 This code also deals with multibyte characters properly.
2964
2965 Examples: >
2966 echo tr("hello there", "ht", "HT")
2967< returns "Hello THere" >
2968 echo tr("<blob>", "<>", "{}")
2969< returns "{blob}"
2970
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971type({expr}) *type()*
2972 The result is a Number:
2973 0 if {expr} has the type Number
2974 1 if {expr} has the type String
2975
2976virtcol({expr}) *virtcol()*
2977 The result is a Number, which is the screen column of the file
2978 position given with {expr}. That is, the last screen position
2979 occupied by the character at that position, when the screen
2980 would be of unlimited width. When there is a <Tab> at the
2981 position, the returned Number will be the column at the end of
2982 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
2983 set to 8, it returns 8.
2984 For the byte position use |col()|.
2985 When Virtual editing is active in the current mode, a position
2986 beyond the end of the line can be returned. |'virtualedit'|
2987 The accepted positions are:
2988 . the cursor position
2989 $ the end of the cursor line (the result is the
2990 number of displayed characters in the cursor line
2991 plus one)
2992 'x position of mark x (if the mark is not set, 0 is
2993 returned)
2994 Note that only marks in the current file can be used.
2995 Examples: >
2996 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
2997 virtcol("$") with text "foo^Lbar", returns 9
2998 virtcol("'t") with text " there", with 't at 'h', returns 6
2999< The first column is 1. 0 is returned for an error.
3000
3001visualmode([expr]) *visualmode()*
3002 The result is a String, which describes the last Visual mode
3003 used. Initially it returns an empty string, but once Visual
3004 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
3005 single CTRL-V character) for character-wise, line-wise, or
3006 block-wise Visual mode respectively.
3007 Example: >
3008 :exe "normal " . visualmode()
3009< This enters the same Visual mode as before. It is also useful
3010 in scripts if you wish to act differently depending on the
3011 Visual mode that was used.
3012
3013 If an expression is supplied that results in a non-zero number
3014 or a non-empty string, then the Visual mode will be cleared
3015 and the old value is returned. Note that " " and "0" are also
3016 non-empty strings, thus cause the mode to be cleared.
3017
3018 *winbufnr()*
3019winbufnr({nr}) The result is a Number, which is the number of the buffer
3020 associated with window {nr}. When {nr} is zero, the number of
3021 the buffer in the current window is returned. When window
3022 {nr} doesn't exist, -1 is returned.
3023 Example: >
3024 :echo "The file in the current window is " . bufname(winbufnr(0))
3025<
3026 *wincol()*
3027wincol() The result is a Number, which is the virtual column of the
3028 cursor in the window. This is counting screen cells from the
3029 left side of the window. The leftmost column is one.
3030
3031winheight({nr}) *winheight()*
3032 The result is a Number, which is the height of window {nr}.
3033 When {nr} is zero, the height of the current window is
3034 returned. When window {nr} doesn't exist, -1 is returned.
3035 An existing window always has a height of zero or more.
3036 Examples: >
3037 :echo "The current window has " . winheight(0) . " lines."
3038<
3039 *winline()*
3040winline() The result is a Number, which is the screen line of the cursor
3041 in the window. This is counting screen lines from the top of
3042 the window. The first line is one.
3043
3044 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003045winnr([{arg}]) The result is a Number, which is the number of the current
3046 window. The top window has number 1.
3047 When the optional argument is "$", the number of the
3048 last window is returnd (the window count).
3049 When the optional argument is "#", the number of the last
3050 accessed window is returned (where |CTRL-W_p| goes to).
3051 If there is no previous window 0 is returned.
3052 The number can be used with |CTRL-W_w| and ":wincmd w"
3053 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
3055 *winrestcmd()*
3056winrestcmd() Returns a sequence of |:resize| commands that should restore
3057 the current window sizes. Only works properly when no windows
3058 are opened or closed and the current window is unchanged.
3059 Example: >
3060 :let cmd = winrestcmd()
3061 :call MessWithWindowSizes()
3062 :exe cmd
3063
3064winwidth({nr}) *winwidth()*
3065 The result is a Number, which is the width of window {nr}.
3066 When {nr} is zero, the width of the current window is
3067 returned. When window {nr} doesn't exist, -1 is returned.
3068 An existing window always has a width of zero or more.
3069 Examples: >
3070 :echo "The current window has " . winwidth(0) . " columns."
3071 :if winwidth(0) <= 50
3072 : exe "normal 50\<C-W>|"
3073 :endif
3074<
3075
3076 *feature-list*
3077There are three types of features:
30781. Features that are only supported when they have been enabled when Vim
3079 was compiled |+feature-list|. Example: >
3080 :if has("cindent")
30812. Features that are only supported when certain conditions have been met.
3082 Example: >
3083 :if has("gui_running")
3084< *has-patch*
30853. Included patches. First check |v:version| for the version of Vim.
3086 Then the "patch123" feature means that patch 123 has been included for
3087 this version. Example (checking version 6.2.148 or later): >
3088 :if v:version > 602 || v:version == 602 && has("patch148")
3089
3090all_builtin_terms Compiled with all builtin terminals enabled.
3091amiga Amiga version of Vim.
3092arabic Compiled with Arabic support |Arabic|.
3093arp Compiled with ARP support (Amiga).
3094autocmd Compiled with autocommands support.
3095balloon_eval Compiled with |balloon-eval| support.
3096beos BeOS version of Vim.
3097browse Compiled with |:browse| support, and browse() will
3098 work.
3099builtin_terms Compiled with some builtin terminals.
3100byte_offset Compiled with support for 'o' in 'statusline'
3101cindent Compiled with 'cindent' support.
3102clientserver Compiled with remote invocation support |clientserver|.
3103clipboard Compiled with 'clipboard' support.
3104cmdline_compl Compiled with |cmdline-completion| support.
3105cmdline_hist Compiled with |cmdline-history| support.
3106cmdline_info Compiled with 'showcmd' and 'ruler' support.
3107comments Compiled with |'comments'| support.
3108cryptv Compiled with encryption support |encryption|.
3109cscope Compiled with |cscope| support.
3110compatible Compiled to be very Vi compatible.
3111debug Compiled with "DEBUG" defined.
3112dialog_con Compiled with console dialog support.
3113dialog_gui Compiled with GUI dialog support.
3114diff Compiled with |vimdiff| and 'diff' support.
3115digraphs Compiled with support for digraphs.
3116dnd Compiled with support for the "~ register |quote_~|.
3117dos32 32 bits DOS (DJGPP) version of Vim.
3118dos16 16 bits DOS version of Vim.
3119ebcdic Compiled on a machine with ebcdic character set.
3120emacs_tags Compiled with support for Emacs tags.
3121eval Compiled with expression evaluation support. Always
3122 true, of course!
3123ex_extra Compiled with extra Ex commands |+ex_extra|.
3124extra_search Compiled with support for |'incsearch'| and
3125 |'hlsearch'|
3126farsi Compiled with Farsi support |farsi|.
3127file_in_path Compiled with support for |gf| and |<cfile>|
3128find_in_path Compiled with support for include file searches
3129 |+find_in_path|.
3130fname_case Case in file names matters (for Amiga, MS-DOS, and
3131 Windows this is not present).
3132folding Compiled with |folding| support.
3133footer Compiled with GUI footer support. |gui-footer|
3134fork Compiled to use fork()/exec() instead of system().
3135gettext Compiled with message translation |multi-lang|
3136gui Compiled with GUI enabled.
3137gui_athena Compiled with Athena GUI.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003138gui_beos Compiled with BeOS GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139gui_gtk Compiled with GTK+ GUI (any version).
3140gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00003141gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142gui_mac Compiled with Macintosh GUI.
3143gui_motif Compiled with Motif GUI.
3144gui_photon Compiled with Photon GUI.
3145gui_win32 Compiled with MS Windows Win32 GUI.
3146gui_win32s idem, and Win32s system being used (Windows 3.1)
3147gui_running Vim is running in the GUI, or it will start soon.
3148hangul_input Compiled with Hangul input support. |hangul|
3149iconv Can use iconv() for conversion.
3150insert_expand Compiled with support for CTRL-X expansion commands in
3151 Insert mode.
3152jumplist Compiled with |jumplist| support.
3153keymap Compiled with 'keymap' support.
3154langmap Compiled with 'langmap' support.
3155libcall Compiled with |libcall()| support.
3156linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
3157 support.
3158lispindent Compiled with support for lisp indenting.
3159listcmds Compiled with commands for the buffer list |:files|
3160 and the argument list |arglist|.
3161localmap Compiled with local mappings and abbr. |:map-local|
3162mac Macintosh version of Vim.
3163macunix Macintosh version of Vim, using Unix files (OS-X).
3164menu Compiled with support for |:menu|.
3165mksession Compiled with support for |:mksession|.
3166modify_fname Compiled with file name modifiers. |filename-modifiers|
3167mouse Compiled with support mouse.
3168mouseshape Compiled with support for 'mouseshape'.
3169mouse_dec Compiled with support for Dec terminal mouse.
3170mouse_gpm Compiled with support for gpm (Linux console mouse)
3171mouse_netterm Compiled with support for netterm mouse.
3172mouse_pterm Compiled with support for qnx pterm mouse.
3173mouse_xterm Compiled with support for xterm mouse.
3174multi_byte Compiled with support for editing Korean et al.
3175multi_byte_ime Compiled with support for IME input method.
3176multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00003177mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00003179netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180ole Compiled with OLE automation support for Win32.
3181os2 OS/2 version of Vim.
3182osfiletype Compiled with support for osfiletypes |+osfiletype|
3183path_extra Compiled with up/downwards search in 'path' and 'tags'
3184perl Compiled with Perl interface.
3185postscript Compiled with PostScript file printing.
3186printer Compiled with |:hardcopy| support.
3187python Compiled with Python interface.
3188qnx QNX version of Vim.
3189quickfix Compiled with |quickfix| support.
3190rightleft Compiled with 'rightleft' support.
3191ruby Compiled with Ruby interface |ruby|.
3192scrollbind Compiled with 'scrollbind' support.
3193showcmd Compiled with 'showcmd' support.
3194signs Compiled with |:sign| support.
3195smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003196sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197statusline Compiled with support for 'statusline', 'rulerformat'
3198 and special formats of 'titlestring' and 'iconstring'.
3199sun_workshop Compiled with support for Sun |workshop|.
3200syntax Compiled with syntax highlighting support.
3201syntax_items There are active syntax highlighting items for the
3202 current buffer.
3203system Compiled to use system() instead of fork()/exec().
3204tag_binary Compiled with binary searching in tags files
3205 |tag-binary-search|.
3206tag_old_static Compiled with support for old static tags
3207 |tag-old-static|.
3208tag_any_white Compiled with support for any white characters in tags
3209 files |tag-any-white|.
3210tcl Compiled with Tcl interface.
3211terminfo Compiled with terminfo instead of termcap.
3212termresponse Compiled with support for |t_RV| and |v:termresponse|.
3213textobjects Compiled with support for |text-objects|.
3214tgetent Compiled with tgetent support, able to use a termcap
3215 or terminfo file.
3216title Compiled with window title support |'title'|.
3217toolbar Compiled with support for |gui-toolbar|.
3218unix Unix version of Vim.
3219user_commands User-defined commands.
3220viminfo Compiled with viminfo support.
3221vim_starting True while initial source'ing takes place.
3222vertsplit Compiled with vertically split windows |:vsplit|.
3223virtualedit Compiled with 'virtualedit' option.
3224visual Compiled with Visual mode.
3225visualextra Compiled with extra Visual mode commands.
3226 |blockwise-operators|.
3227vms VMS version of Vim.
3228vreplace Compiled with |gR| and |gr| commands.
3229wildignore Compiled with 'wildignore' option.
3230wildmenu Compiled with 'wildmenu' option.
3231windows Compiled with support for more than one window.
3232winaltkeys Compiled with 'winaltkeys' option.
3233win16 Win16 version of Vim (MS-Windows 3.1).
3234win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
3235win64 Win64 version of Vim (MS-Windows 64 bit).
3236win32unix Win32 version of Vim, using Unix files (Cygwin)
3237win95 Win32 version for MS-Windows 95/98/ME.
3238writebackup Compiled with 'writebackup' default on.
3239xfontset Compiled with X fontset support |xfontset|.
3240xim Compiled with X input method support |xim|.
3241xsmp Compiled with X session management support.
3242xsmp_interact Compiled with interactive X session management support.
3243xterm_clipboard Compiled with support for xterm clipboard.
3244xterm_save Compiled with support for saving and restoring the
3245 xterm screen.
3246x11 Compiled with X11 support.
3247
3248 *string-match*
3249Matching a pattern in a String
3250
3251A regexp pattern as explained at |pattern| is normally used to find a match in
3252the buffer lines. When a pattern is used to find a match in a String, almost
3253everything works in the same way. The difference is that a String is handled
3254like it is one line. When it contains a "\n" character, this is not seen as a
3255line break for the pattern. It can be matched with a "\n" in the pattern, or
3256with ".". Example: >
3257 :let a = "aaaa\nxxxx"
3258 :echo matchstr(a, "..\n..")
3259 aa
3260 xx
3261 :echo matchstr(a, "a.x")
3262 a
3263 x
3264
3265Don't forget that "^" will only match at the first character of the String and
3266"$" at the last character of the string. They don't match after or before a
3267"\n".
3268
3269==============================================================================
32705. Defining functions *user-functions*
3271
3272New functions can be defined. These can be called just like builtin
3273functions. The function executes a sequence of Ex commands. Normal mode
3274commands can be executed with the |:normal| command.
3275
3276The function name must start with an uppercase letter, to avoid confusion with
3277builtin functions. To prevent from using the same name in different scripts
3278avoid obvious, short names. A good habit is to start the function name with
3279the name of the script, e.g., "HTMLcolor()".
3280
3281It's also possible to use curly braces, see |curly-braces-names|.
3282
3283 *local-function*
3284A function local to a script must start with "s:". A local script function
3285can only be called from within the script and from functions, user commands
3286and autocommands defined in the script. It is also possible to call the
3287function from a mappings defined in the script, but then |<SID>| must be used
3288instead of "s:" when the mapping is expanded outside of the script.
3289
3290 *:fu* *:function* *E128* *E129* *E123*
3291:fu[nction] List all functions and their arguments.
3292
3293:fu[nction] {name} List function {name}.
3294 *E124* *E125*
3295:fu[nction][!] {name}([arguments]) [range] [abort]
3296 Define a new function by the name {name}. The name
3297 must be made of alphanumeric characters and '_', and
3298 must start with a capital or "s:" (see above).
3299 *function-argument* *a:var*
3300 An argument can be defined by giving its name. In the
3301 function this can then be used as "a:name" ("a:" for
3302 argument).
3303 Up to 20 arguments can be given, separated by commas.
3304 Finally, an argument "..." can be specified, which
3305 means that more arguments may be following. In the
3306 function they can be used as "a:1", "a:2", etc. "a:0"
3307 is set to the number of extra arguments (which can be
3308 0).
3309 When not using "...", the number of arguments in a
3310 function call must be equal to the number of named
3311 arguments. When using "...", the number of arguments
3312 may be larger.
3313 It is also possible to define a function without any
3314 arguments. You must still supply the () then.
3315 The body of the function follows in the next lines,
3316 until the matching |:endfunction|. It is allowed to
3317 define another function inside a function body.
3318 *E127* *E122*
3319 When a function by this name already exists and [!] is
3320 not used an error message is given. When [!] is used,
3321 an existing function is silently replaced. Unless it
3322 is currently being executed, that is an error.
3323 *a:firstline* *a:lastline*
3324 When the [range] argument is added, the function is
3325 expected to take care of a range itself. The range is
3326 passed as "a:firstline" and "a:lastline". If [range]
3327 is excluded, ":{range}call" will call the function for
3328 each line in the range, with the cursor on the start
3329 of each line. See |function-range-example|.
3330 When the [abort] argument is added, the function will
3331 abort as soon as an error is detected.
3332 The last used search pattern and the redo command "."
3333 will not be changed by the function.
3334
3335 *:endf* *:endfunction* *E126* *E193*
3336:endf[unction] The end of a function definition. Must be on a line
3337 by its own, without other commands.
3338
3339 *:delf* *:delfunction* *E130* *E131*
3340:delf[unction] {name} Delete function {name}.
3341
3342 *:retu* *:return* *E133*
3343:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
3344 evaluated and returned as the result of the function.
3345 If "[expr]" is not given, the number 0 is returned.
3346 When a function ends without an explicit ":return",
3347 the number 0 is returned.
3348 Note that there is no check for unreachable lines,
3349 thus there is no warning if commands follow ":return".
3350
3351 If the ":return" is used after a |:try| but before the
3352 matching |:finally| (if present), the commands
3353 following the ":finally" up to the matching |:endtry|
3354 are executed first. This process applies to all
3355 nested ":try"s inside the function. The function
3356 returns at the outermost ":endtry".
3357
3358
3359Inside a function variables can be used. These are local variables, which
3360will disappear when the function returns. Global variables need to be
3361accessed with "g:".
3362
3363Example: >
3364 :function Table(title, ...)
3365 : echohl Title
3366 : echo a:title
3367 : echohl None
3368 : let idx = 1
3369 : while idx <= a:0
3370 : echo a:{idx} . ' '
3371 : let idx = idx + 1
3372 : endwhile
3373 : return idx
3374 :endfunction
3375
3376This function can then be called with: >
3377 let lines = Table("Table", "line1", "line2")
3378 let lines = Table("Empty Table")
3379
3380To return more than one value, pass the name of a global variable: >
3381 :function Compute(n1, n2, divname)
3382 : if a:n2 == 0
3383 : return "fail"
3384 : endif
3385 : let g:{a:divname} = a:n1 / a:n2
3386 : return "ok"
3387 :endfunction
3388
3389This function can then be called with: >
3390 :let success = Compute(13, 1324, "div")
3391 :if success == "ok"
3392 : echo div
3393 :endif
3394
3395An alternative is to return a command that can be executed. This also works
3396with local variables in a calling function. Example: >
3397 :function Foo()
3398 : execute Bar()
3399 : echo "line " . lnum . " column " . col
3400 :endfunction
3401
3402 :function Bar()
3403 : return "let lnum = " . line(".") . " | let col = " . col(".")
3404 :endfunction
3405
3406The names "lnum" and "col" could also be passed as argument to Bar(), to allow
3407the caller to set the names.
3408
3409 *:cal* *:call* *E107*
3410:[range]cal[l] {name}([arguments])
3411 Call a function. The name of the function and its arguments
3412 are as specified with |:function|. Up to 20 arguments can be
3413 used.
3414 Without a range and for functions that accept a range, the
3415 function is called once. When a range is given the cursor is
3416 positioned at the start of the first line before executing the
3417 function.
3418 When a range is given and the function doesn't handle it
3419 itself, the function is executed for each line in the range,
3420 with the cursor in the first column of that line. The cursor
3421 is left at the last line (possibly moved by the last function
3422 call). The arguments are re-evaluated for each line. Thus
3423 this works:
3424 *function-range-example* >
3425 :function Mynumber(arg)
3426 : echo line(".") . " " . a:arg
3427 :endfunction
3428 :1,5call Mynumber(getline("."))
3429<
3430 The "a:firstline" and "a:lastline" are defined anyway, they
3431 can be used to do something different at the start or end of
3432 the range.
3433
3434 Example of a function that handles the range itself: >
3435
3436 :function Cont() range
3437 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
3438 :endfunction
3439 :4,8call Cont()
3440<
3441 This function inserts the continuation character "\" in front
3442 of all the lines in the range, except the first one.
3443
3444 *E132*
3445The recursiveness of user functions is restricted with the |'maxfuncdepth'|
3446option.
3447
3448 *autoload-functions*
3449When using many or large functions, it's possible to automatically define them
3450only when they are used. Use the FuncUndefined autocommand event with a
3451pattern that matches the function(s) to be defined. Example: >
3452
3453 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
3454
3455The file "~/vim/bufnetfuncs.vim" should then define functions that start with
3456"BufNet". Also see |FuncUndefined|.
3457
3458==============================================================================
34596. Curly braces names *curly-braces-names*
3460
3461Wherever you can use a variable, you can use a "curly braces name" variable.
3462This is a regular variable name with one or more expressions wrapped in braces
3463{} like this: >
3464 my_{adjective}_variable
3465
3466When Vim encounters this, it evaluates the expression inside the braces, puts
3467that in place of the expression, and re-interprets the whole as a variable
3468name. So in the above example, if the variable "adjective" was set to
3469"noisy", then the reference would be to "my_noisy_variable", whereas if
3470"adjective" was set to "quiet", then it would be to "my_quiet_variable".
3471
3472One application for this is to create a set of variables governed by an option
3473value. For example, the statement >
3474 echo my_{&background}_message
3475
3476would output the contents of "my_dark_message" or "my_light_message" depending
3477on the current value of 'background'.
3478
3479You can use multiple brace pairs: >
3480 echo my_{adverb}_{adjective}_message
3481..or even nest them: >
3482 echo my_{ad{end_of_word}}_message
3483where "end_of_word" is either "verb" or "jective".
3484
3485However, the expression inside the braces must evaluate to a valid single
3486variable name. e.g. this is invalid: >
3487 :let foo='a + b'
3488 :echo c{foo}d
3489.. since the result of expansion is "ca + bd", which is not a variable name.
3490
3491 *curly-braces-function-names*
3492You can call and define functions by an evaluated name in a similar way.
3493Example: >
3494 :let func_end='whizz'
3495 :call my_func_{func_end}(parameter)
3496
3497This would call the function "my_func_whizz(parameter)".
3498
3499==============================================================================
35007. Commands *expression-commands*
3501
3502:let {var-name} = {expr1} *:let* *E18*
3503 Set internal variable {var-name} to the result of the
3504 expression {expr1}. The variable will get the type
3505 from the {expr}. If {var-name} didn't exist yet, it
3506 is created.
3507
3508:let ${env-name} = {expr1} *:let-environment* *:let-$*
3509 Set environment variable {env-name} to the result of
3510 the expression {expr1}. The type is always String.
3511
3512:let @{reg-name} = {expr1} *:let-register* *:let-@*
3513 Write the result of the expression {expr1} in register
3514 {reg-name}. {reg-name} must be a single letter, and
3515 must be the name of a writable register (see
3516 |registers|). "@@" can be used for the unnamed
3517 register, "@/" for the search pattern.
3518 If the result of {expr1} ends in a <CR> or <NL>, the
3519 register will be linewise, otherwise it will be set to
3520 characterwise.
3521 This can be used to clear the last search pattern: >
3522 :let @/ = ""
3523< This is different from searching for an empty string,
3524 that would match everywhere.
3525
3526:let &{option-name} = {expr1} *:let-option* *:let-star*
3527 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003528 expression {expr1}. A String or Number value is
3529 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530 For an option local to a window or buffer the effect
3531 is just like using the |:set| command: both the local
3532 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003533 Example: >
3534 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535
3536:let &l:{option-name} = {expr1}
3537 Like above, but only set the local value of an option
3538 (if there is one). Works like |:setlocal|.
3539
3540:let &g:{option-name} = {expr1}
3541 Like above, but only set the global value of an option
3542 (if there is one). Works like |:setglobal|.
3543
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003544:let [{name1}, {name2}, ...] = {expr1} *:let-unpack*
3545 {expr1} must evaluate to a List. The first item in
3546 the list is assigned to {name1}, the second item to
3547 {name2}, etc.
3548 The number of names must match the number of items in
3549 the List.
3550 Each name can be one of the items of the ":let"
3551 command as mentioned above.
3552 Example: >
3553 :let [s, item] = GetItem(s)
3554
3555:let [{name}, ..., ; {lastname}] = {expr1}
3556 Like above, but the List may have more items than
3557 there are names. A list of the remaining items is
3558 assigned to {lastname}. If there are no remaining
3559 items {lastname} is set to an empty list.
3560 Example: >
3561 :let [a, b; rest] = ["aval", "bval", 3, 4]
3562<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 *E106*
3564:let {var-name} .. List the value of variable {var-name}. Several
3565 variable names may be given.
3566
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003567:let List the values of all variables. The type of the
3568 variable is indicated before the value:
3569 <nothing> String
3570 # Number
3571 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
3573 *:unlet* *:unl* *E108*
3574:unl[et][!] {var-name} ...
3575 Remove the internal variable {var-name}. Several
3576 variable names can be given, they are all removed.
3577 With [!] no error message is given for non-existing
3578 variables.
3579
3580:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
3581:en[dif] Execute the commands until the next matching ":else"
3582 or ":endif" if {expr1} evaluates to non-zero.
3583
3584 From Vim version 4.5 until 5.0, every Ex command in
3585 between the ":if" and ":endif" is ignored. These two
3586 commands were just to allow for future expansions in a
3587 backwards compatible way. Nesting was allowed. Note
3588 that any ":else" or ":elseif" was ignored, the "else"
3589 part was not executed either.
3590
3591 You can use this to remain compatible with older
3592 versions: >
3593 :if version >= 500
3594 : version-5-specific-commands
3595 :endif
3596< The commands still need to be parsed to find the
3597 "endif". Sometimes an older Vim has a problem with a
3598 new command. For example, ":silent" is recognized as
3599 a ":substitute" command. In that case ":execute" can
3600 avoid problems: >
3601 :if version >= 600
3602 : execute "silent 1,$delete"
3603 :endif
3604<
3605 NOTE: The ":append" and ":insert" commands don't work
3606 properly in between ":if" and ":endif".
3607
3608 *:else* *:el* *E581* *E583*
3609:el[se] Execute the commands until the next matching ":else"
3610 or ":endif" if they previously were not being
3611 executed.
3612
3613 *:elseif* *:elsei* *E582* *E584*
3614:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
3615 is no extra ":endif".
3616
3617:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
3618 *E170* *E585* *E588*
3619:endw[hile] Repeat the commands between ":while" and ":endwhile",
3620 as long as {expr1} evaluates to non-zero.
3621 When an error is detected from a command inside the
3622 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00003623 Example: >
3624 :let lnum = 1
3625 :while lnum <= line("$")
3626 :call FixLine(lnum)
3627 :let lnum = lnum + 1
3628 :endwhile
3629<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaar12805862005-01-05 22:16:17 +00003631 properly inside a :while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632
Bram Moolenaar12805862005-01-05 22:16:17 +00003633:for {var} in {list} *:for*
3634:endfo[r] *:endfo* *:endfor*
3635 Repeat the commands between ":for" and ":endfor" for
3636 each item in {list}. {var} is set to the value of the
3637 item.
3638 When an error is detected from a command inside the
3639 loop, execution continues after the "endfor".
3640 A copy of {list} is made, so that it cannot change
3641 while executing the commands. Example (an inefficient
3642 way to make a list empty): >
3643 :for a in mylist
3644 :call remove(mylist, 0)
3645 :endfor
3646< Note that the type of each list item should be
3647 identical to avoid errors for the type of {var}
3648 changing. Unlet the variable at the end of the loop
3649 to allow multiple item types.
3650
3651:for {var} in {string}
3652:endfo[r] Like ":for" above, but use each character in {string}
3653 as a list item.
3654 Composing characters are used as separate characters.
3655 A Number is first converted to a String.
3656
3657:for [{var1}, {var2}, ...] in {listlist}
3658:endfo[r]
3659 Like ":for" above, but each item in {listlist} must be
3660 a list, of which each item is assigned to {var1},
3661 {var2}, etc. Example: >
3662 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
3663 :echo getline(lnum)[col]
3664 :endfor
3665<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00003667:con[tinue] When used inside a ":while" or ":for" loop, jumps back
3668 to the start of the loop.
3669 If it is used after a |:try| inside the loop but
3670 before the matching |:finally| (if present), the
3671 commands following the ":finally" up to the matching
3672 |:endtry| are executed first. This process applies to
3673 all nested ":try"s inside the loop. The outermost
3674 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675
3676 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00003677:brea[k] When used inside a ":while" or ":for" loop, skips to
3678 the command after the matching ":endwhile" or
3679 ":endfor".
3680 If it is used after a |:try| inside the loop but
3681 before the matching |:finally| (if present), the
3682 commands following the ":finally" up to the matching
3683 |:endtry| are executed first. This process applies to
3684 all nested ":try"s inside the loop. The outermost
3685 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686
3687:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
3688:endt[ry] Change the error handling for the commands between
3689 ":try" and ":endtry" including everything being
3690 executed across ":source" commands, function calls,
3691 or autocommand invocations.
3692
3693 When an error or interrupt is detected and there is
3694 a |:finally| command following, execution continues
3695 after the ":finally". Otherwise, or when the
3696 ":endtry" is reached thereafter, the next
3697 (dynamically) surrounding ":try" is checked for
3698 a corresponding ":finally" etc. Then the script
3699 processing is terminated. (Whether a function
3700 definition has an "abort" argument does not matter.)
3701 Example: >
3702 :try | edit too much | finally | echo "cleanup" | endtry
3703 :echo "impossible" " not reached, script terminated above
3704<
3705 Moreover, an error or interrupt (dynamically) inside
3706 ":try" and ":endtry" is converted to an exception. It
3707 can be caught as if it were thrown by a |:throw|
3708 command (see |:catch|). In this case, the script
3709 processing is not terminated.
3710
3711 The value "Vim:Interrupt" is used for an interrupt
3712 exception. An error in a Vim command is converted
3713 to a value of the form "Vim({command}):{errmsg}",
3714 other errors are converted to a value of the form
3715 "Vim:{errmsg}". {command} is the full command name,
3716 and {errmsg} is the message that is displayed if the
3717 error exception is not caught, always beginning with
3718 the error number.
3719 Examples: >
3720 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
3721 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
3722<
3723 *:cat* *:catch* *E603* *E604* *E605*
3724:cat[ch] /{pattern}/ The following commands until the next ":catch",
3725 |:finally|, or |:endtry| that belongs to the same
3726 |:try| as the ":catch" are executed when an exception
3727 matching {pattern} is being thrown and has not yet
3728 been caught by a previous ":catch". Otherwise, these
3729 commands are skipped.
3730 When {pattern} is omitted all errors are caught.
3731 Examples: >
3732 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
3733 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
3734 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
3735 :catch /^Vim(write):/ " catch all errors in :write
3736 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
3737 :catch /my-exception/ " catch user exception
3738 :catch /.*/ " catch everything
3739 :catch " same as /.*/
3740<
3741 Another character can be used instead of / around the
3742 {pattern}, so long as it does not have a special
3743 meaning (e.g., '|' or '"') and doesn't occur inside
3744 {pattern}.
3745 NOTE: It is not reliable to ":catch" the TEXT of
3746 an error message because it may vary in different
3747 locales.
3748
3749 *:fina* *:finally* *E606* *E607*
3750:fina[lly] The following commands until the matching |:endtry|
3751 are executed whenever the part between the matching
3752 |:try| and the ":finally" is left: either by falling
3753 through to the ":finally" or by a |:continue|,
3754 |:break|, |:finish|, or |:return|, or by an error or
3755 interrupt or exception (see |:throw|).
3756
3757 *:th* *:throw* *E608*
3758:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
3759 If the ":throw" is used after a |:try| but before the
3760 first corresponding |:catch|, commands are skipped
3761 until the first ":catch" matching {expr1} is reached.
3762 If there is no such ":catch" or if the ":throw" is
3763 used after a ":catch" but before the |:finally|, the
3764 commands following the ":finally" (if present) up to
3765 the matching |:endtry| are executed. If the ":throw"
3766 is after the ":finally", commands up to the ":endtry"
3767 are skipped. At the ":endtry", this process applies
3768 again for the next dynamically surrounding ":try"
3769 (which may be found in a calling function or sourcing
3770 script), until a matching ":catch" has been found.
3771 If the exception is not caught, the command processing
3772 is terminated.
3773 Example: >
3774 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
3775<
3776
3777 *:ec* *:echo*
3778:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
3779 first {expr1} starts on a new line.
3780 Also see |:comment|.
3781 Use "\n" to start a new line. Use "\r" to move the
3782 cursor to the first column.
3783 Uses the highlighting set by the |:echohl| command.
3784 Cannot be followed by a comment.
3785 Example: >
3786 :echo "the value of 'shell' is" &shell
3787< A later redraw may make the message disappear again.
3788 To avoid that a command from before the ":echo" causes
3789 a redraw afterwards (redraws are often postponed until
3790 you type something), force a redraw with the |:redraw|
3791 command. Example: >
3792 :new | redraw | echo "there is a new window"
3793<
3794 *:echon*
3795:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
3796 |:comment|.
3797 Uses the highlighting set by the |:echohl| command.
3798 Cannot be followed by a comment.
3799 Example: >
3800 :echon "the value of 'shell' is " &shell
3801<
3802 Note the difference between using ":echo", which is a
3803 Vim command, and ":!echo", which is an external shell
3804 command: >
3805 :!echo % --> filename
3806< The arguments of ":!" are expanded, see |:_%|. >
3807 :!echo "%" --> filename or "filename"
3808< Like the previous example. Whether you see the double
3809 quotes or not depends on your 'shell'. >
3810 :echo % --> nothing
3811< The '%' is an illegal character in an expression. >
3812 :echo "%" --> %
3813< This just echoes the '%' character. >
3814 :echo expand("%") --> filename
3815< This calls the expand() function to expand the '%'.
3816
3817 *:echoh* *:echohl*
3818:echoh[l] {name} Use the highlight group {name} for the following
3819 |:echo|, |:echon| and |:echomsg| commands. Also used
3820 for the |input()| prompt. Example: >
3821 :echohl WarningMsg | echo "Don't panic!" | echohl None
3822< Don't forget to set the group back to "None",
3823 otherwise all following echo's will be highlighted.
3824
3825 *:echom* *:echomsg*
3826:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
3827 message in the |message-history|.
3828 Spaces are placed between the arguments as with the
3829 |:echo| command. But unprintable characters are
3830 displayed, not interpreted.
3831 Uses the highlighting set by the |:echohl| command.
3832 Example: >
3833 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
3834<
3835 *:echoe* *:echoerr*
3836:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
3837 message in the |message-history|. When used in a
3838 script or function the line number will be added.
3839 Spaces are placed between the arguments as with the
3840 :echo command. When used inside a try conditional,
3841 the message is raised as an error exception instead
3842 (see |try-echoerr|).
3843 Example: >
3844 :echoerr "This script just failed!"
3845< If you just want a highlighted message use |:echohl|.
3846 And to get a beep: >
3847 :exe "normal \<Esc>"
3848<
3849 *:exe* *:execute*
3850:exe[cute] {expr1} .. Executes the string that results from the evaluation
3851 of {expr1} as an Ex command. Multiple arguments are
3852 concatenated, with a space in between. {expr1} is
3853 used as the processed command, command line editing
3854 keys are not recognized.
3855 Cannot be followed by a comment.
3856 Examples: >
3857 :execute "buffer " nextbuf
3858 :execute "normal " count . "w"
3859<
3860 ":execute" can be used to append a command to commands
3861 that don't accept a '|'. Example: >
3862 :execute '!ls' | echo "theend"
3863
3864< ":execute" is also a nice way to avoid having to type
3865 control characters in a Vim script for a ":normal"
3866 command: >
3867 :execute "normal ixxx\<Esc>"
3868< This has an <Esc> character, see |expr-string|.
3869
3870 Note: The executed string may be any command-line, but
3871 you cannot start or end a "while" or "if" command.
3872 Thus this is illegal: >
3873 :execute 'while i > 5'
3874 :execute 'echo "test" | break'
3875<
3876 It is allowed to have a "while" or "if" command
3877 completely in the executed string: >
3878 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
3879<
3880
3881 *:comment*
3882 ":execute", ":echo" and ":echon" cannot be followed by
3883 a comment directly, because they see the '"' as the
3884 start of a string. But, you can use '|' followed by a
3885 comment. Example: >
3886 :echo "foo" | "this is a comment
3887
3888==============================================================================
38898. Exception handling *exception-handling*
3890
3891The Vim script language comprises an exception handling feature. This section
3892explains how it can be used in a Vim script.
3893
3894Exceptions may be raised by Vim on an error or on interrupt, see
3895|catch-errors| and |catch-interrupt|. You can also explicitly throw an
3896exception by using the ":throw" command, see |throw-catch|.
3897
3898
3899TRY CONDITIONALS *try-conditionals*
3900
3901Exceptions can be caught or can cause cleanup code to be executed. You can
3902use a try conditional to specify catch clauses (that catch exceptions) and/or
3903a finally clause (to be executed for cleanup).
3904 A try conditional begins with a |:try| command and ends at the matching
3905|:endtry| command. In between, you can use a |:catch| command to start
3906a catch clause, or a |:finally| command to start a finally clause. There may
3907be none or multiple catch clauses, but there is at most one finally clause,
3908which must not be followed by any catch clauses. The lines before the catch
3909clauses and the finally clause is called a try block. >
3910
3911 :try
3912 : ...
3913 : ... TRY BLOCK
3914 : ...
3915 :catch /{pattern}/
3916 : ...
3917 : ... CATCH CLAUSE
3918 : ...
3919 :catch /{pattern}/
3920 : ...
3921 : ... CATCH CLAUSE
3922 : ...
3923 :finally
3924 : ...
3925 : ... FINALLY CLAUSE
3926 : ...
3927 :endtry
3928
3929The try conditional allows to watch code for exceptions and to take the
3930appropriate actions. Exceptions from the try block may be caught. Exceptions
3931from the try block and also the catch clauses may cause cleanup actions.
3932 When no exception is thrown during execution of the try block, the control
3933is transferred to the finally clause, if present. After its execution, the
3934script continues with the line following the ":endtry".
3935 When an exception occurs during execution of the try block, the remaining
3936lines in the try block are skipped. The exception is matched against the
3937patterns specified as arguments to the ":catch" commands. The catch clause
3938after the first matching ":catch" is taken, other catch clauses are not
3939executed. The catch clause ends when the next ":catch", ":finally", or
3940":endtry" command is reached - whatever is first. Then, the finally clause
3941(if present) is executed. When the ":endtry" is reached, the script execution
3942continues in the following line as usual.
3943 When an exception that does not match any of the patterns specified by the
3944":catch" commands is thrown in the try block, the exception is not caught by
3945that try conditional and none of the catch clauses is executed. Only the
3946finally clause, if present, is taken. The exception pends during execution of
3947the finally clause. It is resumed at the ":endtry", so that commands after
3948the ":endtry" are not executed and the exception might be caught elsewhere,
3949see |try-nesting|.
3950 When during execution of a catch clause another exception is thrown, the
3951remaining lines in that catch clause are not executed. The new exception is
3952not matched against the patterns in any of the ":catch" commands of the same
3953try conditional and none of its catch clauses is taken. If there is, however,
3954a finally clause, it is executed, and the exception pends during its
3955execution. The commands following the ":endtry" are not executed. The new
3956exception might, however, be caught elsewhere, see |try-nesting|.
3957 When during execution of the finally clause (if present) an exception is
3958thrown, the remaining lines in the finally clause are skipped. If the finally
3959clause has been taken because of an exception from the try block or one of the
3960catch clauses, the original (pending) exception is discarded. The commands
3961following the ":endtry" are not executed, and the exception from the finally
3962clause is propagated and can be caught elsewhere, see |try-nesting|.
3963
3964The finally clause is also executed, when a ":break" or ":continue" for
3965a ":while" loop enclosing the complete try conditional is executed from the
3966try block or a catch clause. Or when a ":return" or ":finish" is executed
3967from the try block or a catch clause of a try conditional in a function or
3968sourced script, respectively. The ":break", ":continue", ":return", or
3969":finish" pends during execution of the finally clause and is resumed when the
3970":endtry" is reached. It is, however, discarded when an exception is thrown
3971from the finally clause.
3972 When a ":break" or ":continue" for a ":while" loop enclosing the complete
3973try conditional or when a ":return" or ":finish" is encountered in the finally
3974clause, the rest of the finally clause is skipped, and the ":break",
3975":continue", ":return" or ":finish" is executed as usual. If the finally
3976clause has been taken because of an exception or an earlier ":break",
3977":continue", ":return", or ":finish" from the try block or a catch clause,
3978this pending exception or command is discarded.
3979
3980For examples see |throw-catch| and |try-finally|.
3981
3982
3983NESTING OF TRY CONDITIONALS *try-nesting*
3984
3985Try conditionals can be nested arbitrarily. That is, a complete try
3986conditional can be put into the try block, a catch clause, or the finally
3987clause of another try conditional. If the inner try conditional does not
3988catch an exception thrown in its try block or throws a new exception from one
3989of its catch clauses or its finally clause, the outer try conditional is
3990checked according to the rules above. If the inner try conditional is in the
3991try block of the outer try conditional, its catch clauses are checked, but
3992otherwise only the finally clause is executed. It does not matter for
3993nesting, whether the inner try conditional is directly contained in the outer
3994one, or whether the outer one sources a script or calls a function containing
3995the inner try conditional.
3996
3997When none of the active try conditionals catches an exception, just their
3998finally clauses are executed. Thereafter, the script processing terminates.
3999An error message is displayed in case of an uncaught exception explicitly
4000thrown by a ":throw" command. For uncaught error and interrupt exceptions
4001implicitly raised by Vim, the error message(s) or interrupt message are shown
4002as usual.
4003
4004For examples see |throw-catch|.
4005
4006
4007EXAMINING EXCEPTION HANDLING CODE *except-examine*
4008
4009Exception handling code can get tricky. If you are in doubt what happens, set
4010'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
4011script file. Then you see when an exception is thrown, discarded, caught, or
4012finished. When using a verbosity level of at least 14, things pending in
4013a finally clause are also shown. This information is also given in debug mode
4014(see |debug-scripts|).
4015
4016
4017THROWING AND CATCHING EXCEPTIONS *throw-catch*
4018
4019You can throw any number or string as an exception. Use the |:throw| command
4020and pass the value to be thrown as argument: >
4021 :throw 4711
4022 :throw "string"
4023< *throw-expression*
4024You can also specify an expression argument. The expression is then evaluated
4025first, and the result is thrown: >
4026 :throw 4705 + strlen("string")
4027 :throw strpart("strings", 0, 6)
4028
4029An exception might be thrown during evaluation of the argument of the ":throw"
4030command. Unless it is caught there, the expression evaluation is abandoned.
4031The ":throw" command then does not throw a new exception.
4032 Example: >
4033
4034 :function! Foo(arg)
4035 : try
4036 : throw a:arg
4037 : catch /foo/
4038 : endtry
4039 : return 1
4040 :endfunction
4041 :
4042 :function! Bar()
4043 : echo "in Bar"
4044 : return 4710
4045 :endfunction
4046 :
4047 :throw Foo("arrgh") + Bar()
4048
4049This throws "arrgh", and "in Bar" is not displayed since Bar() is not
4050executed. >
4051 :throw Foo("foo") + Bar()
4052however displays "in Bar" and throws 4711.
4053
4054Any other command that takes an expression as argument might also be
4055abandoned by an (uncaught) exception during the expression evaluation. The
4056exception is then propagated to the caller of the command.
4057 Example: >
4058
4059 :if Foo("arrgh")
4060 : echo "then"
4061 :else
4062 : echo "else"
4063 :endif
4064
4065Here neither of "then" or "else" is displayed.
4066
4067 *catch-order*
4068Exceptions can be caught by a try conditional with one or more |:catch|
4069commands, see |try-conditionals|. The values to be caught by each ":catch"
4070command can be specified as a pattern argument. The subsequent catch clause
4071gets executed when a matching exception is caught.
4072 Example: >
4073
4074 :function! Foo(value)
4075 : try
4076 : throw a:value
4077 : catch /^\d\+$/
4078 : echo "Number thrown"
4079 : catch /.*/
4080 : echo "String thrown"
4081 : endtry
4082 :endfunction
4083 :
4084 :call Foo(0x1267)
4085 :call Foo('string')
4086
4087The first call to Foo() displays "Number thrown", the second "String thrown".
4088An exception is matched against the ":catch" commands in the order they are
4089specified. Only the first match counts. So you should place the more
4090specific ":catch" first. The following order does not make sense: >
4091
4092 : catch /.*/
4093 : echo "String thrown"
4094 : catch /^\d\+$/
4095 : echo "Number thrown"
4096
4097The first ":catch" here matches always, so that the second catch clause is
4098never taken.
4099
4100 *throw-variables*
4101If you catch an exception by a general pattern, you may access the exact value
4102in the variable |v:exception|: >
4103
4104 : catch /^\d\+$/
4105 : echo "Number thrown. Value is" v:exception
4106
4107You may also be interested where an exception was thrown. This is stored in
4108|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
4109exception most recently caught as long it is not finished.
4110 Example: >
4111
4112 :function! Caught()
4113 : if v:exception != ""
4114 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
4115 : else
4116 : echo 'Nothing caught'
4117 : endif
4118 :endfunction
4119 :
4120 :function! Foo()
4121 : try
4122 : try
4123 : try
4124 : throw 4711
4125 : finally
4126 : call Caught()
4127 : endtry
4128 : catch /.*/
4129 : call Caught()
4130 : throw "oops"
4131 : endtry
4132 : catch /.*/
4133 : call Caught()
4134 : finally
4135 : call Caught()
4136 : endtry
4137 :endfunction
4138 :
4139 :call Foo()
4140
4141This displays >
4142
4143 Nothing caught
4144 Caught "4711" in function Foo, line 4
4145 Caught "oops" in function Foo, line 10
4146 Nothing caught
4147
4148A practical example: The following command ":LineNumber" displays the line
4149number in the script or function where it has been used: >
4150
4151 :function! LineNumber()
4152 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
4153 :endfunction
4154 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
4155<
4156 *try-nested*
4157An exception that is not caught by a try conditional can be caught by
4158a surrounding try conditional: >
4159
4160 :try
4161 : try
4162 : throw "foo"
4163 : catch /foobar/
4164 : echo "foobar"
4165 : finally
4166 : echo "inner finally"
4167 : endtry
4168 :catch /foo/
4169 : echo "foo"
4170 :endtry
4171
4172The inner try conditional does not catch the exception, just its finally
4173clause is executed. The exception is then caught by the outer try
4174conditional. The example displays "inner finally" and then "foo".
4175
4176 *throw-from-catch*
4177You can catch an exception and throw a new one to be caught elsewhere from the
4178catch clause: >
4179
4180 :function! Foo()
4181 : throw "foo"
4182 :endfunction
4183 :
4184 :function! Bar()
4185 : try
4186 : call Foo()
4187 : catch /foo/
4188 : echo "Caught foo, throw bar"
4189 : throw "bar"
4190 : endtry
4191 :endfunction
4192 :
4193 :try
4194 : call Bar()
4195 :catch /.*/
4196 : echo "Caught" v:exception
4197 :endtry
4198
4199This displays "Caught foo, throw bar" and then "Caught bar".
4200
4201 *rethrow*
4202There is no real rethrow in the Vim script language, but you may throw
4203"v:exception" instead: >
4204
4205 :function! Bar()
4206 : try
4207 : call Foo()
4208 : catch /.*/
4209 : echo "Rethrow" v:exception
4210 : throw v:exception
4211 : endtry
4212 :endfunction
4213< *try-echoerr*
4214Note that this method cannot be used to "rethrow" Vim error or interrupt
4215exceptions, because it is not possible to fake Vim internal exceptions.
4216Trying so causes an error exception. You should throw your own exception
4217denoting the situation. If you want to cause a Vim error exception containing
4218the original error exception value, you can use the |:echoerr| command: >
4219
4220 :try
4221 : try
4222 : asdf
4223 : catch /.*/
4224 : echoerr v:exception
4225 : endtry
4226 :catch /.*/
4227 : echo v:exception
4228 :endtry
4229
4230This code displays
4231
4232 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
4233
4234
4235CLEANUP CODE *try-finally*
4236
4237Scripts often change global settings and restore them at their end. If the
4238user however interrupts the script by pressing CTRL-C, the settings remain in
4239an inconsistent state. The same may happen to you in the development phase of
4240a script when an error occurs or you explicitly throw an exception without
4241catching it. You can solve these problems by using a try conditional with
4242a finally clause for restoring the settings. Its execution is guaranteed on
4243normal control flow, on error, on an explicit ":throw", and on interrupt.
4244(Note that errors and interrupts from inside the try conditional are converted
4245to exceptions. When not caught, they terminate the script after the finally
4246clause has been executed.)
4247Example: >
4248
4249 :try
4250 : let s:saved_ts = &ts
4251 : set ts=17
4252 :
4253 : " Do the hard work here.
4254 :
4255 :finally
4256 : let &ts = s:saved_ts
4257 : unlet s:saved_ts
4258 :endtry
4259
4260This method should be used locally whenever a function or part of a script
4261changes global settings which need to be restored on failure or normal exit of
4262that function or script part.
4263
4264 *break-finally*
4265Cleanup code works also when the try block or a catch clause is left by
4266a ":continue", ":break", ":return", or ":finish".
4267 Example: >
4268
4269 :let first = 1
4270 :while 1
4271 : try
4272 : if first
4273 : echo "first"
4274 : let first = 0
4275 : continue
4276 : else
4277 : throw "second"
4278 : endif
4279 : catch /.*/
4280 : echo v:exception
4281 : break
4282 : finally
4283 : echo "cleanup"
4284 : endtry
4285 : echo "still in while"
4286 :endwhile
4287 :echo "end"
4288
4289This displays "first", "cleanup", "second", "cleanup", and "end". >
4290
4291 :function! Foo()
4292 : try
4293 : return 4711
4294 : finally
4295 : echo "cleanup\n"
4296 : endtry
4297 : echo "Foo still active"
4298 :endfunction
4299 :
4300 :echo Foo() "returned by Foo"
4301
4302This displays "cleanup" and "4711 returned by Foo". You don't need to add an
4303extra ":return" in the finally clause. (Above all, this would override the
4304return value.)
4305
4306 *except-from-finally*
4307Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
4308a finally clause is possible, but not recommended since it abandons the
4309cleanup actions for the try conditional. But, of course, interrupt and error
4310exceptions might get raised from a finally clause.
4311 Example where an error in the finally clause stops an interrupt from
4312working correctly: >
4313
4314 :try
4315 : try
4316 : echo "Press CTRL-C for interrupt"
4317 : while 1
4318 : endwhile
4319 : finally
4320 : unlet novar
4321 : endtry
4322 :catch /novar/
4323 :endtry
4324 :echo "Script still running"
4325 :sleep 1
4326
4327If you need to put commands that could fail into a finally clause, you should
4328think about catching or ignoring the errors in these commands, see
4329|catch-errors| and |ignore-errors|.
4330
4331
4332CATCHING ERRORS *catch-errors*
4333
4334If you want to catch specific errors, you just have to put the code to be
4335watched in a try block and add a catch clause for the error message. The
4336presence of the try conditional causes all errors to be converted to an
4337exception. No message is displayed and |v:errmsg| is not set then. To find
4338the right pattern for the ":catch" command, you have to know how the format of
4339the error exception is.
4340 Error exceptions have the following format: >
4341
4342 Vim({cmdname}):{errmsg}
4343or >
4344 Vim:{errmsg}
4345
4346{cmdname} is the name of the command that failed; the second form is used when
4347the command name is not known. {errmsg} is the error message usually produced
4348when the error occurs outside try conditionals. It always begins with
4349a capital "E", followed by a two or three-digit error number, a colon, and
4350a space.
4351
4352Examples:
4353
4354The command >
4355 :unlet novar
4356normally produces the error message >
4357 E108: No such variable: "novar"
4358which is converted inside try conditionals to an exception >
4359 Vim(unlet):E108: No such variable: "novar"
4360
4361The command >
4362 :dwim
4363normally produces the error message >
4364 E492: Not an editor command: dwim
4365which is converted inside try conditionals to an exception >
4366 Vim:E492: Not an editor command: dwim
4367
4368You can catch all ":unlet" errors by a >
4369 :catch /^Vim(unlet):/
4370or all errors for misspelled command names by a >
4371 :catch /^Vim:E492:/
4372
4373Some error messages may be produced by different commands: >
4374 :function nofunc
4375and >
4376 :delfunction nofunc
4377both produce the error message >
4378 E128: Function name must start with a capital: nofunc
4379which is converted inside try conditionals to an exception >
4380 Vim(function):E128: Function name must start with a capital: nofunc
4381or >
4382 Vim(delfunction):E128: Function name must start with a capital: nofunc
4383respectively. You can catch the error by its number independently on the
4384command that caused it if you use the following pattern: >
4385 :catch /^Vim(\a\+):E128:/
4386
4387Some commands like >
4388 :let x = novar
4389produce multiple error messages, here: >
4390 E121: Undefined variable: novar
4391 E15: Invalid expression: novar
4392Only the first is used for the exception value, since it is the most specific
4393one (see |except-several-errors|). So you can catch it by >
4394 :catch /^Vim(\a\+):E121:/
4395
4396You can catch all errors related to the name "nofunc" by >
4397 :catch /\<nofunc\>/
4398
4399You can catch all Vim errors in the ":write" and ":read" commands by >
4400 :catch /^Vim(\(write\|read\)):E\d\+:/
4401
4402You can catch all Vim errors by the pattern >
4403 :catch /^Vim\((\a\+)\)\=:E\d\+:/
4404<
4405 *catch-text*
4406NOTE: You should never catch the error message text itself: >
4407 :catch /No such variable/
4408only works in the english locale, but not when the user has selected
4409a different language by the |:language| command. It is however helpful to
4410cite the message text in a comment: >
4411 :catch /^Vim(\a\+):E108:/ " No such variable
4412
4413
4414IGNORING ERRORS *ignore-errors*
4415
4416You can ignore errors in a specific Vim command by catching them locally: >
4417
4418 :try
4419 : write
4420 :catch
4421 :endtry
4422
4423But you are strongly recommended NOT to use this simple form, since it could
4424catch more than you want. With the ":write" command, some autocommands could
4425be executed and cause errors not related to writing, for instance: >
4426
4427 :au BufWritePre * unlet novar
4428
4429There could even be such errors you are not responsible for as a script
4430writer: a user of your script might have defined such autocommands. You would
4431then hide the error from the user.
4432 It is much better to use >
4433
4434 :try
4435 : write
4436 :catch /^Vim(write):/
4437 :endtry
4438
4439which only catches real write errors. So catch only what you'd like to ignore
4440intentionally.
4441
4442For a single command that does not cause execution of autocommands, you could
4443even suppress the conversion of errors to exceptions by the ":silent!"
4444command: >
4445 :silent! nunmap k
4446This works also when a try conditional is active.
4447
4448
4449CATCHING INTERRUPTS *catch-interrupt*
4450
4451When there are active try conditionals, an interrupt (CTRL-C) is converted to
4452the exception "Vim:Interrupt". You can catch it like every exception. The
4453script is not terminated, then.
4454 Example: >
4455
4456 :function! TASK1()
4457 : sleep 10
4458 :endfunction
4459
4460 :function! TASK2()
4461 : sleep 20
4462 :endfunction
4463
4464 :while 1
4465 : let command = input("Type a command: ")
4466 : try
4467 : if command == ""
4468 : continue
4469 : elseif command == "END"
4470 : break
4471 : elseif command == "TASK1"
4472 : call TASK1()
4473 : elseif command == "TASK2"
4474 : call TASK2()
4475 : else
4476 : echo "\nIllegal command:" command
4477 : continue
4478 : endif
4479 : catch /^Vim:Interrupt$/
4480 : echo "\nCommand interrupted"
4481 : " Caught the interrupt. Continue with next prompt.
4482 : endtry
4483 :endwhile
4484
4485You can interrupt a task here by pressing CTRL-C; the script then asks for
4486a new command. If you press CTRL-C at the prompt, the script is terminated.
4487
4488For testing what happens when CTRL-C would be pressed on a specific line in
4489your script, use the debug mode and execute the |>quit| or |>interrupt|
4490command on that line. See |debug-scripts|.
4491
4492
4493CATCHING ALL *catch-all*
4494
4495The commands >
4496
4497 :catch /.*/
4498 :catch //
4499 :catch
4500
4501catch everything, error exceptions, interrupt exceptions and exceptions
4502explicitly thrown by the |:throw| command. This is useful at the top level of
4503a script in order to catch unexpected things.
4504 Example: >
4505
4506 :try
4507 :
4508 : " do the hard work here
4509 :
4510 :catch /MyException/
4511 :
4512 : " handle known problem
4513 :
4514 :catch /^Vim:Interrupt$/
4515 : echo "Script interrupted"
4516 :catch /.*/
4517 : echo "Internal error (" . v:exception . ")"
4518 : echo " - occurred at " . v:throwpoint
4519 :endtry
4520 :" end of script
4521
4522Note: Catching all might catch more things than you want. Thus, you are
4523strongly encouraged to catch only for problems that you can really handle by
4524specifying a pattern argument to the ":catch".
4525 Example: Catching all could make it nearly impossible to interrupt a script
4526by pressing CTRL-C: >
4527
4528 :while 1
4529 : try
4530 : sleep 1
4531 : catch
4532 : endtry
4533 :endwhile
4534
4535
4536EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
4537
4538Exceptions may be used during execution of autocommands. Example: >
4539
4540 :autocmd User x try
4541 :autocmd User x throw "Oops!"
4542 :autocmd User x catch
4543 :autocmd User x echo v:exception
4544 :autocmd User x endtry
4545 :autocmd User x throw "Arrgh!"
4546 :autocmd User x echo "Should not be displayed"
4547 :
4548 :try
4549 : doautocmd User x
4550 :catch
4551 : echo v:exception
4552 :endtry
4553
4554This displays "Oops!" and "Arrgh!".
4555
4556 *except-autocmd-Pre*
4557For some commands, autocommands get executed before the main action of the
4558command takes place. If an exception is thrown and not caught in the sequence
4559of autocommands, the sequence and the command that caused its execution are
4560abandoned and the exception is propagated to the caller of the command.
4561 Example: >
4562
4563 :autocmd BufWritePre * throw "FAIL"
4564 :autocmd BufWritePre * echo "Should not be displayed"
4565 :
4566 :try
4567 : write
4568 :catch
4569 : echo "Caught:" v:exception "from" v:throwpoint
4570 :endtry
4571
4572Here, the ":write" command does not write the file currently being edited (as
4573you can see by checking 'modified'), since the exception from the BufWritePre
4574autocommand abandons the ":write". The exception is then caught and the
4575script displays: >
4576
4577 Caught: FAIL from BufWrite Auto commands for "*"
4578<
4579 *except-autocmd-Post*
4580For some commands, autocommands get executed after the main action of the
4581command has taken place. If this main action fails and the command is inside
4582an active try conditional, the autocommands are skipped and an error exception
4583is thrown that can be caught by the caller of the command.
4584 Example: >
4585
4586 :autocmd BufWritePost * echo "File successfully written!"
4587 :
4588 :try
4589 : write /i/m/p/o/s/s/i/b/l/e
4590 :catch
4591 : echo v:exception
4592 :endtry
4593
4594This just displays: >
4595
4596 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
4597
4598If you really need to execute the autocommands even when the main action
4599fails, trigger the event from the catch clause.
4600 Example: >
4601
4602 :autocmd BufWritePre * set noreadonly
4603 :autocmd BufWritePost * set readonly
4604 :
4605 :try
4606 : write /i/m/p/o/s/s/i/b/l/e
4607 :catch
4608 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
4609 :endtry
4610<
4611You can also use ":silent!": >
4612
4613 :let x = "ok"
4614 :let v:errmsg = ""
4615 :autocmd BufWritePost * if v:errmsg != ""
4616 :autocmd BufWritePost * let x = "after fail"
4617 :autocmd BufWritePost * endif
4618 :try
4619 : silent! write /i/m/p/o/s/s/i/b/l/e
4620 :catch
4621 :endtry
4622 :echo x
4623
4624This displays "after fail".
4625
4626If the main action of the command does not fail, exceptions from the
4627autocommands will be catchable by the caller of the command: >
4628
4629 :autocmd BufWritePost * throw ":-("
4630 :autocmd BufWritePost * echo "Should not be displayed"
4631 :
4632 :try
4633 : write
4634 :catch
4635 : echo v:exception
4636 :endtry
4637<
4638 *except-autocmd-Cmd*
4639For some commands, the normal action can be replaced by a sequence of
4640autocommands. Exceptions from that sequence will be catchable by the caller
4641of the command.
4642 Example: For the ":write" command, the caller cannot know whether the file
4643had actually been written when the exception occurred. You need to tell it in
4644some way. >
4645
4646 :if !exists("cnt")
4647 : let cnt = 0
4648 :
4649 : autocmd BufWriteCmd * if &modified
4650 : autocmd BufWriteCmd * let cnt = cnt + 1
4651 : autocmd BufWriteCmd * if cnt % 3 == 2
4652 : autocmd BufWriteCmd * throw "BufWriteCmdError"
4653 : autocmd BufWriteCmd * endif
4654 : autocmd BufWriteCmd * write | set nomodified
4655 : autocmd BufWriteCmd * if cnt % 3 == 0
4656 : autocmd BufWriteCmd * throw "BufWriteCmdError"
4657 : autocmd BufWriteCmd * endif
4658 : autocmd BufWriteCmd * echo "File successfully written!"
4659 : autocmd BufWriteCmd * endif
4660 :endif
4661 :
4662 :try
4663 : write
4664 :catch /^BufWriteCmdError$/
4665 : if &modified
4666 : echo "Error on writing (file contents not changed)"
4667 : else
4668 : echo "Error after writing"
4669 : endif
4670 :catch /^Vim(write):/
4671 : echo "Error on writing"
4672 :endtry
4673
4674When this script is sourced several times after making changes, it displays
4675first >
4676 File successfully written!
4677then >
4678 Error on writing (file contents not changed)
4679then >
4680 Error after writing
4681etc.
4682
4683 *except-autocmd-ill*
4684You cannot spread a try conditional over autocommands for different events.
4685The following code is ill-formed: >
4686
4687 :autocmd BufWritePre * try
4688 :
4689 :autocmd BufWritePost * catch
4690 :autocmd BufWritePost * echo v:exception
4691 :autocmd BufWritePost * endtry
4692 :
4693 :write
4694
4695
4696EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
4697
4698Some programming languages allow to use hierarchies of exception classes or to
4699pass additional information with the object of an exception class. You can do
4700similar things in Vim.
4701 In order to throw an exception from a hierarchy, just throw the complete
4702class name with the components separated by a colon, for instance throw the
4703string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
4704 When you want to pass additional information with your exception class, add
4705it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
4706for an error when writing "myfile".
4707 With the appropriate patterns in the ":catch" command, you can catch for
4708base classes or derived classes of your hierarchy. Additional information in
4709parentheses can be cut out from |v:exception| with the ":substitute" command.
4710 Example: >
4711
4712 :function! CheckRange(a, func)
4713 : if a:a < 0
4714 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
4715 : endif
4716 :endfunction
4717 :
4718 :function! Add(a, b)
4719 : call CheckRange(a:a, "Add")
4720 : call CheckRange(a:b, "Add")
4721 : let c = a:a + a:b
4722 : if c < 0
4723 : throw "EXCEPT:MATHERR:OVERFLOW"
4724 : endif
4725 : return c
4726 :endfunction
4727 :
4728 :function! Div(a, b)
4729 : call CheckRange(a:a, "Div")
4730 : call CheckRange(a:b, "Div")
4731 : if (a:b == 0)
4732 : throw "EXCEPT:MATHERR:ZERODIV"
4733 : endif
4734 : return a:a / a:b
4735 :endfunction
4736 :
4737 :function! Write(file)
4738 : try
4739 : execute "write" a:file
4740 : catch /^Vim(write):/
4741 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
4742 : endtry
4743 :endfunction
4744 :
4745 :try
4746 :
4747 : " something with arithmetics and I/O
4748 :
4749 :catch /^EXCEPT:MATHERR:RANGE/
4750 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
4751 : echo "Range error in" function
4752 :
4753 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
4754 : echo "Math error"
4755 :
4756 :catch /^EXCEPT:IO/
4757 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
4758 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
4759 : if file !~ '^/'
4760 : let file = dir . "/" . file
4761 : endif
4762 : echo 'I/O error for "' . file . '"'
4763 :
4764 :catch /^EXCEPT/
4765 : echo "Unspecified error"
4766 :
4767 :endtry
4768
4769The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
4770a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
4771exceptions with the "Vim" prefix; they are reserved for Vim.
4772 Vim error exceptions are parameterized with the name of the command that
4773failed, if known. See |catch-errors|.
4774
4775
4776PECULIARITIES
4777 *except-compat*
4778The exception handling concept requires that the command sequence causing the
4779exception is aborted immediately and control is transferred to finally clauses
4780and/or a catch clause.
4781
4782In the Vim script language there are cases where scripts and functions
4783continue after an error: in functions without the "abort" flag or in a command
4784after ":silent!", control flow goes to the following line, and outside
4785functions, control flow goes to the line following the outermost ":endwhile"
4786or ":endif". On the other hand, errors should be catchable as exceptions
4787(thus, requiring the immediate abortion).
4788
4789This problem has been solved by converting errors to exceptions and using
4790immediate abortion (if not suppressed by ":silent!") only when a try
4791conditional is active. This is no restriction since an (error) exception can
4792be caught only from an active try conditional. If you want an immediate
4793termination without catching the error, just use a try conditional without
4794catch clause. (You can cause cleanup code being executed before termination
4795by specifying a finally clause.)
4796
4797When no try conditional is active, the usual abortion and continuation
4798behavior is used instead of immediate abortion. This ensures compatibility of
4799scripts written for Vim 6.1 and earlier.
4800
4801However, when sourcing an existing script that does not use exception handling
4802commands (or when calling one of its functions) from inside an active try
4803conditional of a new script, you might change the control flow of the existing
4804script on error. You get the immediate abortion on error and can catch the
4805error in the new script. If however the sourced script suppresses error
4806messages by using the ":silent!" command (checking for errors by testing
4807|v:errmsg| if appropriate), its execution path is not changed. The error is
4808not converted to an exception. (See |:silent|.) So the only remaining cause
4809where this happens is for scripts that don't care about errors and produce
4810error messages. You probably won't want to use such code from your new
4811scripts.
4812
4813 *except-syntax-err*
4814Syntax errors in the exception handling commands are never caught by any of
4815the ":catch" commands of the try conditional they belong to. Its finally
4816clauses, however, is executed.
4817 Example: >
4818
4819 :try
4820 : try
4821 : throw 4711
4822 : catch /\(/
4823 : echo "in catch with syntax error"
4824 : catch
4825 : echo "inner catch-all"
4826 : finally
4827 : echo "inner finally"
4828 : endtry
4829 :catch
4830 : echo 'outer catch-all caught "' . v:exception . '"'
4831 : finally
4832 : echo "outer finally"
4833 :endtry
4834
4835This displays: >
4836 inner finally
4837 outer catch-all caught "Vim(catch):E54: Unmatched \("
4838 outer finally
4839The original exception is discarded and an error exception is raised, instead.
4840
4841 *except-single-line*
4842The ":try", ":catch", ":finally", and ":endtry" commands can be put on
4843a single line, but then syntax errors may make it difficult to recognize the
4844"catch" line, thus you better avoid this.
4845 Example: >
4846 :try | unlet! foo # | catch | endtry
4847raises an error exception for the trailing characters after the ":unlet!"
4848argument, but does not see the ":catch" and ":endtry" commands, so that the
4849error exception is discarded and the "E488: Trailing characters" message gets
4850displayed.
4851
4852 *except-several-errors*
4853When several errors appear in a single command, the first error message is
4854usually the most specific one and therefor converted to the error exception.
4855 Example: >
4856 echo novar
4857causes >
4858 E121: Undefined variable: novar
4859 E15: Invalid expression: novar
4860The value of the error exception inside try conditionals is: >
4861 Vim(echo):E121: Undefined variable: novar
4862< *except-syntax-error*
4863But when a syntax error is detected after a normal error in the same command,
4864the syntax error is used for the exception being thrown.
4865 Example: >
4866 unlet novar #
4867causes >
4868 E108: No such variable: "novar"
4869 E488: Trailing characters
4870The value of the error exception inside try conditionals is: >
4871 Vim(unlet):E488: Trailing characters
4872This is done because the syntax error might change the execution path in a way
4873not intended by the user. Example: >
4874 try
4875 try | unlet novar # | catch | echo v:exception | endtry
4876 catch /.*/
4877 echo "outer catch:" v:exception
4878 endtry
4879This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
4880a "E600: Missing :endtry" error message is given, see |except-single-line|.
4881
4882==============================================================================
48839. Examples *eval-examples*
4884
4885Printing in Hex ~
4886>
4887 :" The function Nr2Hex() returns the Hex string of a number.
4888 :func Nr2Hex(nr)
4889 : let n = a:nr
4890 : let r = ""
4891 : while n
4892 : let r = '0123456789ABCDEF'[n % 16] . r
4893 : let n = n / 16
4894 : endwhile
4895 : return r
4896 :endfunc
4897
4898 :" The function String2Hex() converts each character in a string to a two
4899 :" character Hex string.
4900 :func String2Hex(str)
4901 : let out = ''
4902 : let ix = 0
4903 : while ix < strlen(a:str)
4904 : let out = out . Nr2Hex(char2nr(a:str[ix]))
4905 : let ix = ix + 1
4906 : endwhile
4907 : return out
4908 :endfunc
4909
4910Example of its use: >
4911 :echo Nr2Hex(32)
4912result: "20" >
4913 :echo String2Hex("32")
4914result: "3332"
4915
4916
4917Sorting lines (by Robert Webb) ~
4918
4919Here is a Vim script to sort lines. Highlight the lines in Vim and type
4920":Sort". This doesn't call any external programs so it'll work on any
4921platform. The function Sort() actually takes the name of a comparison
4922function as its argument, like qsort() does in C. So you could supply it
4923with different comparison functions in order to sort according to date etc.
4924>
4925 :" Function for use with Sort(), to compare two strings.
4926 :func! Strcmp(str1, str2)
4927 : if (a:str1 < a:str2)
4928 : return -1
4929 : elseif (a:str1 > a:str2)
4930 : return 1
4931 : else
4932 : return 0
4933 : endif
4934 :endfunction
4935
4936 :" Sort lines. SortR() is called recursively.
4937 :func! SortR(start, end, cmp)
4938 : if (a:start >= a:end)
4939 : return
4940 : endif
4941 : let partition = a:start - 1
4942 : let middle = partition
4943 : let partStr = getline((a:start + a:end) / 2)
4944 : let i = a:start
4945 : while (i <= a:end)
4946 : let str = getline(i)
4947 : exec "let result = " . a:cmp . "(str, partStr)"
4948 : if (result <= 0)
4949 : " Need to put it before the partition. Swap lines i and partition.
4950 : let partition = partition + 1
4951 : if (result == 0)
4952 : let middle = partition
4953 : endif
4954 : if (i != partition)
4955 : let str2 = getline(partition)
4956 : call setline(i, str2)
4957 : call setline(partition, str)
4958 : endif
4959 : endif
4960 : let i = i + 1
4961 : endwhile
4962
4963 : " Now we have a pointer to the "middle" element, as far as partitioning
4964 : " goes, which could be anywhere before the partition. Make sure it is at
4965 : " the end of the partition.
4966 : if (middle != partition)
4967 : let str = getline(middle)
4968 : let str2 = getline(partition)
4969 : call setline(middle, str2)
4970 : call setline(partition, str)
4971 : endif
4972 : call SortR(a:start, partition - 1, a:cmp)
4973 : call SortR(partition + 1, a:end, a:cmp)
4974 :endfunc
4975
4976 :" To Sort a range of lines, pass the range to Sort() along with the name of a
4977 :" function that will compare two lines.
4978 :func! Sort(cmp) range
4979 : call SortR(a:firstline, a:lastline, a:cmp)
4980 :endfunc
4981
4982 :" :Sort takes a range of lines and sorts them.
4983 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
4984<
4985 *sscanf*
4986There is no sscanf() function in Vim. If you need to extract parts from a
4987line, you can use matchstr() and substitute() to do it. This example shows
4988how to get the file name, line number and column number out of a line like
4989"foobar.txt, 123, 45". >
4990 :" Set up the match bit
4991 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
4992 :"get the part matching the whole expression
4993 :let l = matchstr(line, mx)
4994 :"get each item out of the match
4995 :let file = substitute(l, mx, '\1', '')
4996 :let lnum = substitute(l, mx, '\2', '')
4997 :let col = substitute(l, mx, '\3', '')
4998
4999The input is in the variable "line", the results in the variables "file",
5000"lnum" and "col". (idea from Michael Geddes)
5001
5002==============================================================================
500310. No +eval feature *no-eval-feature*
5004
5005When the |+eval| feature was disabled at compile time, none of the expression
5006evaluation commands are available. To prevent this from causing Vim scripts
5007to generate all kinds of errors, the ":if" and ":endif" commands are still
5008recognized, though the argument of the ":if" and everything between the ":if"
5009and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
5010only if the commands are at the start of the line. The ":else" command is not
5011recognized.
5012
5013Example of how to avoid executing commands when the |+eval| feature is
5014missing: >
5015
5016 :if 1
5017 : echo "Expression evaluation is compiled in"
5018 :else
5019 : echo "You will _never_ see this message"
5020 :endif
5021
5022==============================================================================
502311. The sandbox *eval-sandbox* *sandbox* *E48*
5024
5025The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
5026options are evaluated in a sandbox. This means that you are protected from
5027these expressions having nasty side effects. This gives some safety for when
5028these options are set from a modeline. It is also used when the command from
5029a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005030The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032These items are not allowed in the sandbox:
5033 - changing the buffer text
5034 - defining or changing mapping, autocommands, functions, user commands
5035 - setting certain options (see |option-summary|)
5036 - executing a shell command
5037 - reading or writing a file
5038 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005039This is not guaranteed 100% secure, but it should block most attacks.
5040
5041 *:san* *:sandbox*
5042:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
5043 option that may have been set from a modeline, e.g.
5044 'foldexpr'.
5045
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046
5047 vim:tw=78:ts=8:ft=help:norl: