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