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