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