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