blob: 5de6a41bd4979890336eda9b620da5457bd43972 [file] [log] [blame]
Bram Moolenaar9cd15162005-01-16 22:02:49 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Jan 16
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
Bram Moolenaard8b02732005-01-14 21:48:43 +000012done, the features in this document are not available. See |+eval| and
13|no-eval-feature|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000014
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 Moolenaard8b02732005-01-14 21:48:43 +000019 1.4 Dictionaries |Dictionaries|
20 1.5 More about variables |more-variables|
Bram Moolenaar13065c42005-01-08 16:08:21 +0000212. Expression syntax |expression-syntax|
223. Internal variable |internal-variables|
234. Builtin Functions |functions|
245. Defining functions |user-functions|
256. Curly braces names |curly-braces-names|
267. Commands |expression-commands|
278. Exception handling |exception-handling|
289. Examples |eval-examples|
2910. No +eval feature |no-eval-feature|
3011. The sandbox |eval-sandbox|
Bram Moolenaar071d4272004-06-13 20:20:40 +000031
32{Vi does not have any of these commands}
33
34==============================================================================
351. Variables *variables*
36
Bram Moolenaar13065c42005-01-08 16:08:21 +0000371.1 Variable types ~
38
39There are four types of variables:
Bram Moolenaar071d4272004-06-13 20:20:40 +000040
Bram Moolenaard8b02732005-01-14 21:48:43 +000041Number A 32 bit signed number.
42 Examples: -123 0x10 0177
43
44String A NUL terminated string of 8-bit unsigned characters (bytes).
45 Examples: "ab\txx\"--" 'x-z''a,c'
46
47Funcref A reference to a function |Funcref|.
48 Example: function("strlen")
49
50List An ordered sequence of items |List|.
51 Example: [1, 2, ['a', 'b']]
Bram Moolenaar071d4272004-06-13 20:20:40 +000052
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000053The Number and String types are converted automatically, depending on how they
54are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +000055
56Conversion from a Number to a String is by making the ASCII representation of
57the Number. Examples: >
58 Number 123 --> String "123"
59 Number 0 --> String "0"
60 Number -1 --> String "-1"
61
62Conversion from a String to a Number is done by converting the first digits
63to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If
64the String doesn't start with digits, the result is zero. Examples: >
65 String "456" --> Number 456
66 String "6bar" --> Number 6
67 String "foo" --> Number 0
68 String "0xf1" --> Number 241
69 String "0100" --> Number 64
70 String "-8" --> Number -8
71 String "+8" --> Number 0
72
73To force conversion from String to Number, add zero to it: >
74 :echo "0100" + 0
75
76For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
77
78Note that in the command >
79 :if "foo"
80"foo" is converted to 0, which means FALSE. To test for a non-empty string,
81use strlen(): >
82 :if strlen("foo")
83
Bram Moolenaar13065c42005-01-08 16:08:21 +000084List and Funcref types are not automatically converted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000085
Bram Moolenaar13065c42005-01-08 16:08:21 +000086 *E706*
87You will get an error if you try to change the type of a variable. You need
88to |:unlet| it first to avoid this error. String and Number are considered
Bram Moolenaard8b02732005-01-14 21:48:43 +000089equivalent though. Consider this sequence of commands: >
Bram Moolenaar13065c42005-01-08 16:08:21 +000090 :let l = "string"
Bram Moolenaar9588a0f2005-01-08 21:45:39 +000091 :let l = 44 " changes type from String to Number
Bram Moolenaar13065c42005-01-08 16:08:21 +000092 :let l = [1, 2, 3] " error!
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000093
Bram Moolenaar13065c42005-01-08 16:08:21 +000094
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000951.2 Function references ~
Bram Moolenaar13065c42005-01-08 16:08:21 +000096 *Funcref* *E695* *E703*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000097A Funcref variable is obtained with the |function()| function. It can be used
98in an expression to invoke the function it refers to by using it in the place
99of a function name, before the parenthesis around the arguments. Example: >
100
101 :let Fn = function("MyFunc")
102 :echo Fn()
Bram Moolenaar13065c42005-01-08 16:08:21 +0000103<
104 *E704* *E705* *E707*
105A Funcref variable must start with a capital, "s:", "w:" or "b:". You cannot
106have both a Funcref variable and a function with the same name.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000107
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000108Note that a Funcref cannot be used with the |:call| command, because its
109argument is not an expression.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000110
111The name of the referenced function can be obtained with |string()|. >
112 :echo "The function is " . string(Myfunc)
113
114You can use |call()| to invoke a Funcref and use a list variable for the
115arguments: >
116 :let r = call(Myfunc, mylist)
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000117
118
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001191.3 Lists ~
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000120 *List* *E686* *E712*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000121A List is an ordered sequence of items. An item can be of any type. Items
122can be accessed by their index number. Items can be added and removed at any
123position in the sequence.
124
Bram Moolenaar13065c42005-01-08 16:08:21 +0000125
126List creation ~
127 *E696* *E697*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000128A List is created with a comma separated list of items in square brackets.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000129Examples: >
130 :let mylist = [1, two, 3, "four"]
131 :let emptylist = []
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000132
133An item can be any expression. Using a List for an item creates a
Bram Moolenaar13065c42005-01-08 16:08:21 +0000134nested List: >
135 :let nestlist = [[11, 12], [21, 22], [31, 32]]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000136
137An extra comma after the last item is ignored.
138
Bram Moolenaar13065c42005-01-08 16:08:21 +0000139
140List index ~
141 *list-index* *E684*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000142An item in the List can be accessed by putting the index in square brackets
Bram Moolenaar13065c42005-01-08 16:08:21 +0000143after the List. Indexes are zero-based, thus the first item has index zero. >
144 :let item = mylist[0] " get the first item: 1
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000145 :let item = mylist[2] " get the third item: 3
Bram Moolenaar13065c42005-01-08 16:08:21 +0000146
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000147When the resulting item is a list this can be repeated: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000148 :let item = nestlist[0][1] " get the first list, second item: 12
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000149<
Bram Moolenaar13065c42005-01-08 16:08:21 +0000150A negative index is counted from the end. Index -1 refers to the last item in
151the List, -2 to the last but one item, etc. >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000152 :let last = mylist[-1] " get the last item: "four"
153
Bram Moolenaar13065c42005-01-08 16:08:21 +0000154To avoid an error for an invalid index use the |get()| function. When an item
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000155is not available it returns zero or the default value you specify: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000156 :echo get(mylist, idx)
157 :echo get(mylist, idx, "NONE")
158
159
160List concatenation ~
161
162Two lists can be concatenated with the "+" operator: >
163 :let longlist = mylist + [5, 6]
164
165To prepend or append an item turn the item into a list by putting [] around
166it. To change a list in-place see |list-modification| below.
167
168
169Sublist ~
170
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000171A part of the List can be obtained by specifying the first and last index,
172separated by a colon in square brackets: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000173 :let shortlist = mylist[2:-1] " get List [3, "four"]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000174
175Omitting the first index is similar to zero. Omitting the last index is
176similar to -1. The difference is that there is no error if the items are not
177available. >
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000178 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
179 :let shortlist = mylist[2:2] " List with one item: [3]
180 :let otherlist = mylist[:] " make a copy of the List
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000181
Bram Moolenaard8b02732005-01-14 21:48:43 +0000182The second index can be just before the first index. In that case the result
183is an empty list. If the second index is lower, this results in an error. >
184 :echo mylist[2:1] " result: []
185 :echo mylist[2:0] " error!
186
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000187
Bram Moolenaar13065c42005-01-08 16:08:21 +0000188List identity ~
Bram Moolenaard8b02732005-01-14 21:48:43 +0000189 *list-identity*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000190When variable "aa" is a list and you assign it to another variable "bb", both
191variables refer to the same list. Thus changing the list "aa" will also
192change "bb": >
193 :let aa = [1, 2, 3]
194 :let bb = aa
195 :call add(aa, 4)
196 :echo bb
197 [1, 2, 3, 4]
198
199Making a copy of a list is done with the |copy()| function. Using [:] also
200works, as explained above. This creates a shallow copy of the list: Changing
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000201a list item in the list will also change the item in the copied list: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000202 :let aa = [[1, 'a'], 2, 3]
203 :let bb = copy(aa)
204 :let aa = aa + [4]
205 :let aa[0][1] = 'aaa'
206 :echo aa
207 [[1, aaa], 2, 3, 4]
208 :echo bb
209 [[1, aaa], 2, 3]
210
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000211To make a completely independent list use |deepcopy()|. This also makes a
212copy of the values in the list, recursively.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000213
214The operator "is" can be used to check if two variables refer to the same
215list. "isnot" does the opposite. In contrast "==" compares if two lists have
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000216the same value. >
217 :let alist = [1, 2, 3]
218 :let blist = [1, 2, 3]
219 :echo alist is blist
220 0
221 :echo alist == blist
222 1
Bram Moolenaar13065c42005-01-08 16:08:21 +0000223
224
225List unpack ~
226
227To unpack the items in a list to individual variables, put the variables in
228square brackets, like list items: >
229 :let [var1, var2] = mylist
230
231When the number of variables does not match the number of items in the list
232this produces an error. To handle any extra items from the list append ";"
233and a variable name: >
234 :let [var1, var2; rest] = mylist
235
236This works like: >
237 :let var1 = mylist[0]
238 :let var2 = mylist[1]
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000239 :let rest = mylist[2:]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000240
241Except that there is no error if there are only two items. "rest" will be an
242empty list then.
243
244
245List modification ~
246 *list-modification*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000247To change a specific item of a list use |:let| this way: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000248 :let list[4] = "four"
249 :let listlist[0][3] = item
250
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000251To change part of a list you can specify the first and last item to be
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000252modified. The value must match the range of replaced items: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000253 :let list[3:5] = [3, 4, 5]
254
Bram Moolenaar13065c42005-01-08 16:08:21 +0000255Adding and removing items from a list is done with functions. Here are a few
256examples: >
257 :call insert(list, 'a') " prepend item 'a'
258 :call insert(list, 'a', 3) " insert item 'a' before list[3]
259 :call add(list, "new") " append String item
260 :call add(list, [1, 2]) " append List as one new item
261 :call extend(list, [1, 2]) " extend the list with two more items
262 :let i = remove(list, 3) " remove item 3
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000263 :unlet list[3] " idem
Bram Moolenaar13065c42005-01-08 16:08:21 +0000264 :let l = remove(list, 3, -1) " remove items 3 to last item
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000265 :unlet list[3 : ] " idem
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000266 :call filter(list, 'v:val =~ "x"') " remove items with an 'x'
Bram Moolenaar13065c42005-01-08 16:08:21 +0000267
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000268Changing the oder of items in a list: >
269 :call sort(list) " sort a list alphabetically
270 :call reverse(list) " reverse the order of items
271
Bram Moolenaar13065c42005-01-08 16:08:21 +0000272
273For loop ~
274
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000275The |:for| loop executes commands for each item in a list. A variable is set
276to each item in the list in sequence. Example: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000277 :for i in mylist
278 : call Doit(i)
279 :endfor
280
281This works like: >
282 :let index = 0
283 :while index < len(mylist)
284 : let i = mylist[index]
285 : :call Doit(i)
286 : let index = index + 1
287 :endwhile
288
289Note that all items in the list should be of the same type, otherwise this
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000290results in an error |E706|. To avoid this |:unlet| the variable at the end of
291the loop.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000292
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000293If all you want to do is modify each item in the list then the |map()|
294function might be a simpler method than a for loop.
295
Bram Moolenaar13065c42005-01-08 16:08:21 +0000296Just like the |:let| command, |:for| also accepts a list of variables. This
297requires the argument to be a list of lists. >
298 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
299 : call Doit(lnum, col)
300 :endfor
301
302This works like a |:let| command is done for each list item. Again, the types
303must remain the same to avoid an error.
304
305It is also possible to put remaining items in a list: >
306 :for [i, j; rest] in listlist
307 : call Doit(i, j)
308 : if !empty(rest)
309 : echo "remainder: " . string(rest)
310 : endif
311 :endfor
312
313
314List functions ~
315
316Functions that are useful with a List: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000317 :let r = call(funcname, list) " call a function with an argument list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000318 :if empty(list) " check if list is empty
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000319 :let l = len(list) " number of items in list
320 :let big = max(list) " maximum value in list
321 :let small = min(list) " minimum value in list
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000322 :let xs = count(list, 'x') " count nr of times 'x' appears in list
323 :let i = index(list, 'x') " index of first 'x' in list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000324 :let lines = getline(1, 10) " get ten text lines from buffer
325 :call append('$', lines) " append text lines in buffer
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000326 :let list = split("a b c") " create list from items in a string
327 :let string = join(list, ', ') " create string from list items
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000328 :let s = string(list) " String representation of list
329 :call map(list, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000330
331
Bram Moolenaard8b02732005-01-14 21:48:43 +00003321.4 Dictionaries ~
333 *Dictionaries*
334A Dictionary is an associative array: Each entry has a key and a value. The
335entry can be located with the key. The entries are stored without ordering.
336
337
338Dictionary creation ~
339
340A Dictionary is created with a comma separated list of entries in curly
341braces. Each entry has a key and a value, separated by a colon. Examples: >
342 :let mydict = {1: 'one', 2: 'two', 3: 'three'}
343 :let emptydict = {}
344
345A key is always a String. You can use a Number, it will be converted to a
346String automatically. Thus the String '4' and the number 4 will find the same
347entry. Note that the String '04' and the Number 04 are different, since 04
348will be converted to the String '4'.
349
350A value can be any expression. Using a Dictionary for an entry creates a
351nested Dictionary: >
352 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
353
354An extra comma after the last entry is ignored.
355
356
357Accessing entries ~
358
359The normal way to access an entry is by putting the key in square brackets: >
360 :let val = mydict["one"]
361 :let mydict["four"] = 4
362
363You can add new entries to an existing Dictionary this way.
364
365For keys that consist entirely of letters, digits and underscore the following
366form can be used |expr-entry|: >
367 :let val = mydict.one
368 :let mydict.four = 4
369
370Since an entry can be any type, also a List and a Dictionary, the indexing and
371key lookup can be repeated: >
372 :let dict.key[idx].key = 0
373
374
375Dictionary to List conversion ~
376
377You may want to loop over the entries in a dictionary. For this you need to
378turn the Dictionary into a List and pass it to |:for|.
379
380Most often you want to loop over the keys, using the |keys()| function: >
381 :for key in keys(mydict)
382 : echo key . ': ' . mydict[key]
383 :endfor
384
385The List of keys is unsorted. You may want to sort them first: >
386 :for key in sort(keys(mydict))
387
388To loop over the values use the |values()| function: >
389 :for v in values(mydict)
390 : echo "value: " . v
391 :endfor
392
393If you want both the key and the value use the |items()| function. It returns
394a List of Lists with two items: the key and the value: >
395 :for entry in items(mydict)
396 : echo entry[0] . ': ' . entry[1]
397 :endfor
398
399
400Dictionary identity ~
401
402Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
403Dictionary. Otherwise, assignment results in referring to the same
404Dictionary: >
405 :let onedict = {'a': 1, 'b': 2}
406 :let adict = onedict
407 :let adict['a'] = 11
408 :echo onedict['a']
409 11
410
411For more info see |list-identity|.
412
413
414Dictionary modification ~
415 *dict-modification*
416To change an already existing entry of a Dictionary, or to add a new entry,
417use |:let| this way: >
418 :let dict[4] = "four"
419 :let dict['one'] = item
420
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000421Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
422Three ways to remove the entry with key "aaa" from dict: >
423 :let i = remove(dict, 'aaa')
424 :unlet dict.aaa
425 :unlet dict['aaa']
Bram Moolenaard8b02732005-01-14 21:48:43 +0000426
427Merging a Dictionary with another is done with |extend()|: >
428 :call extend(adict, bdict) " extend adict with entries from bdict
429
430Weeding out entries from a Dictionary can be done with |filter()|: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000431 :call filter(dict 'v:val =~ "x"') " remove entries with value 'x'
432
433
434Dictionary function ~
435 *Dictionary-function* *self*
436When a function is defined with the "dict" attribute it can be used in a
437special way with a dictionary. Example: >
438 :function Mylen() dict
439 : return len(self) - 4
440 :endfunction
441 :let dict.len = function(Mylen)
442 :let l = dict.len()
443
444This is like a method in object oriented programming. The entry in the
445Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
446the function was invoked from.
447
448To avoid the extra name for the function it can be defined and directly
449assigned to a Dictionary in this way: >
450 :function dict.len() dict
451 : return len(self) - 4
452 :endfunction
453
454It is also possible to add a Funcref to a Dictionary without the "dict"
455attribute, but the "self" variable is not available then.
456
457
458Functions for Dictionaries ~
459
460Functions that are useful with a Dictionary: >
461 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
462 :if empty(dict) " TRUE if dict is empty
463 :let l = len(dict) " number of items in dict
464 :let big = max(dict) " maximum value in dict
465 :let small = min(dict) " minimum value in dict
466 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
467 :let s = string(dict) " String representation of dict
468 :call map(dict, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaard8b02732005-01-14 21:48:43 +0000469
470
4711.5 More about variables ~
Bram Moolenaar13065c42005-01-08 16:08:21 +0000472 *more-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473If you need to know the type of a variable or expression, use the |type()|
474function.
475
476When the '!' flag is included in the 'viminfo' option, global variables that
477start with an uppercase letter, and don't contain a lowercase letter, are
478stored in the viminfo file |viminfo-file|.
479
480When the 'sessionoptions' option contains "global", global variables that
481start with an uppercase letter and contain at least one lowercase letter are
482stored in the session file |session-file|.
483
484variable name can be stored where ~
485my_var_6 not
486My_Var_6 session file
487MY_VAR_6 viminfo file
488
489
490It's possible to form a variable name with curly braces, see
491|curly-braces-names|.
492
493==============================================================================
4942. Expression syntax *expression-syntax*
495
496Expression syntax summary, from least to most significant:
497
498|expr1| expr2 ? expr1 : expr1 if-then-else
499
500|expr2| expr3 || expr3 .. logical OR
501
502|expr3| expr4 && expr4 .. logical AND
503
504|expr4| expr5 == expr5 equal
505 expr5 != expr5 not equal
506 expr5 > expr5 greater than
507 expr5 >= expr5 greater than or equal
508 expr5 < expr5 smaller than
509 expr5 <= expr5 smaller than or equal
510 expr5 =~ expr5 regexp matches
511 expr5 !~ expr5 regexp doesn't match
512
513 expr5 ==? expr5 equal, ignoring case
514 expr5 ==# expr5 equal, match case
515 etc. As above, append ? for ignoring case, # for
516 matching case
517
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000518 expr5 is expr5 same List instance
519 expr5 isnot expr5 different List instance
520
521|expr5| expr6 + expr6 .. number addition or list concatenation
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 expr6 - expr6 .. number subtraction
523 expr6 . expr6 .. string concatenation
524
525|expr6| expr7 * expr7 .. number multiplication
526 expr7 / expr7 .. number division
527 expr7 % expr7 .. number modulo
528
529|expr7| ! expr7 logical NOT
530 - expr7 unary minus
531 + expr7 unary plus
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000534|expr8| expr8[expr1] byte of a String or item of a List
535 expr8[expr1 : expr1] substring of a String or sublist of a List
536 expr8.name entry in a Dictionary
537 expr8(expr1, ...) function call with Funcref variable
538
539|expr9| number number constant
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000540 "string" string constant, backslash is special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000541 'string' string constant, ' is doubled
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000542 [expr1, ...] List
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000543 {expr1: expr1, ...} Dictionary
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 &option option value
545 (expr1) nested expression
546 variable internal variable
547 va{ria}ble internal variable with curly braces
548 $VAR environment variable
549 @r contents of register 'r'
550 function(expr1, ...) function call
551 func{ti}on(expr1, ...) function call with curly braces
552
553
554".." indicates that the operations in this level can be concatenated.
555Example: >
556 &nu || &list && &shell == "csh"
557
558All expressions within one level are parsed from left to right.
559
560
561expr1 *expr1* *E109*
562-----
563
564expr2 ? expr1 : expr1
565
566The expression before the '?' is evaluated to a number. If it evaluates to
567non-zero, the result is the value of the expression between the '?' and ':',
568otherwise the result is the value of the expression after the ':'.
569Example: >
570 :echo lnum == 1 ? "top" : lnum
571
572Since the first expression is an "expr2", it cannot contain another ?:. The
573other two expressions can, thus allow for recursive use of ?:.
574Example: >
575 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
576
577To keep this readable, using |line-continuation| is suggested: >
578 :echo lnum == 1
579 :\ ? "top"
580 :\ : lnum == 1000
581 :\ ? "last"
582 :\ : lnum
583
584
585expr2 and expr3 *expr2* *expr3*
586---------------
587
588 *expr-barbar* *expr-&&*
589The "||" and "&&" operators take one argument on each side. The arguments
590are (converted to) Numbers. The result is:
591
592 input output ~
593n1 n2 n1 || n2 n1 && n2 ~
594zero zero zero zero
595zero non-zero non-zero zero
596non-zero zero non-zero zero
597non-zero non-zero non-zero non-zero
598
599The operators can be concatenated, for example: >
600
601 &nu || &list && &shell == "csh"
602
603Note that "&&" takes precedence over "||", so this has the meaning of: >
604
605 &nu || (&list && &shell == "csh")
606
607Once the result is known, the expression "short-circuits", that is, further
608arguments are not evaluated. This is like what happens in C. For example: >
609
610 let a = 1
611 echo a || b
612
613This is valid even if there is no variable called "b" because "a" is non-zero,
614so the result must be non-zero. Similarly below: >
615
616 echo exists("b") && b == "yes"
617
618This is valid whether "b" has been defined or not. The second clause will
619only be evaluated if "b" has been defined.
620
621
622expr4 *expr4*
623-----
624
625expr5 {cmp} expr5
626
627Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
628if it evaluates to true.
629
630 *expr-==* *expr-!=* *expr->* *expr->=*
631 *expr-<* *expr-<=* *expr-=~* *expr-!~*
632 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
633 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
634 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
635 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000636 *expr-is*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 use 'ignorecase' match case ignore case ~
638equal == ==# ==?
639not equal != !=# !=?
640greater than > ># >?
641greater than or equal >= >=# >=?
642smaller than < <# <?
643smaller than or equal <= <=# <=?
644regexp matches =~ =~# =~?
645regexp doesn't match !~ !~# !~?
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000646same instance is
647different instance isnot
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648
649Examples:
650"abc" ==# "Abc" evaluates to 0
651"abc" ==? "Abc" evaluates to 1
652"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
653
Bram Moolenaar13065c42005-01-08 16:08:21 +0000654 *E691* *E692*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000655A List can only be compared with a List and only "equal", "not equal" and "is"
656can be used. This compares the values of the list, recursively. Ignoring
657case means case is ignored when comparing item values.
658
Bram Moolenaar13065c42005-01-08 16:08:21 +0000659 *E693* *E694*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000660A Funcref can only be compared with a Funcref and only "equal" and "not equal"
661can be used. Case is never ignored.
662
663When using "is" or "isnot" with a List this checks if the expressions are
664referring to the same List instance. A copy of a List is different from the
665original List. When using "is" without a List it is equivalent to using
666"equal", using "isnot" equivalent to using "not equal". Except that a
667different type means the values are different. "4 == '4'" is true, "4 is '4'"
668is false.
669
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670When comparing a String with a Number, the String is converted to a Number,
671and the comparison is done on Numbers. This means that "0 == 'x'" is TRUE,
672because 'x' converted to a Number is zero.
673
674When comparing two Strings, this is done with strcmp() or stricmp(). This
675results in the mathematical difference (comparing byte values), not
676necessarily the alphabetical difference in the local language.
677
678When using the operators with a trailing '#", or the short version and
679'ignorecase' is off, the comparing is done with strcmp().
680
681When using the operators with a trailing '?', or the short version and
682'ignorecase' is set, the comparing is done with stricmp().
683
684The "=~" and "!~" operators match the lefthand argument with the righthand
685argument, which is used as a pattern. See |pattern| for what a pattern is.
686This matching is always done like 'magic' was set and 'cpoptions' is empty, no
687matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
688portable. To avoid backslashes in the regexp pattern to be doubled, use a
689single-quote string, see |literal-string|.
690Since a string is considered to be a single line, a multi-line pattern
691(containing \n, backslash-n) will not match. However, a literal NL character
692can be matched like an ordinary character. Examples:
693 "foo\nbar" =~ "\n" evaluates to 1
694 "foo\nbar" =~ "\\n" evaluates to 0
695
696
697expr5 and expr6 *expr5* *expr6*
698---------------
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000699expr6 + expr6 .. Number addition or List concatenation *expr-+*
700expr6 - expr6 .. Number subtraction *expr--*
701expr6 . expr6 .. String concatenation *expr-.*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000703For Lists only "+" is possible and then both expr6 must be a list. The result
704is a new list with the two lists Concatenated.
705
706expr7 * expr7 .. number multiplication *expr-star*
707expr7 / expr7 .. number division *expr-/*
708expr7 % expr7 .. number modulo *expr-%*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709
710For all, except ".", Strings are converted to Numbers.
711
712Note the difference between "+" and ".":
713 "123" + "456" = 579
714 "123" . "456" = "123456"
715
716When the righthand side of '/' is zero, the result is 0x7fffffff.
717When the righthand side of '%' is zero, the result is 0.
718
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000719None of these work for Funcrefs.
720
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721
722expr7 *expr7*
723-----
724! expr7 logical NOT *expr-!*
725- expr7 unary minus *expr-unary--*
726+ expr7 unary plus *expr-unary-+*
727
728For '!' non-zero becomes zero, zero becomes one.
729For '-' the sign of the number is changed.
730For '+' the number is unchanged.
731
732A String will be converted to a Number first.
733
734These three can be repeated and mixed. Examples:
735 !-1 == 0
736 !!8 == 1
737 --9 == 9
738
739
740expr8 *expr8*
741-----
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000742expr8[expr1] item of String or List *expr-[]* *E111*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000744If expr8 is a Number or String this results in a String that contains the
745expr1'th single byte from expr8. expr8 is used as a String, expr1 as a
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000746Number. Note that this doesn't recognize multi-byte encodings.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000748Index zero gives the first character. This is like it works in C. Careful:
749text column numbers start with one! Example, to get the character under the
750cursor: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 :let c = getline(line("."))[col(".") - 1]
752
753If the length of the String is less than the index, the result is an empty
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000754String. A negative index always results in an empty string (reason: backwards
755compatibility). Use [-1:] to get the last byte.
756
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000757If expr8 is a List then it results the item at index expr1. See |list-index|
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000758for possible index values. If the index is out of range this results in an
759error. Example: >
760 :let item = mylist[-1] " get last item
761
762Generally, if a List index is equal to or higher than the length of the List,
763or more negative than the length of the List, this results in an error.
764
Bram Moolenaard8b02732005-01-14 21:48:43 +0000765
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000766expr8[expr1a : expr1b] substring or sublist *expr-[:]*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000767
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000768If expr8 is a Number or String this results in the substring with the bytes
769from expr1a to and including expr1b. expr8 is used as a String, expr1a and
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000770expr1b are used as a Number. Note that this doesn't recognize multi-byte
771encodings.
772
773If expr1a is omitted zero is used. If expr1b is omitted the length of the
774string minus one is used.
775
776A negative number can be used to measure from the end of the string. -1 is
777the last character, -2 the last but one, etc.
778
779If an index goes out of range for the string characters are omitted. If
780expr1b is smaller than expr1a the result is an empty string.
781
782Examples: >
783 :let c = name[-1:] " last byte of a string
784 :let c = name[-2:-2] " last but one byte of a string
785 :let s = line(".")[4:] " from the fifth byte to the end
786 :let s = s[:-3] " remove last two bytes
787
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000788If expr8 is a List this results in a new List with the items indicated by the
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000789indexes expr1a and expr1b. This works like with a String, as explained just
790above, except that indexes out of range cause an error. Examples: >
791 :let l = mylist[:3] " first four items
792 :let l = mylist[4:4] " List with one item
793 :let l = mylist[:] " shallow copy of a List
794
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000795Using expr8[expr1] or expr8[expr1a : expr1b] on a Funcref results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796
Bram Moolenaard8b02732005-01-14 21:48:43 +0000797
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000798expr8.name entry in a Dictionary *expr-entry*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000799
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000800If expr8 is a Dictionary and it is followed by a dot, then the following name
801will be used as a key in the Dictionary. This is just like: expr8[name].
Bram Moolenaard8b02732005-01-14 21:48:43 +0000802
803The name must consist of alphanumeric characters, just like a variable name,
804but it may start with a number. Curly braces cannot be used.
805
806There must not be white space before or after the dot.
807
808Examples: >
809 :let dict = {"one": 1, 2: "two"}
810 :echo dict.one
811 :echo dict .2
812
813Note that the dot is also used for String concatenation. To avoid confusion
814always put spaces around the dot for String concatenation.
815
816
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000817expr8(expr1, ...) Funcref function call
818
819When expr8 is a |Funcref| type variable, invoke the function it refers to.
820
821
822
823 *expr9*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824number
825------
826number number constant *expr-number*
827
828Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
829
830
831string *expr-string* *E114*
832------
833"string" string constant *expr-quote*
834
835Note that double quotes are used.
836
837A string constant accepts these special characters:
838\... three-digit octal number (e.g., "\316")
839\.. two-digit octal number (must be followed by non-digit)
840\. one-digit octal number (must be followed by non-digit)
841\x.. byte specified with two hex numbers (e.g., "\x1f")
842\x. byte specified with one hex number (must be followed by non-hex char)
843\X.. same as \x..
844\X. same as \x.
845\u.... character specified with up to 4 hex numbers, stored according to the
846 current value of 'encoding' (e.g., "\u02a4")
847\U.... same as \u....
848\b backspace <BS>
849\e escape <Esc>
850\f formfeed <FF>
851\n newline <NL>
852\r return <CR>
853\t tab <Tab>
854\\ backslash
855\" double quote
856\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W.
857
858Note that "\000" and "\x00" force the end of the string.
859
860
861literal-string *literal-string* *E115*
862---------------
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000863'string' string constant *expr-'*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864
865Note that single quotes are used.
866
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000867This string is taken as it is. No backslashes are removed or have a special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000868meaning. The only exception is that two quotes stand for one quote.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000869
870Single quoted strings are useful for patterns, so that backslashes do not need
871to be doubled. These two commands are equivalent: >
872 if a =~ "\\s*"
873 if a =~ '\s*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
875
876option *expr-option* *E112* *E113*
877------
878&option option value, local value if possible
879&g:option global option value
880&l:option local option value
881
882Examples: >
883 echo "tabstop is " . &tabstop
884 if &insertmode
885
886Any option name can be used here. See |options|. When using the local value
887and there is no buffer-local or window-local value, the global value is used
888anyway.
889
890
891register *expr-register*
892--------
893@r contents of register 'r'
894
895The result is the contents of the named register, as a single string.
896Newlines are inserted where required. To get the contents of the unnamed
897register use @" or @@. The '=' register can not be used here. See
898|registers| for an explanation of the available registers.
899
900
901nesting *expr-nesting* *E110*
902-------
903(expr1) nested expression
904
905
906environment variable *expr-env*
907--------------------
908$VAR environment variable
909
910The String value of any environment variable. When it is not defined, the
911result is an empty string.
912 *expr-env-expand*
913Note that there is a difference between using $VAR directly and using
914expand("$VAR"). Using it directly will only expand environment variables that
915are known inside the current Vim session. Using expand() will first try using
916the environment variables known inside the current Vim session. If that
917fails, a shell will be used to expand the variable. This can be slow, but it
918does expand all variables that the shell knows about. Example: >
919 :echo $version
920 :echo expand("$version")
921The first one probably doesn't echo anything, the second echoes the $version
922variable (if your shell supports it).
923
924
925internal variable *expr-variable*
926-----------------
927variable internal variable
928See below |internal-variables|.
929
930
931function call *expr-function* *E116* *E117* *E118* *E119* *E120*
932-------------
933function(expr1, ...) function call
934See below |functions|.
935
936
937==============================================================================
9383. Internal variable *internal-variables* *E121*
939 *E461*
940An internal variable name can be made up of letters, digits and '_'. But it
941cannot start with a digit. It's also possible to use curly braces, see
942|curly-braces-names|.
943
944An internal variable is created with the ":let" command |:let|.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000945An internal variable is explicitly destroyed with the ":unlet" command
946|:unlet|.
947Using a name that is not an internal variable or refers to a variable that has
948been destroyed results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949
950There are several name spaces for variables. Which one is to be used is
951specified by what is prepended:
952
953 (nothing) In a function: local to a function; otherwise: global
954|buffer-variable| b: Local to the current buffer.
955|window-variable| w: Local to the current window.
956|global-variable| g: Global.
957|local-variable| l: Local to a function.
958|script-variable| s: Local to a |:source|'ed Vim script.
959|function-argument| a: Function argument (only inside a function).
960|vim-variable| v: Global, predefined by Vim.
961
962 *buffer-variable* *b:var*
963A variable name that is preceded with "b:" is local to the current buffer.
964Thus you can have several "b:foo" variables, one for each buffer.
965This kind of variable is deleted when the buffer is wiped out or deleted with
966|:bdelete|.
967
968One local buffer variable is predefined:
969 *b:changedtick-variable* *changetick*
970b:changedtick The total number of changes to the current buffer. It is
971 incremented for each change. An undo command is also a change
972 in this case. This can be used to perform an action only when
973 the buffer has changed. Example: >
974 :if my_changedtick != b:changedtick
975 : let my_changedtick = b:changedtick
976 : call My_Update()
977 :endif
978<
979 *window-variable* *w:var*
980A variable name that is preceded with "w:" is local to the current window. It
981is deleted when the window is closed.
982
983 *global-variable* *g:var*
984Inside functions global variables are accessed with "g:". Omitting this will
985access a variable local to a function. But "g:" can also be used in any other
986place if you like.
987
988 *local-variable* *l:var*
989Inside functions local variables are accessed without prepending anything.
990But you can also prepend "l:" if you like.
991
992 *script-variable* *s:var*
993In a Vim script variables starting with "s:" can be used. They cannot be
994accessed from outside of the scripts, thus are local to the script.
995
996They can be used in:
997- commands executed while the script is sourced
998- functions defined in the script
999- autocommands defined in the script
1000- functions and autocommands defined in functions and autocommands which were
1001 defined in the script (recursively)
1002- user defined commands defined in the script
1003Thus not in:
1004- other scripts sourced from this one
1005- mappings
1006- etc.
1007
1008script variables can be used to avoid conflicts with global variable names.
1009Take this example:
1010
1011 let s:counter = 0
1012 function MyCounter()
1013 let s:counter = s:counter + 1
1014 echo s:counter
1015 endfunction
1016 command Tick call MyCounter()
1017
1018You can now invoke "Tick" from any script, and the "s:counter" variable in
1019that script will not be changed, only the "s:counter" in the script where
1020"Tick" was defined is used.
1021
1022Another example that does the same: >
1023
1024 let s:counter = 0
1025 command Tick let s:counter = s:counter + 1 | echo s:counter
1026
1027When calling a function and invoking a user-defined command, the context for
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001028script variables is set to the script where the function or command was
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029defined.
1030
1031The script variables are also available when a function is defined inside a
1032function that is defined in a script. Example: >
1033
1034 let s:counter = 0
1035 function StartCounting(incr)
1036 if a:incr
1037 function MyCounter()
1038 let s:counter = s:counter + 1
1039 endfunction
1040 else
1041 function MyCounter()
1042 let s:counter = s:counter - 1
1043 endfunction
1044 endif
1045 endfunction
1046
1047This defines the MyCounter() function either for counting up or counting down
1048when calling StartCounting(). It doesn't matter from where StartCounting() is
1049called, the s:counter variable will be accessible in MyCounter().
1050
1051When the same script is sourced again it will use the same script variables.
1052They will remain valid as long as Vim is running. This can be used to
1053maintain a counter: >
1054
1055 if !exists("s:counter")
1056 let s:counter = 1
1057 echo "script executed for the first time"
1058 else
1059 let s:counter = s:counter + 1
1060 echo "script executed " . s:counter . " times now"
1061 endif
1062
1063Note that this means that filetype plugins don't get a different set of script
1064variables for each buffer. Use local buffer variables instead |b:var|.
1065
1066
1067Predefined Vim variables: *vim-variable* *v:var*
1068
1069 *v:charconvert_from* *charconvert_from-variable*
1070v:charconvert_from
1071 The name of the character encoding of a file to be converted.
1072 Only valid while evaluating the 'charconvert' option.
1073
1074 *v:charconvert_to* *charconvert_to-variable*
1075v:charconvert_to
1076 The name of the character encoding of a file after conversion.
1077 Only valid while evaluating the 'charconvert' option.
1078
1079 *v:cmdarg* *cmdarg-variable*
1080v:cmdarg This variable is used for two purposes:
1081 1. The extra arguments given to a file read/write command.
1082 Currently these are "++enc=" and "++ff=". This variable is
1083 set before an autocommand event for a file read/write
1084 command is triggered. There is a leading space to make it
1085 possible to append this variable directly after the
1086 read/write command. Note: The "+cmd" argument isn't
1087 included here, because it will be executed anyway.
1088 2. When printing a PostScript file with ":hardcopy" this is
1089 the argument for the ":hardcopy" command. This can be used
1090 in 'printexpr'.
1091
1092 *v:cmdbang* *cmdbang-variable*
1093v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1094 was used the value is 1, otherwise it is 0. Note that this
1095 can only be used in autocommands. For user commands |<bang>|
1096 can be used.
1097
1098 *v:count* *count-variable*
1099v:count The count given for the last Normal mode command. Can be used
1100 to get the count before a mapping. Read-only. Example: >
1101 :map _x :<C-U>echo "the count is " . v:count<CR>
1102< Note: The <C-U> is required to remove the line range that you
1103 get when typing ':' after a count.
1104 "count" also works, for backwards compatibility.
1105
1106 *v:count1* *count1-variable*
1107v:count1 Just like "v:count", but defaults to one when no count is
1108 used.
1109
1110 *v:ctype* *ctype-variable*
1111v:ctype The current locale setting for characters of the runtime
1112 environment. This allows Vim scripts to be aware of the
1113 current locale encoding. Technical: it's the value of
1114 LC_CTYPE. When not using a locale the value is "C".
1115 This variable can not be set directly, use the |:language|
1116 command.
1117 See |multi-lang|.
1118
1119 *v:dying* *dying-variable*
1120v:dying Normally zero. When a deadly signal is caught it's set to
1121 one. When multiple signals are caught the number increases.
1122 Can be used in an autocommand to check if Vim didn't
1123 terminate normally. {only works on Unix}
1124 Example: >
1125 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
1126<
1127 *v:errmsg* *errmsg-variable*
1128v:errmsg Last given error message. It's allowed to set this variable.
1129 Example: >
1130 :let v:errmsg = ""
1131 :silent! next
1132 :if v:errmsg != ""
1133 : ... handle error
1134< "errmsg" also works, for backwards compatibility.
1135
1136 *v:exception* *exception-variable*
1137v:exception The value of the exception most recently caught and not
1138 finished. See also |v:throwpoint| and |throw-variables|.
1139 Example: >
1140 :try
1141 : throw "oops"
1142 :catch /.*/
1143 : echo "caught" v:exception
1144 :endtry
1145< Output: "caught oops".
1146
1147 *v:fname_in* *fname_in-variable*
1148v:fname_in The name of the input file. Only valid while evaluating:
1149 option used for ~
1150 'charconvert' file to be converted
1151 'diffexpr' original file
1152 'patchexpr' original file
1153 'printexpr' file to be printed
1154
1155 *v:fname_out* *fname_out-variable*
1156v:fname_out The name of the output file. Only valid while
1157 evaluating:
1158 option used for ~
1159 'charconvert' resulting converted file (*)
1160 'diffexpr' output of diff
1161 'patchexpr' resulting patched file
1162 (*) When doing conversion for a write command (e.g., ":w
1163 file") it will be equal to v:fname_in. When doing conversion
1164 for a read command (e.g., ":e file") it will be a temporary
1165 file and different from v:fname_in.
1166
1167 *v:fname_new* *fname_new-variable*
1168v:fname_new The name of the new version of the file. Only valid while
1169 evaluating 'diffexpr'.
1170
1171 *v:fname_diff* *fname_diff-variable*
1172v:fname_diff The name of the diff (patch) file. Only valid while
1173 evaluating 'patchexpr'.
1174
1175 *v:folddashes* *folddashes-variable*
1176v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
1177 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001178 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179
1180 *v:foldlevel* *foldlevel-variable*
1181v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001182 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183
1184 *v:foldend* *foldend-variable*
1185v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001186 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187
1188 *v:foldstart* *foldstart-variable*
1189v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001190 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191
Bram Moolenaar843ee412004-06-30 16:16:41 +00001192 *v:insertmode* *insertmode-variable*
1193v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
1194 events. Values:
1195 i Insert mode
1196 r Replace mode
1197 v Virtual Replace mode
1198
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001199 *v:key* *key-variable*
1200v:key Key of the current item of a Dictionary. Only valid while
1201 evaluating the expression used with |map()| and |filter()|.
1202 Read-only.
1203
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 *v:lang* *lang-variable*
1205v:lang The current locale setting for messages of the runtime
1206 environment. This allows Vim scripts to be aware of the
1207 current language. Technical: it's the value of LC_MESSAGES.
1208 The value is system dependent.
1209 This variable can not be set directly, use the |:language|
1210 command.
1211 It can be different from |v:ctype| when messages are desired
1212 in a different language than what is used for character
1213 encoding. See |multi-lang|.
1214
1215 *v:lc_time* *lc_time-variable*
1216v:lc_time The current locale setting for time messages of the runtime
1217 environment. This allows Vim scripts to be aware of the
1218 current language. Technical: it's the value of LC_TIME.
1219 This variable can not be set directly, use the |:language|
1220 command. See |multi-lang|.
1221
1222 *v:lnum* *lnum-variable*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001223v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr'
1224 expressions. Only valid while one of these expressions is
1225 being evaluated. Read-only when in the |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226
1227 *v:prevcount* *prevcount-variable*
1228v:prevcount The count given for the last but one Normal mode command.
1229 This is the v:count value of the previous command. Useful if
1230 you want to cancel Visual mode and then use the count. >
1231 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
1232< Read-only.
1233
1234 *v:progname* *progname-variable*
1235v:progname Contains the name (with path removed) with which Vim was
1236 invoked. Allows you to do special initialisations for "view",
1237 "evim" etc., or any other name you might symlink to Vim.
1238 Read-only.
1239
1240 *v:register* *register-variable*
1241v:register The name of the register supplied to the last normal mode
1242 command. Empty if none were supplied. |getreg()| |setreg()|
1243
1244 *v:servername* *servername-variable*
1245v:servername The resulting registered |x11-clientserver| name if any.
1246 Read-only.
1247
1248 *v:shell_error* *shell_error-variable*
1249v:shell_error Result of the last shell command. When non-zero, the last
1250 shell command had an error. When zero, there was no problem.
1251 This only works when the shell returns the error code to Vim.
1252 The value -1 is often used when the command could not be
1253 executed. Read-only.
1254 Example: >
1255 :!mv foo bar
1256 :if v:shell_error
1257 : echo 'could not rename "foo" to "bar"!'
1258 :endif
1259< "shell_error" also works, for backwards compatibility.
1260
1261 *v:statusmsg* *statusmsg-variable*
1262v:statusmsg Last given status message. It's allowed to set this variable.
1263
1264 *v:termresponse* *termresponse-variable*
1265v:termresponse The escape sequence returned by the terminal for the |t_RV|
1266 termcap entry. It is set when Vim receives an escape sequence
1267 that starts with ESC [ or CSI and ends in a 'c', with only
1268 digits, ';' and '.' in between.
1269 When this option is set, the TermResponse autocommand event is
1270 fired, so that you can react to the response from the
1271 terminal.
1272 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
1273 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
1274 patch level (since this was introduced in patch 95, it's
1275 always 95 or bigger). Pc is always zero.
1276 {only when compiled with |+termresponse| feature}
1277
1278 *v:this_session* *this_session-variable*
1279v:this_session Full filename of the last loaded or saved session file. See
1280 |:mksession|. It is allowed to set this variable. When no
1281 session file has been saved, this variable is empty.
1282 "this_session" also works, for backwards compatibility.
1283
1284 *v:throwpoint* *throwpoint-variable*
1285v:throwpoint The point where the exception most recently caught and not
1286 finished was thrown. Not set when commands are typed. See
1287 also |v:exception| and |throw-variables|.
1288 Example: >
1289 :try
1290 : throw "oops"
1291 :catch /.*/
1292 : echo "Exception from" v:throwpoint
1293 :endtry
1294< Output: "Exception from test.vim, line 2"
1295
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001296 *v:val* *val-variable*
1297v:val Value of the current item of a List or Dictionary. Only valid
1298 while evaluating the expression used with |map()| and
1299 |filter()|. Read-only.
1300
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301 *v:version* *version-variable*
1302v:version Version number of Vim: Major version number times 100 plus
1303 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
1304 is 501. Read-only. "version" also works, for backwards
1305 compatibility.
1306 Use |has()| to check if a certain patch was included, e.g.: >
1307 if has("patch123")
1308< Note that patch numbers are specific to the version, thus both
1309 version 5.0 and 5.1 may have a patch 123, but these are
1310 completely different.
1311
1312 *v:warningmsg* *warningmsg-variable*
1313v:warningmsg Last given warning message. It's allowed to set this variable.
1314
1315==============================================================================
13164. Builtin Functions *functions*
1317
1318See |function-list| for a list grouped by what the function is used for.
1319
1320(Use CTRL-] on the function name to jump to the full explanation)
1321
1322USAGE RESULT DESCRIPTION ~
1323
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001324add( {list}, {item}) List append {item} to List {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001325append( {lnum}, {string}) Number append {string} below line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326argc() Number number of files in the argument list
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001327argidx() Number current index in the argument list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328argv( {nr}) String {nr} entry of the argument list
1329browse( {save}, {title}, {initdir}, {default})
1330 String put up a file requester
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001331browsedir( {title}, {initdir}) String put up a directory requester
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332bufexists( {expr}) Number TRUE if buffer {expr} exists
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001333buflisted( {expr}) Number TRUE if buffer {expr} is listed
1334bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335bufname( {expr}) String Name of the buffer {expr}
1336bufnr( {expr}) Number Number of the buffer {expr}
1337bufwinnr( {expr}) Number window number of buffer {expr}
1338byte2line( {byte}) Number line number at byte count {byte}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001339byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001340call( {func}, {arglist} [, {dict}])
1341 any call {func} with arguments {arglist}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342char2nr( {expr}) Number ASCII value of first char in {expr}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001343cindent( {lnum}) Number C indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001344col( {expr}) Number column nr of cursor or mark
1345confirm( {msg} [, {choices} [, {default} [, {type}]]])
1346 Number number of choice picked by user
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001347copy( {expr}) any make a shallow copy of {expr}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001348count( {list}, {expr} [, {start} [, {ic}]])
1349 Number count how many {expr} are in {list}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350cscope_connection( [{num} , {dbpath} [, {prepend}]])
1351 Number checks existence of cscope connection
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001352cursor( {lnum}, {col}) Number position cursor at {lnum}, {col}
1353deepcopy( {expr}) any make a full copy of {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001354delete( {fname}) Number delete file {fname}
1355did_filetype() Number TRUE if FileType autocommand event used
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001356diff_filler( {lnum}) Number diff filler lines about {lnum}
1357diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
Bram Moolenaar13065c42005-01-08 16:08:21 +00001358empty( {expr}) Number TRUE if {expr} is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359escape( {string}, {chars}) String escape {chars} in {string} with '\'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001360eval( {string}) any evaluate {string} into its value
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001361eventhandler( ) Number TRUE if inside an event handler
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362executable( {expr}) Number 1 if executable {expr} exists
1363exists( {expr}) Number TRUE if {expr} exists
1364expand( {expr}) String expand special keywords in {expr}
1365filereadable( {file}) Number TRUE if {file} is a readable file
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001366filter( {expr}, {string}) List/Dict remove items from {expr} where
1367 {string} is 0
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001368finddir( {name}[, {path}[, {count}]])
1369 String Find directory {name} in {path}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001370findfile( {name}[, {path}[, {count}]])
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001371 String Find file {name} in {path}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372filewritable( {file}) Number TRUE if {file} is a writable file
1373fnamemodify( {fname}, {mods}) String modify file name
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001374foldclosed( {lnum}) Number first line of fold at {lnum} if closed
1375foldclosedend( {lnum}) Number last line of fold at {lnum} if closed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376foldlevel( {lnum}) Number fold level at {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001377foldtext( ) String line displayed for closed fold
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378foreground( ) Number bring the Vim window to the foreground
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001379function( {name}) Funcref reference to function {name}
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001380get( {list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001381get( {dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001382getchar( [expr]) Number get one character from the user
1383getcharmod( ) Number modifiers for the last typed character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384getbufvar( {expr}, {varname}) variable {varname} in buffer {expr}
1385getcmdline() String return the current command-line
1386getcmdpos() Number return cursor position in command-line
1387getcwd() String the current working directory
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001388getfperm( {fname}) String file permissions of file {fname}
1389getfsize( {fname}) Number size in bytes of file {fname}
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001390getfontname( [{name}]) String name of font being used
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391getftime( {fname}) Number last modification time of file
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001392getftype( {fname}) String description of type of file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393getline( {lnum}) String line {lnum} from current buffer
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001394getreg( [{regname}]) String contents of register
1395getregtype( [{regname}]) String type of register
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396getwinposx() Number X coord in pixels of GUI Vim window
1397getwinposy() Number Y coord in pixels of GUI Vim window
1398getwinvar( {nr}, {varname}) variable {varname} in window {nr}
1399glob( {expr}) String expand file wildcards in {expr}
1400globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path}
1401has( {feature}) Number TRUE if feature {feature} supported
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001402has_key( {dict}, {key}) Number TRUE if {dict} has entry {key}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001403hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists
1404histadd( {history},{item}) String add an item to a history
1405histdel( {history} [, {item}]) String remove an item from a history
1406histget( {history} [, {index}]) String get the item {index} from a history
1407histnr( {history}) Number highest index of a history
1408hlexists( {name}) Number TRUE if highlight group {name} exists
1409hlID( {name}) Number syntax ID of highlight group {name}
1410hostname() String name of the machine Vim is running on
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001411iconv( {expr}, {from}, {to}) String convert encoding of {expr}
1412indent( {lnum}) Number indent of line {lnum}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001413index( {list}, {expr} [, {start} [, {ic}]])
1414 Number index in {list} where {expr} appears
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415input( {prompt} [, {text}]) String get input from the user
1416inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001417inputrestore() Number restore typeahead
1418inputsave() Number save and clear typeahead
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419inputsecret( {prompt} [, {text}]) String like input() but hiding the text
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001420insert( {list}, {item} [, {idx}]) List insert {item} in {list} [before {idx}]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421isdirectory( {directory}) Number TRUE if {directory} is a directory
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001422join( {list} [, {sep}]) String join {list} items into one String
Bram Moolenaard8b02732005-01-14 21:48:43 +00001423keys( {dict}) List List of keys in {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001424len( {expr}) Number the length of {expr}
1425libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number
1427line( {expr}) Number line nr of cursor, last line or mark
1428line2byte( {lnum}) Number byte count of line {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001429lispindent( {lnum}) Number Lisp indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430localtime() Number current time
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001431map( {expr}, {string}) List/Dict change each item in {expr} to {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
1433mapcheck( {name}[, {mode}]) String check for mappings matching {name}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001434match( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435 Number position where {pat} matches in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001436matchend( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 Number position where {pat} ends in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001438matchstr( {expr}, {pat}[, {start}[, {count}]])
1439 String {count}'th match of {pat} in {expr}
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001440max({list}) Number maximum value of items in {list}
1441min({list}) Number minumum value of items in {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001442mode() String current editing mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum}
1444nr2char( {expr}) String single char with ASCII value {expr}
1445prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001446range( {expr} [, {max} [, {stride}]])
1447 List items from {expr} to {max}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448remote_expr( {server}, {string} [, {idvar}])
1449 String send expression
1450remote_foreground( {server}) Number bring Vim server to the foreground
1451remote_peek( {serverid} [, {retvar}])
1452 Number check for reply string
1453remote_read( {serverid}) String read reply string
1454remote_send( {server}, {string} [, {idvar}])
1455 String send key sequence
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001456remove( {list}, {idx} [, {end}]) any remove items {idx}-{end} from {list}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001457remove( {dict}, {key}) any remove entry {key} from {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001458rename( {from}, {to}) Number rename (move) file from {from} to {to}
1459repeat( {expr}, {count}) String repeat {expr} {count} times
1460resolve( {filename}) String get filename a shortcut points to
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001461reverse( {list}) List reverse {list} in-place
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001462search( {pattern} [, {flags}]) Number search for {pattern}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001464 Number search for other end of start/end pair
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465server2client( {clientid}, {string})
1466 Number send reply string
1467serverlist() String get a list of available servers
1468setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val}
1469setcmdpos( {pos}) Number set cursor position in command-line
1470setline( {lnum}, {line}) Number set line {lnum} to {line}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001471setreg( {n}, {v}[, {opt}]) Number set register to value and type
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001473simplify( {filename}) String simplify filename as much as possible
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001474sort( {list} [, {func}]) List sort {list}, using {func} to compare
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001475split( {expr} [, {pat}]) List make List from {pat} separated {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476strftime( {format}[, {time}]) String time in specified format
1477stridx( {haystack}, {needle}) Number first index of {needle} in {haystack}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001478string( {expr}) String String representation of {expr} value
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479strlen( {expr}) Number length of the String {expr}
1480strpart( {src}, {start}[, {len}])
1481 String {len} characters of {src} at {start}
1482strridx( {haystack}, {needle}) Number last index of {needle} in {haystack}
1483strtrans( {expr}) String translate string to make it printable
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001484submatch( {nr}) String specific match in ":substitute"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485substitute( {expr}, {pat}, {sub}, {flags})
1486 String all {pat} in {expr} replaced with {sub}
Bram Moolenaar47136d72004-10-12 20:02:24 +00001487synID( {lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488synIDattr( {synID}, {what} [, {mode}])
1489 String attribute {what} of syntax ID {synID}
1490synIDtrans( {synID}) Number translated syntax ID of {synID}
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001491system( {expr} [, {input}]) String output of shell command/filter {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492tempname() String name for a temporary file
1493tolower( {expr}) String the String {expr} switched to lowercase
1494toupper( {expr}) String the String {expr} switched to uppercase
Bram Moolenaar8299df92004-07-10 09:47:34 +00001495tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr}
1496 to chars in {tostr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497type( {name}) Number type of variable {name}
1498virtcol( {expr}) Number screen column of cursor or mark
1499visualmode( [expr]) String last visual mode used
1500winbufnr( {nr}) Number buffer number of window {nr}
1501wincol() Number window column of the cursor
1502winheight( {nr}) Number height of window {nr}
1503winline() Number window line of the cursor
1504winnr() Number number of current window
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001505winrestcmd() String returns command to restore window sizes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506winwidth( {nr}) Number width of window {nr}
1507
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001508add({list}, {expr}) *add()*
1509 Append the item {expr} to List {list}. Returns the resulting
1510 List. Examples: >
1511 :let alist = add([1, 2, 3], item)
1512 :call add(mylist, "woodstock")
1513< Note that when {expr} is a List it is appended as a single
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001514 item. Use |extend()| to concatenate Lists.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001515 Use |insert()| to add an item at another position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001517
1518append({lnum}, {expr}) *append()*
1519 When {expr} is a List: Append each item of the list as a text
1520 line below line {lnum} in the current buffer.
1521 Otherwise append the text line {expr} below line {lnum} in the
1522 current buffer.
1523 {lnum} can be zero, to insert a line before the first one.
1524 Returns 1 for failure ({lnum} out of range or out of memory),
1525 0 for success. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001526 :let failed = append(line('$'), "# THE END")
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001527 :let failed = append(0, ["Chapter 1", "the beginning"])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001528<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 *argc()*
1530argc() The result is the number of files in the argument list of the
1531 current window. See |arglist|.
1532
1533 *argidx()*
1534argidx() The result is the current index in the argument list. 0 is
1535 the first file. argc() - 1 is the last one. See |arglist|.
1536
1537 *argv()*
1538argv({nr}) The result is the {nr}th file in the argument list of the
1539 current window. See |arglist|. "argv(0)" is the first one.
1540 Example: >
1541 :let i = 0
1542 :while i < argc()
1543 : let f = escape(argv(i), '. ')
1544 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
1545 : let i = i + 1
1546 :endwhile
1547<
1548 *browse()*
1549browse({save}, {title}, {initdir}, {default})
1550 Put up a file requester. This only works when "has("browse")"
1551 returns non-zero (only in some GUI versions).
1552 The input fields are:
1553 {save} when non-zero, select file to write
1554 {title} title for the requester
1555 {initdir} directory to start browsing in
1556 {default} default file name
1557 When the "Cancel" button is hit, something went wrong, or
1558 browsing is not possible, an empty string is returned.
1559
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001560 *browsedir()*
1561browsedir({title}, {initdir})
1562 Put up a directory requester. This only works when
1563 "has("browse")" returns non-zero (only in some GUI versions).
1564 On systems where a directory browser is not supported a file
1565 browser is used. In that case: select a file in the directory
1566 to be used.
1567 The input fields are:
1568 {title} title for the requester
1569 {initdir} directory to start browsing in
1570 When the "Cancel" button is hit, something went wrong, or
1571 browsing is not possible, an empty string is returned.
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573bufexists({expr}) *bufexists()*
1574 The result is a Number, which is non-zero if a buffer called
1575 {expr} exists.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001576 If the {expr} argument is a number, buffer numbers are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 If the {expr} argument is a string it must match a buffer name
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001578 exactly. The name can be:
1579 - Relative to the current directory.
1580 - A full path.
1581 - The name of a buffer with 'filetype' set to "nofile".
1582 - A URL name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 Unlisted buffers will be found.
1584 Note that help files are listed by their short name in the
1585 output of |:buffers|, but bufexists() requires using their
1586 long name to be able to find them.
1587 Use "bufexists(0)" to test for the existence of an alternate
1588 file name.
1589 *buffer_exists()*
1590 Obsolete name: buffer_exists().
1591
1592buflisted({expr}) *buflisted()*
1593 The result is a Number, which is non-zero if a buffer called
1594 {expr} exists and is listed (has the 'buflisted' option set).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001595 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596
1597bufloaded({expr}) *bufloaded()*
1598 The result is a Number, which is non-zero if a buffer called
1599 {expr} exists and is loaded (shown in a window or hidden).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001600 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
1602bufname({expr}) *bufname()*
1603 The result is the name of a buffer, as it is displayed by the
1604 ":ls" command.
1605 If {expr} is a Number, that buffer number's name is given.
1606 Number zero is the alternate buffer for the current window.
1607 If {expr} is a String, it is used as a |file-pattern| to match
1608 with the buffer names. This is always done like 'magic' is
1609 set and 'cpoptions' is empty. When there is more than one
1610 match an empty string is returned.
1611 "" or "%" can be used for the current buffer, "#" for the
1612 alternate buffer.
1613 A full match is preferred, otherwise a match at the start, end
1614 or middle of the buffer name is accepted.
1615 Listed buffers are found first. If there is a single match
1616 with a listed buffer, that one is returned. Next unlisted
1617 buffers are searched for.
1618 If the {expr} is a String, but you want to use it as a buffer
1619 number, force it to be a Number by adding zero to it: >
1620 :echo bufname("3" + 0)
1621< If the buffer doesn't exist, or doesn't have a name, an empty
1622 string is returned. >
1623 bufname("#") alternate buffer name
1624 bufname(3) name of buffer 3
1625 bufname("%") name of current buffer
1626 bufname("file2") name of buffer where "file2" matches.
1627< *buffer_name()*
1628 Obsolete name: buffer_name().
1629
1630 *bufnr()*
1631bufnr({expr}) The result is the number of a buffer, as it is displayed by
1632 the ":ls" command. For the use of {expr}, see |bufname()|
1633 above. If the buffer doesn't exist, -1 is returned.
1634 bufnr("$") is the last buffer: >
1635 :let last_buffer = bufnr("$")
1636< The result is a Number, which is the highest buffer number
1637 of existing buffers. Note that not all buffers with a smaller
1638 number necessarily exist, because ":bwipeout" may have removed
1639 them. Use bufexists() to test for the existence of a buffer.
1640 *buffer_number()*
1641 Obsolete name: buffer_number().
1642 *last_buffer_nr()*
1643 Obsolete name for bufnr("$"): last_buffer_nr().
1644
1645bufwinnr({expr}) *bufwinnr()*
1646 The result is a Number, which is the number of the first
1647 window associated with buffer {expr}. For the use of {expr},
1648 see |bufname()| above. If buffer {expr} doesn't exist or
1649 there is no such window, -1 is returned. Example: >
1650
1651 echo "A window containing buffer 1 is " . (bufwinnr(1))
1652
1653< The number can be used with |CTRL-W_w| and ":wincmd w"
1654 |:wincmd|.
1655
1656
1657byte2line({byte}) *byte2line()*
1658 Return the line number that contains the character at byte
1659 count {byte} in the current buffer. This includes the
1660 end-of-line character, depending on the 'fileformat' option
1661 for the current buffer. The first character has byte count
1662 one.
1663 Also see |line2byte()|, |go| and |:goto|.
1664 {not available when compiled without the |+byte_offset|
1665 feature}
1666
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001667byteidx({expr}, {nr}) *byteidx()*
1668 Return byte index of the {nr}'th character in the string
1669 {expr}. Use zero for the first character, it returns zero.
1670 This function is only useful when there are multibyte
1671 characters, otherwise the returned value is equal to {nr}.
1672 Composing characters are counted as a separate character.
1673 Example : >
1674 echo matchstr(str, ".", byteidx(str, 3))
1675< will display the fourth character. Another way to do the
1676 same: >
1677 let s = strpart(str, byteidx(str, 3))
1678 echo strpart(s, 0, byteidx(s, 1))
1679< If there are less than {nr} characters -1 is returned.
1680 If there are exactly {nr} characters the length of the string
1681 is returned.
1682
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001683call({func}, {arglist} [, {dict}]) *call()* *E699*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001684 Call function {func} with the items in List {arglist} as
1685 arguments.
1686 {func} can either be a Funcref or the name of a function.
1687 a:firstline and a:lastline are set to the cursor line.
1688 Returns the return value of the called function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001689 {dict} is for functions with the "dict" attribute. It will be
1690 used to set the local variable "self". |Dictionary-function|
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001691
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692char2nr({expr}) *char2nr()*
1693 Return number value of the first char in {expr}. Examples: >
1694 char2nr(" ") returns 32
1695 char2nr("ABC") returns 65
1696< The current 'encoding' is used. Example for "utf-8": >
1697 char2nr("á") returns 225
1698 char2nr("á"[0]) returns 195
1699
1700cindent({lnum}) *cindent()*
1701 Get the amount of indent for line {lnum} according the C
1702 indenting rules, as with 'cindent'.
1703 The indent is counted in spaces, the value of 'tabstop' is
1704 relevant. {lnum} is used just like in |getline()|.
1705 When {lnum} is invalid or Vim was not compiled the |+cindent|
1706 feature, -1 is returned.
1707
1708 *col()*
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001709col({expr}) The result is a Number, which is the byte index of the column
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 position given with {expr}. The accepted positions are:
1711 . the cursor position
1712 $ the end of the cursor line (the result is the
1713 number of characters in the cursor line plus one)
1714 'x position of mark x (if the mark is not set, 0 is
1715 returned)
1716 For the screen column position use |virtcol()|.
1717 Note that only marks in the current file can be used.
1718 Examples: >
1719 col(".") column of cursor
1720 col("$") length of cursor line plus one
1721 col("'t") column of mark t
1722 col("'" . markname) column of mark markname
1723< The first column is 1. 0 is returned for an error.
1724 For the cursor position, when 'virtualedit' is active, the
1725 column is one higher if the cursor is after the end of the
1726 line. This can be used to obtain the column in Insert mode: >
1727 :imap <F2> <C-O>:let save_ve = &ve<CR>
1728 \<C-O>:set ve=all<CR>
1729 \<C-O>:echo col(".") . "\n" <Bar>
1730 \let &ve = save_ve<CR>
1731<
1732 *confirm()*
1733confirm({msg} [, {choices} [, {default} [, {type}]]])
1734 Confirm() offers the user a dialog, from which a choice can be
1735 made. It returns the number of the choice. For the first
1736 choice this is 1.
1737 Note: confirm() is only supported when compiled with dialog
1738 support, see |+dialog_con| and |+dialog_gui|.
1739 {msg} is displayed in a |dialog| with {choices} as the
1740 alternatives. When {choices} is missing or empty, "&OK" is
1741 used (and translated).
1742 {msg} is a String, use '\n' to include a newline. Only on
1743 some systems the string is wrapped when it doesn't fit.
1744 {choices} is a String, with the individual choices separated
1745 by '\n', e.g. >
1746 confirm("Save changes?", "&Yes\n&No\n&Cancel")
1747< The letter after the '&' is the shortcut key for that choice.
1748 Thus you can type 'c' to select "Cancel". The shortcut does
1749 not need to be the first letter: >
1750 confirm("file has been modified", "&Save\nSave &All")
1751< For the console, the first letter of each choice is used as
1752 the default shortcut key.
1753 The optional {default} argument is the number of the choice
1754 that is made if the user hits <CR>. Use 1 to make the first
1755 choice the default one. Use 0 to not set a default. If
1756 {default} is omitted, 1 is used.
1757 The optional {type} argument gives the type of dialog. This
1758 is only used for the icon of the Win32 GUI. It can be one of
1759 these values: "Error", "Question", "Info", "Warning" or
1760 "Generic". Only the first character is relevant. When {type}
1761 is omitted, "Generic" is used.
1762 If the user aborts the dialog by pressing <Esc>, CTRL-C,
1763 or another valid interrupt key, confirm() returns 0.
1764
1765 An example: >
1766 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
1767 :if choice == 0
1768 : echo "make up your mind!"
1769 :elseif choice == 3
1770 : echo "tasteful"
1771 :else
1772 : echo "I prefer bananas myself."
1773 :endif
1774< In a GUI dialog, buttons are used. The layout of the buttons
1775 depends on the 'v' flag in 'guioptions'. If it is included,
1776 the buttons are always put vertically. Otherwise, confirm()
1777 tries to put the buttons in one horizontal line. If they
1778 don't fit, a vertical layout is used anyway. For some systems
1779 the horizontal layout is always used.
1780
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001781 *copy()*
1782copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
1783 different from using {expr} directly.
1784 When {expr} is a List a shallow copy is created. This means
1785 that the original List can be changed without changing the
1786 copy, and vise versa. But the items are identical, thus
1787 changing an item changes the contents of both Lists. Also see
1788 |deepcopy()|.
1789
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001790count({comp}, {expr} [, {ic} [, {start}]]) *count()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001791 Return the number of times an item with value {expr} appears
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001792 in List or Dictionary {comp}.
1793 If {start} is given then start with the item with this index.
1794 {start} can only be used with a List.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001795 When {ic} is given and it's non-zero then case is ignored.
1796
1797
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 *cscope_connection()*
1799cscope_connection([{num} , {dbpath} [, {prepend}]])
1800 Checks for the existence of a |cscope| connection. If no
1801 parameters are specified, then the function returns:
1802 0, if cscope was not available (not compiled in), or
1803 if there are no cscope connections;
1804 1, if there is at least one cscope connection.
1805
1806 If parameters are specified, then the value of {num}
1807 determines how existence of a cscope connection is checked:
1808
1809 {num} Description of existence check
1810 ----- ------------------------------
1811 0 Same as no parameters (e.g., "cscope_connection()").
1812 1 Ignore {prepend}, and use partial string matches for
1813 {dbpath}.
1814 2 Ignore {prepend}, and use exact string matches for
1815 {dbpath}.
1816 3 Use {prepend}, use partial string matches for both
1817 {dbpath} and {prepend}.
1818 4 Use {prepend}, use exact string matches for both
1819 {dbpath} and {prepend}.
1820
1821 Note: All string comparisons are case sensitive!
1822
1823 Examples. Suppose we had the following (from ":cs show"): >
1824
1825 # pid database name prepend path
1826 0 27664 cscope.out /usr/local
1827<
1828 Invocation Return Val ~
1829 ---------- ---------- >
1830 cscope_connection() 1
1831 cscope_connection(1, "out") 1
1832 cscope_connection(2, "out") 0
1833 cscope_connection(3, "out") 0
1834 cscope_connection(3, "out", "local") 1
1835 cscope_connection(4, "out") 0
1836 cscope_connection(4, "out", "local") 0
1837 cscope_connection(4, "cscope.out", "/usr/local") 1
1838<
1839cursor({lnum}, {col}) *cursor()*
1840 Positions the cursor at the column {col} in the line {lnum}.
1841 Does not change the jumplist.
1842 If {lnum} is greater than the number of lines in the buffer,
1843 the cursor will be positioned at the last line in the buffer.
1844 If {lnum} is zero, the cursor will stay in the current line.
1845 If {col} is greater than the number of characters in the line,
1846 the cursor will be positioned at the last character in the
1847 line.
1848 If {col} is zero, the cursor will stay in the current column.
1849
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001850
Bram Moolenaar13065c42005-01-08 16:08:21 +00001851deepcopy({expr}) *deepcopy()* *E698*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001852 Make a copy of {expr}. For Numbers and Strings this isn't
1853 different from using {expr} directly.
1854 When {expr} is a List a full copy is created. This means
1855 that the original List can be changed without changing the
1856 copy, and vise versa. When an item is a List, a copy for it
1857 is made, recursively. Thus changing an item in the copy does
1858 not change the contents of the original List.
1859 Also see |copy()|.
1860
1861delete({fname}) *delete()*
1862 Deletes the file by the name {fname}. The result is a Number,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863 which is 0 if the file was deleted successfully, and non-zero
1864 when the deletion failed.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001865 Use |remove()| to delete an item from a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001866
1867 *did_filetype()*
1868did_filetype() Returns non-zero when autocommands are being executed and the
1869 FileType event has been triggered at least once. Can be used
1870 to avoid triggering the FileType event again in the scripts
1871 that detect the file type. |FileType|
1872 When editing another file, the counter is reset, thus this
1873 really checks if the FileType event has been triggered for the
1874 current buffer. This allows an autocommand that starts
1875 editing another buffer to set 'filetype' and load a syntax
1876 file.
1877
Bram Moolenaar47136d72004-10-12 20:02:24 +00001878diff_filler({lnum}) *diff_filler()*
1879 Returns the number of filler lines above line {lnum}.
1880 These are the lines that were inserted at this point in
1881 another diff'ed window. These filler lines are shown in the
1882 display but don't exist in the buffer.
1883 {lnum} is used like with |getline()|. Thus "." is the current
1884 line, "'m" mark m, etc.
1885 Returns 0 if the current window is not in diff mode.
1886
1887diff_hlID({lnum}, {col}) *diff_hlID()*
1888 Returns the highlight ID for diff mode at line {lnum} column
1889 {col} (byte index). When the current line does not have a
1890 diff change zero is returned.
1891 {lnum} is used like with |getline()|. Thus "." is the current
1892 line, "'m" mark m, etc.
1893 {col} is 1 for the leftmost column, {lnum} is 1 for the first
1894 line.
1895 The highlight ID can be used with |synIDattr()| to obtain
1896 syntax information about the highlighting.
1897
Bram Moolenaar13065c42005-01-08 16:08:21 +00001898empty({expr}) *empty()*
1899 Return the Number 1 if {expr} is empty, zero otherwise.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001900 A List or Dictionary is empty when it does not have any items.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001901 A Number is empty when its value is zero.
1902 For a long List this is much faster then comparing the length
1903 with zero.
1904
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905escape({string}, {chars}) *escape()*
1906 Escape the characters in {chars} that occur in {string} with a
1907 backslash. Example: >
1908 :echo escape('c:\program files\vim', ' \')
1909< results in: >
1910 c:\\program\ files\\vim
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001911
1912< *eval()*
1913eval({string}) Evaluate {string} and return the result. Especially useful to
1914 turn the result of |string()| back into the original value.
1915 This works for Numbers, Strings and composites of them.
1916 Also works for Funcrefs that refer to existing functions.
1917
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918eventhandler() *eventhandler()*
1919 Returns 1 when inside an event handler. That is that Vim got
1920 interrupted while waiting for the user to type a character,
1921 e.g., when dropping a file on Vim. This means interactive
1922 commands cannot be used. Otherwise zero is returned.
1923
1924executable({expr}) *executable()*
1925 This function checks if an executable with the name {expr}
1926 exists. {expr} must be the name of the program without any
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001927 arguments.
1928 executable() uses the value of $PATH and/or the normal
1929 searchpath for programs. *PATHEXT*
1930 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
1931 optionally be included. Then the extensions in $PATHEXT are
1932 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
1933 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
1934 used. A dot by itself can be used in $PATHEXT to try using
1935 the name without an extension. When 'shell' looks like a
1936 Unix shell, then the name is also tried without adding an
1937 extension.
1938 On MS-DOS and MS-Windows it only checks if the file exists and
1939 is not a directory, not if it's really executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 The result is a Number:
1941 1 exists
1942 0 does not exist
1943 -1 not implemented on this system
1944
1945 *exists()*
1946exists({expr}) The result is a Number, which is non-zero if {expr} is
1947 defined, zero otherwise. The {expr} argument is a string,
1948 which contains one of these:
1949 &option-name Vim option (only checks if it exists,
1950 not if it really works)
1951 +option-name Vim option that works.
1952 $ENVNAME environment variable (could also be
1953 done by comparing with an empty
1954 string)
1955 *funcname built-in function (see |functions|)
1956 or user defined function (see
1957 |user-functions|).
1958 varname internal variable (see
1959 |internal-variables|). Does not work
1960 for |curly-braces-names|.
1961 :cmdname Ex command: built-in command, user
1962 command or command modifier |:command|.
1963 Returns:
1964 1 for match with start of a command
1965 2 full match with a command
1966 3 matches several user commands
1967 To check for a supported command
1968 always check the return value to be 2.
1969 #event autocommand defined for this event
1970 #event#pattern autocommand defined for this event and
1971 pattern (the pattern is taken
1972 literally and compared to the
1973 autocommand patterns character by
1974 character)
1975 For checking for a supported feature use |has()|.
1976
1977 Examples: >
1978 exists("&shortname")
1979 exists("$HOSTNAME")
1980 exists("*strftime")
1981 exists("*s:MyFunc")
1982 exists("bufcount")
1983 exists(":Make")
1984 exists("#CursorHold");
1985 exists("#BufReadPre#*.gz")
1986< There must be no space between the symbol (&/$/*/#) and the
1987 name.
1988 Note that the argument must be a string, not the name of the
1989 variable itself! For example: >
1990 exists(bufcount)
1991< This doesn't check for existence of the "bufcount" variable,
1992 but gets the contents of "bufcount", and checks if that
1993 exists.
1994
1995expand({expr} [, {flag}]) *expand()*
1996 Expand wildcards and the following special keywords in {expr}.
1997 The result is a String.
1998
1999 When there are several matches, they are separated by <NL>
2000 characters. [Note: in version 5.0 a space was used, which
2001 caused problems when a file name contains a space]
2002
2003 If the expansion fails, the result is an empty string. A name
2004 for a non-existing file is not included.
2005
2006 When {expr} starts with '%', '#' or '<', the expansion is done
2007 like for the |cmdline-special| variables with their associated
2008 modifiers. Here is a short overview:
2009
2010 % current file name
2011 # alternate file name
2012 #n alternate file name n
2013 <cfile> file name under the cursor
2014 <afile> autocmd file name
2015 <abuf> autocmd buffer number (as a String!)
2016 <amatch> autocmd matched name
2017 <sfile> sourced script file name
2018 <cword> word under the cursor
2019 <cWORD> WORD under the cursor
2020 <client> the {clientid} of the last received
2021 message |server2client()|
2022 Modifiers:
2023 :p expand to full path
2024 :h head (last path component removed)
2025 :t tail (last path component only)
2026 :r root (one extension removed)
2027 :e extension only
2028
2029 Example: >
2030 :let &tags = expand("%:p:h") . "/tags"
2031< Note that when expanding a string that starts with '%', '#' or
2032 '<', any following text is ignored. This does NOT work: >
2033 :let doesntwork = expand("%:h.bak")
2034< Use this: >
2035 :let doeswork = expand("%:h") . ".bak"
2036< Also note that expanding "<cfile>" and others only returns the
2037 referenced file name without further expansion. If "<cfile>"
2038 is "~/.cshrc", you need to do another expand() to have the
2039 "~/" expanded into the path of the home directory: >
2040 :echo expand(expand("<cfile>"))
2041<
2042 There cannot be white space between the variables and the
2043 following modifier. The |fnamemodify()| function can be used
2044 to modify normal file names.
2045
2046 When using '%' or '#', and the current or alternate file name
2047 is not defined, an empty string is used. Using "%:p" in a
2048 buffer with no name, results in the current directory, with a
2049 '/' added.
2050
2051 When {expr} does not start with '%', '#' or '<', it is
2052 expanded like a file name is expanded on the command line.
2053 'suffixes' and 'wildignore' are used, unless the optional
2054 {flag} argument is given and it is non-zero. Names for
2055 non-existing files are included.
2056
2057 Expand() can also be used to expand variables and environment
2058 variables that are only known in a shell. But this can be
2059 slow, because a shell must be started. See |expr-env-expand|.
2060 The expanded variable is still handled like a list of file
2061 names. When an environment variable cannot be expanded, it is
2062 left unchanged. Thus ":echo expand('$FOOBAR')" results in
2063 "$FOOBAR".
2064
2065 See |glob()| for finding existing files. See |system()| for
2066 getting the raw output of an external command.
2067
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002068extend({expr1}, {expr2} [, {expr3}]) *extend()*
2069 {expr1} and {expr2} must be both Lists or both Dictionaries.
2070
2071 If they are Lists: Append {expr2} to {expr1}.
2072 If {expr3} is given insert the items of {expr2} before item
2073 {expr3} in {expr1}. When {expr3} is zero insert before the
2074 first item. When {expr3} is equal to len({expr1}) then
2075 {expr2} is appended.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002076 Examples: >
2077 :echo sort(extend(mylist, [7, 5]))
2078 :call extend(mylist, [2, 3], 1)
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002079< Use |add()| to concatenate one item to a list. To concatenate
2080 two lists into a new list use the + operator: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002081 :let newlist = [1, 2, 3] + [4, 5]
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002082<
2083 If they are Dictionaries:
2084 Add all entries from {expr2} to {expr1}.
2085 If a key exists in both {expr1} and {expr2} then {expr3} is
2086 used to decide what to do:
2087 {expr3} = "keep": keep the value of {expr1}
2088 {expr3} = "force": use the value of {expr2}
2089 {expr3} = "error": give an error message
2090 When {expr3} is omitted then "force" is assumed.
2091
2092 {expr1} is changed when {expr2} is not empty. If necessary
2093 make a copy of {expr1} first.
2094 {expr2} remains unchanged.
2095 Returns {expr1}.
2096
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002097
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098filereadable({file}) *filereadable()*
2099 The result is a Number, which is TRUE when a file with the
2100 name {file} exists, and can be read. If {file} doesn't exist,
2101 or is a directory, the result is FALSE. {file} is any
2102 expression, which is used as a String.
2103 *file_readable()*
2104 Obsolete name: file_readable().
2105
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002106
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002107filter({expr}, {string}) *filter()*
2108 {expr} must be a List or a Dictionary.
2109 For each item in {expr} evaluate {string} and when the result
2110 is zero remove the item from the List or Dictionary.
2111 Inside {string} |v:val| has the value of the current item.
2112 For a Dictionary |v:key| has the key of the current item.
2113 Examples: >
2114 :call filter(mylist, 'v:val !~ "OLD"')
2115< Removes the items where "OLD" appears. >
2116 :call filter(mydict, 'v:key >= 8')
2117< Removes the items with a key below 8. >
2118 :call filter(var, 0)
Bram Moolenaard8b02732005-01-14 21:48:43 +00002119< Removes all the items, thus clears the List or Dictionary.
2120
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002121 Note that {string} is the result of expression and is then
2122 used as an expression again. Often it is good to use a
2123 |literal-string| to avoid having to double backslashes.
2124
2125 The operation is done in-place. If you want a List or
2126 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002127 :let l = filter(copy(mylist), '& =~ "KEEP"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002128
2129< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002130
2131
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002132finddir({name}[, {path}[, {count}]]) *finddir()*
2133 Find directory {name} in {path}.
2134 If {path} is omitted or empty then 'path' is used.
2135 If the optional {count} is given, find {count}'s occurrence of
2136 {name} in {path}.
2137 This is quite similar to the ex-command |:find|.
2138 When the found directory is below the current directory a
2139 relative path is returned. Otherwise a full path is returned.
2140 Example: >
2141 :echo findfile("tags.vim", ".;")
2142< Searches from the current directory upwards until it finds
2143 the file "tags.vim".
2144 {only available when compiled with the +file_in_path feature}
2145
2146findfile({name}[, {path}[, {count}]]) *findfile()*
2147 Just like |finddir()|, but find a file instead of a directory.
2148
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149filewritable({file}) *filewritable()*
2150 The result is a Number, which is 1 when a file with the
2151 name {file} exists, and can be written. If {file} doesn't
2152 exist, or is not writable, the result is 0. If (file) is a
2153 directory, and we can write to it, the result is 2.
2154
2155fnamemodify({fname}, {mods}) *fnamemodify()*
2156 Modify file name {fname} according to {mods}. {mods} is a
2157 string of characters like it is used for file names on the
2158 command line. See |filename-modifiers|.
2159 Example: >
2160 :echo fnamemodify("main.c", ":p:h")
2161< results in: >
2162 /home/mool/vim/vim/src
2163< Note: Environment variables and "~" don't work in {fname}, use
2164 |expand()| first then.
2165
2166foldclosed({lnum}) *foldclosed()*
2167 The result is a Number. If the line {lnum} is in a closed
2168 fold, the result is the number of the first line in that fold.
2169 If the line {lnum} is not in a closed fold, -1 is returned.
2170
2171foldclosedend({lnum}) *foldclosedend()*
2172 The result is a Number. If the line {lnum} is in a closed
2173 fold, the result is the number of the last line in that fold.
2174 If the line {lnum} is not in a closed fold, -1 is returned.
2175
2176foldlevel({lnum}) *foldlevel()*
2177 The result is a Number, which is the foldlevel of line {lnum}
2178 in the current buffer. For nested folds the deepest level is
2179 returned. If there is no fold at line {lnum}, zero is
2180 returned. It doesn't matter if the folds are open or closed.
2181 When used while updating folds (from 'foldexpr') -1 is
2182 returned for lines where folds are still to be updated and the
2183 foldlevel is unknown. As a special case the level of the
2184 previous line is usually available.
2185
2186 *foldtext()*
2187foldtext() Returns a String, to be displayed for a closed fold. This is
2188 the default function used for the 'foldtext' option and should
2189 only be called from evaluating 'foldtext'. It uses the
2190 |v:foldstart|, |v:foldend| and |v:folddashes| variables.
2191 The returned string looks like this: >
2192 +-- 45 lines: abcdef
2193< The number of dashes depends on the foldlevel. The "45" is
2194 the number of lines in the fold. "abcdef" is the text in the
2195 first non-blank line of the fold. Leading white space, "//"
2196 or "/*" and the text from the 'foldmarker' and 'commentstring'
2197 options is removed.
2198 {not available when compiled without the |+folding| feature}
2199
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002200foldtextresult({lnum}) *foldtextresult()*
2201 Returns the text that is displayed for the closed fold at line
2202 {lnum}. Evaluates 'foldtext' in the appropriate context.
2203 When there is no closed fold at {lnum} an empty string is
2204 returned.
2205 {lnum} is used like with |getline()|. Thus "." is the current
2206 line, "'m" mark m, etc.
2207 Useful when exporting folded text, e.g., to HTML.
2208 {not available when compiled without the |+folding| feature}
2209
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 *foreground()*
2211foreground() Move the Vim window to the foreground. Useful when sent from
2212 a client to a Vim server. |remote_send()|
2213 On Win32 systems this might not work, the OS does not always
2214 allow a window to bring itself to the foreground. Use
2215 |remote_foreground()| instead.
2216 {only in the Win32, Athena, Motif and GTK GUI versions and the
2217 Win32 console version}
2218
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002219
Bram Moolenaar13065c42005-01-08 16:08:21 +00002220function({name}) *function()* *E700*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002221 Return a Funcref variable that refers to function {name}.
2222 {name} can be a user defined function or an internal function.
2223
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002224
2225get({list}, {idx} [, {default}]) *get*
2226 Get item {idx} from List {list}. When this item is not
2227 available return {default}. Return zero when {default} is
2228 omitted.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002229get({dict}, {key} [, {default}])
2230 Get item with key {key} from Dictionary {dict}. When this
2231 item is not available return {default}. Return zero when
2232 {default} is omitted.
2233
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002234
2235getbufvar({expr}, {varname}) *getbufvar()*
2236 The result is the value of option or local buffer variable
2237 {varname} in buffer {expr}. Note that the name without "b:"
2238 must be used.
2239 This also works for a global or local window option, but it
2240 doesn't work for a global or local window variable.
2241 For the use of {expr}, see |bufname()| above.
2242 When the buffer or variable doesn't exist an empty string is
2243 returned, there is no error message.
2244 Examples: >
2245 :let bufmodified = getbufvar(1, "&mod")
2246 :echo "todo myvar = " . getbufvar("todo", "myvar")
2247<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248getchar([expr]) *getchar()*
2249 Get a single character from the user. If it is an 8-bit
2250 character, the result is a number. Otherwise a String is
2251 returned with the encoded character. For a special key it's a
2252 sequence of bytes starting with 0x80 (decimal: 128).
2253 If [expr] is omitted, wait until a character is available.
2254 If [expr] is 0, only get a character when one is available.
2255 If [expr] is 1, only check if a character is available, it is
2256 not consumed. If a normal character is
2257 available, it is returned, otherwise a
2258 non-zero value is returned.
2259 If a normal character available, it is returned as a Number.
2260 Use nr2char() to convert it to a String.
2261 The returned value is zero if no character is available.
2262 The returned value is a string of characters for special keys
2263 and when a modifier (shift, control, alt) was used.
2264 There is no prompt, you will somehow have to make clear to the
2265 user that a character has to be typed.
2266 There is no mapping for the character.
2267 Key codes are replaced, thus when the user presses the <Del>
2268 key you get the code for the <Del> key, not the raw character
2269 sequence. Examples: >
2270 getchar() == "\<Del>"
2271 getchar() == "\<S-Left>"
2272< This example redefines "f" to ignore case: >
2273 :nmap f :call FindChar()<CR>
2274 :function FindChar()
2275 : let c = nr2char(getchar())
2276 : while col('.') < col('$') - 1
2277 : normal l
2278 : if getline('.')[col('.') - 1] ==? c
2279 : break
2280 : endif
2281 : endwhile
2282 :endfunction
2283
2284getcharmod() *getcharmod()*
2285 The result is a Number which is the state of the modifiers for
2286 the last obtained character with getchar() or in another way.
2287 These values are added together:
2288 2 shift
2289 4 control
2290 8 alt (meta)
2291 16 mouse double click
2292 32 mouse triple click
2293 64 mouse quadruple click
2294 128 Macintosh only: command
2295 Only the modifiers that have not been included in the
2296 character itself are obtained. Thus Shift-a results in "A"
2297 with no modifier.
2298
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299getcmdline() *getcmdline()*
2300 Return the current command-line. Only works when the command
2301 line is being edited, thus requires use of |c_CTRL-\_e| or
2302 |c_CTRL-R_=|.
2303 Example: >
2304 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
2305< Also see |getcmdpos()| and |setcmdpos()|.
2306
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002307getcmdpos() *getcmdpos()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 Return the position of the cursor in the command line as a
2309 byte count. The first column is 1.
2310 Only works when editing the command line, thus requires use of
2311 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
2312 Also see |setcmdpos()| and |getcmdline()|.
2313
2314 *getcwd()*
2315getcwd() The result is a String, which is the name of the current
2316 working directory.
2317
2318getfsize({fname}) *getfsize()*
2319 The result is a Number, which is the size in bytes of the
2320 given file {fname}.
2321 If {fname} is a directory, 0 is returned.
2322 If the file {fname} can't be found, -1 is returned.
2323
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002324getfontname([{name}]) *getfontname()*
2325 Without an argument returns the name of the normal font being
2326 used. Like what is used for the Normal highlight group
2327 |hl-Normal|.
2328 With an argument a check is done whether {name} is a valid
2329 font name. If not then an empty string is returned.
2330 Otherwise the actual font name is returned, or {name} if the
2331 GUI does not support obtaining the real name.
2332 Only works when the GUI is running, thus not you your vimrc or
2333 Note that the GTK 2 GUI accepts any font name, thus checking
2334 for a valid name does not work.
2335 gvimrc file. Use the |GUIEnter| autocommand to use this
2336 function just after the GUI has started.
2337
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002338getfperm({fname}) *getfperm()*
2339 The result is a String, which is the read, write, and execute
2340 permissions of the given file {fname}.
2341 If {fname} does not exist or its directory cannot be read, an
2342 empty string is returned.
2343 The result is of the form "rwxrwxrwx", where each group of
2344 "rwx" flags represent, in turn, the permissions of the owner
2345 of the file, the group the file belongs to, and other users.
2346 If a user does not have a given permission the flag for this
2347 is replaced with the string "-". Example: >
2348 :echo getfperm("/etc/passwd")
2349< This will hopefully (from a security point of view) display
2350 the string "rw-r--r--" or even "rw-------".
2351
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352getftime({fname}) *getftime()*
2353 The result is a Number, which is the last modification time of
2354 the given file {fname}. The value is measured as seconds
2355 since 1st Jan 1970, and may be passed to strftime(). See also
2356 |localtime()| and |strftime()|.
2357 If the file {fname} can't be found -1 is returned.
2358
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002359getftype({fname}) *getftype()*
2360 The result is a String, which is a description of the kind of
2361 file of the given file {fname}.
2362 If {fname} does not exist an empty string is returned.
2363 Here is a table over different kinds of files and their
2364 results:
2365 Normal file "file"
2366 Directory "dir"
2367 Symbolic link "link"
2368 Block device "bdev"
2369 Character device "cdev"
2370 Socket "socket"
2371 FIFO "fifo"
2372 All other "other"
2373 Example: >
2374 getftype("/home")
2375< Note that a type such as "link" will only be returned on
2376 systems that support it. On some systems only "dir" and
2377 "file" are returned.
2378
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 *getline()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002380getline({lnum} [, {end}])
2381 Without {end} the result is a String, which is line {lnum}
2382 from the current buffer. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 getline(1)
2384< When {lnum} is a String that doesn't start with a
2385 digit, line() is called to translate the String into a Number.
2386 To get the line under the cursor: >
2387 getline(".")
2388< When {lnum} is smaller than 1 or bigger than the number of
2389 lines in the buffer, an empty string is returned.
2390
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002391 When {end} is given the result is a List where each item is a
2392 line from the current buffer in the range {lnum} to {end},
2393 including line {end}.
2394 {end} is used in the same way as {lnum}.
2395 Non-existing lines are silently omitted.
2396 When {end} is before {lnum} an error is given.
2397 Example: >
2398 :let start = line('.')
2399 :let end = search("^$") - 1
2400 :let lines = getline(start, end)
2401
2402
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403getreg([{regname}]) *getreg()*
2404 The result is a String, which is the contents of register
2405 {regname}. Example: >
2406 :let cliptext = getreg('*')
2407< getreg('=') returns the last evaluated value of the expression
2408 register. (For use in maps).
2409 If {regname} is not specified, |v:register| is used.
2410
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002411
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412getregtype([{regname}]) *getregtype()*
2413 The result is a String, which is type of register {regname}.
2414 The value will be one of:
2415 "v" for |characterwise| text
2416 "V" for |linewise| text
2417 "<CTRL-V>{width}" for |blockwise-visual| text
2418 0 for an empty or unknown register
2419 <CTRL-V> is one character with value 0x16.
2420 If {regname} is not specified, |v:register| is used.
2421
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002422
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 *getwinposx()*
2424getwinposx() The result is a Number, which is the X coordinate in pixels of
2425 the left hand side of the GUI Vim window. The result will be
2426 -1 if the information is not available.
2427
2428 *getwinposy()*
2429getwinposy() The result is a Number, which is the Y coordinate in pixels of
2430 the top of the GUI Vim window. The result will be -1 if the
2431 information is not available.
2432
2433getwinvar({nr}, {varname}) *getwinvar()*
2434 The result is the value of option or local window variable
2435 {varname} in window {nr}.
2436 This also works for a global or local buffer option, but it
2437 doesn't work for a global or local buffer variable.
2438 Note that the name without "w:" must be used.
2439 Examples: >
2440 :let list_is_on = getwinvar(2, '&list')
2441 :echo "myvar = " . getwinvar(1, 'myvar')
2442<
2443 *glob()*
2444glob({expr}) Expand the file wildcards in {expr}. The result is a String.
2445 When there are several matches, they are separated by <NL>
2446 characters.
2447 If the expansion fails, the result is an empty string.
2448 A name for a non-existing file is not included.
2449
2450 For most systems backticks can be used to get files names from
2451 any external command. Example: >
2452 :let tagfiles = glob("`find . -name tags -print`")
2453 :let &tags = substitute(tagfiles, "\n", ",", "g")
2454< The result of the program inside the backticks should be one
2455 item per line. Spaces inside an item are allowed.
2456
2457 See |expand()| for expanding special Vim variables. See
2458 |system()| for getting the raw output of an external command.
2459
2460globpath({path}, {expr}) *globpath()*
2461 Perform glob() on all directories in {path} and concatenate
2462 the results. Example: >
2463 :echo globpath(&rtp, "syntax/c.vim")
2464< {path} is a comma-separated list of directory names. Each
2465 directory name is prepended to {expr} and expanded like with
2466 glob(). A path separator is inserted when needed.
2467 To add a comma inside a directory name escape it with a
2468 backslash. Note that on MS-Windows a directory may have a
2469 trailing backslash, remove it if you put a comma after it.
2470 If the expansion fails for one of the directories, there is no
2471 error message.
2472 The 'wildignore' option applies: Names matching one of the
2473 patterns in 'wildignore' will be skipped.
2474
2475 *has()*
2476has({feature}) The result is a Number, which is 1 if the feature {feature} is
2477 supported, zero otherwise. The {feature} argument is a
2478 string. See |feature-list| below.
2479 Also see |exists()|.
2480
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002481
2482has_key({dict}, {key}) *has_key()*
2483 The result is a Number, which is 1 if Dictionary {dict} has an
2484 entry with key {key}. Zero otherwise.
2485
2486
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487hasmapto({what} [, {mode}]) *hasmapto()*
2488 The result is a Number, which is 1 if there is a mapping that
2489 contains {what} in somewhere in the rhs (what it is mapped to)
2490 and this mapping exists in one of the modes indicated by
2491 {mode}.
2492 Both the global mappings and the mappings local to the current
2493 buffer are checked for a match.
2494 If no matching mapping is found 0 is returned.
2495 The following characters are recognized in {mode}:
2496 n Normal mode
2497 v Visual mode
2498 o Operator-pending mode
2499 i Insert mode
2500 l Language-Argument ("r", "f", "t", etc.)
2501 c Command-line mode
2502 When {mode} is omitted, "nvo" is used.
2503
2504 This function is useful to check if a mapping already exists
2505 to a function in a Vim script. Example: >
2506 :if !hasmapto('\ABCdoit')
2507 : map <Leader>d \ABCdoit
2508 :endif
2509< This installs the mapping to "\ABCdoit" only if there isn't
2510 already a mapping to "\ABCdoit".
2511
2512histadd({history}, {item}) *histadd()*
2513 Add the String {item} to the history {history} which can be
2514 one of: *hist-names*
2515 "cmd" or ":" command line history
2516 "search" or "/" search pattern history
2517 "expr" or "=" typed expression history
2518 "input" or "@" input line history
2519 If {item} does already exist in the history, it will be
2520 shifted to become the newest entry.
2521 The result is a Number: 1 if the operation was successful,
2522 otherwise 0 is returned.
2523
2524 Example: >
2525 :call histadd("input", strftime("%Y %b %d"))
2526 :let date=input("Enter date: ")
2527< This function is not available in the |sandbox|.
2528
2529histdel({history} [, {item}]) *histdel()*
2530 Clear {history}, ie. delete all its entries. See |hist-names|
2531 for the possible values of {history}.
2532
2533 If the parameter {item} is given as String, this is seen
2534 as regular expression. All entries matching that expression
2535 will be removed from the history (if there are any).
2536 Upper/lowercase must match, unless "\c" is used |/\c|.
2537 If {item} is a Number, it will be interpreted as index, see
2538 |:history-indexing|. The respective entry will be removed
2539 if it exists.
2540
2541 The result is a Number: 1 for a successful operation,
2542 otherwise 0 is returned.
2543
2544 Examples:
2545 Clear expression register history: >
2546 :call histdel("expr")
2547<
2548 Remove all entries starting with "*" from the search history: >
2549 :call histdel("/", '^\*')
2550<
2551 The following three are equivalent: >
2552 :call histdel("search", histnr("search"))
2553 :call histdel("search", -1)
2554 :call histdel("search", '^'.histget("search", -1).'$')
2555<
2556 To delete the last search pattern and use the last-but-one for
2557 the "n" command and 'hlsearch': >
2558 :call histdel("search", -1)
2559 :let @/ = histget("search", -1)
2560
2561histget({history} [, {index}]) *histget()*
2562 The result is a String, the entry with Number {index} from
2563 {history}. See |hist-names| for the possible values of
2564 {history}, and |:history-indexing| for {index}. If there is
2565 no such entry, an empty String is returned. When {index} is
2566 omitted, the most recent item from the history is used.
2567
2568 Examples:
2569 Redo the second last search from history. >
2570 :execute '/' . histget("search", -2)
2571
2572< Define an Ex command ":H {num}" that supports re-execution of
2573 the {num}th entry from the output of |:history|. >
2574 :command -nargs=1 H execute histget("cmd", 0+<args>)
2575<
2576histnr({history}) *histnr()*
2577 The result is the Number of the current entry in {history}.
2578 See |hist-names| for the possible values of {history}.
2579 If an error occurred, -1 is returned.
2580
2581 Example: >
2582 :let inp_index = histnr("expr")
2583<
2584hlexists({name}) *hlexists()*
2585 The result is a Number, which is non-zero if a highlight group
2586 called {name} exists. This is when the group has been
2587 defined in some way. Not necessarily when highlighting has
2588 been defined for it, it may also have been used for a syntax
2589 item.
2590 *highlight_exists()*
2591 Obsolete name: highlight_exists().
2592
2593 *hlID()*
2594hlID({name}) The result is a Number, which is the ID of the highlight group
2595 with name {name}. When the highlight group doesn't exist,
2596 zero is returned.
2597 This can be used to retrieve information about the highlight
2598 group. For example, to get the background color of the
2599 "Comment" group: >
2600 :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
2601< *highlightID()*
2602 Obsolete name: highlightID().
2603
2604hostname() *hostname()*
2605 The result is a String, which is the name of the machine on
2606 which Vim is currently running. Machine names greater than
2607 256 characters long are truncated.
2608
2609iconv({expr}, {from}, {to}) *iconv()*
2610 The result is a String, which is the text {expr} converted
2611 from encoding {from} to encoding {to}.
2612 When the conversion fails an empty string is returned.
2613 The encoding names are whatever the iconv() library function
2614 can accept, see ":!man 3 iconv".
2615 Most conversions require Vim to be compiled with the |+iconv|
2616 feature. Otherwise only UTF-8 to latin1 conversion and back
2617 can be done.
2618 This can be used to display messages with special characters,
2619 no matter what 'encoding' is set to. Write the message in
2620 UTF-8 and use: >
2621 echo iconv(utf8_str, "utf-8", &enc)
2622< Note that Vim uses UTF-8 for all Unicode encodings, conversion
2623 from/to UCS-2 is automatically changed to use UTF-8. You
2624 cannot use UCS-2 in a string anyway, because of the NUL bytes.
2625 {only available when compiled with the +multi_byte feature}
2626
2627 *indent()*
2628indent({lnum}) The result is a Number, which is indent of line {lnum} in the
2629 current buffer. The indent is counted in spaces, the value
2630 of 'tabstop' is relevant. {lnum} is used just like in
2631 |getline()|.
2632 When {lnum} is invalid -1 is returned.
2633
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002634
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002635index({list}, {expr} [, {start} [, {ic}]]) *index()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002636 Return the lowest index in List {list} where the item has a
2637 value equal to {expr}.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002638 If {start} is given then skip items with a lower index.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002639 When {ic} is given and it is non-zero, ignore case. Otherwise
2640 case must match.
2641 -1 is returned when {expr} is not found in {list}.
2642 Example: >
2643 :let idx = index(words, "the")
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002644 :if index(numbers, 123) >= 0
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002645
2646
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647input({prompt} [, {text}]) *input()*
2648 The result is a String, which is whatever the user typed on
2649 the command-line. The parameter is either a prompt string, or
2650 a blank string (for no prompt). A '\n' can be used in the
2651 prompt to start a new line. The highlighting set with
2652 |:echohl| is used for the prompt. The input is entered just
2653 like a command-line, with the same editing commands and
2654 mappings. There is a separate history for lines typed for
2655 input().
2656 If the optional {text} is present, this is used for the
2657 default reply, as if the user typed this.
2658 NOTE: This must not be used in a startup file, for the
2659 versions that only run in GUI mode (e.g., the Win32 GUI).
2660 Note: When input() is called from within a mapping it will
2661 consume remaining characters from that mapping, because a
2662 mapping is handled like the characters were typed.
2663 Use |inputsave()| before input() and |inputrestore()|
2664 after input() to avoid that. Another solution is to avoid
2665 that further characters follow in the mapping, e.g., by using
2666 |:execute| or |:normal|.
2667
2668 Example: >
2669 :if input("Coffee or beer? ") == "beer"
2670 : echo "Cheers!"
2671 :endif
2672< Example with default text: >
2673 :let color = input("Color? ", "white")
2674< Example with a mapping: >
2675 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
2676 :function GetFoo()
2677 : call inputsave()
2678 : let g:Foo = input("enter search pattern: ")
2679 : call inputrestore()
2680 :endfunction
2681
2682inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
2683 Like input(), but when the GUI is running and text dialogs are
2684 supported, a dialog window pops up to input the text.
2685 Example: >
2686 :let n = inputdialog("value for shiftwidth", &sw)
2687 :if n != ""
2688 : let &sw = n
2689 :endif
2690< When the dialog is cancelled {cancelreturn} is returned. When
2691 omitted an empty string is returned.
2692 Hitting <Enter> works like pressing the OK button. Hitting
2693 <Esc> works like pressing the Cancel button.
2694
2695inputrestore() *inputrestore()*
2696 Restore typeahead that was saved with a previous inputsave().
2697 Should be called the same number of times inputsave() is
2698 called. Calling it more often is harmless though.
2699 Returns 1 when there is nothing to restore, 0 otherwise.
2700
2701inputsave() *inputsave()*
2702 Preserve typeahead (also from mappings) and clear it, so that
2703 a following prompt gets input from the user. Should be
2704 followed by a matching inputrestore() after the prompt. Can
2705 be used several times, in which case there must be just as
2706 many inputrestore() calls.
2707 Returns 1 when out of memory, 0 otherwise.
2708
2709inputsecret({prompt} [, {text}]) *inputsecret()*
2710 This function acts much like the |input()| function with but
2711 two exceptions:
2712 a) the user's response will be displayed as a sequence of
2713 asterisks ("*") thereby keeping the entry secret, and
2714 b) the user's response will not be recorded on the input
2715 |history| stack.
2716 The result is a String, which is whatever the user actually
2717 typed on the command-line in response to the issued prompt.
2718
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002719insert({list}, {item} [, {idx}]) *insert()*
2720 Insert {item} at the start of List {list}.
2721 If {idx} is specified insert {item} before the item with index
2722 {idx}. If {idx} is zero it goes before the first item, just
2723 like omitting {idx}. A negative {idx} is also possible, see
2724 |list-index|. -1 inserts just before the last item.
2725 Returns the resulting List. Examples: >
2726 :let mylist = insert([2, 3, 5], 1)
2727 :call insert(mylist, 4, -1)
2728 :call insert(mylist, 6, len(mylist))
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002729< The last example can be done simpler with |add()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002730 Note that when {item} is a List it is inserted as a single
2731 item. Use |extend()| to concatenate Lists.
2732
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733isdirectory({directory}) *isdirectory()*
2734 The result is a Number, which is non-zero when a directory
2735 with the name {directory} exists. If {directory} doesn't
2736 exist, or isn't a directory, the result is FALSE. {directory}
2737 is any expression, which is used as a String.
2738
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002739
2740join({list} [, {sep}]) *join()*
2741 Join the items in {list} together into one String.
2742 When {sep} is specified it is put in between the items. If
2743 {sep} is omitted a single space is used.
2744 Note that {sep} is not added at the end. You might want to
2745 add it there too: >
2746 let lines = join(mylist, "\n") . "\n"
2747< String items are used as-is. Lists and Dictionaries are
2748 converted into a string like with |string()|.
2749 The opposite function is |split()|.
2750
Bram Moolenaard8b02732005-01-14 21:48:43 +00002751keys({dict}) *keys()*
2752 Return a List with all the keys of {dict}. The List is in
2753 arbitrary order.
2754
Bram Moolenaar13065c42005-01-08 16:08:21 +00002755 *len()* *E701*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002756len({expr}) The result is a Number, which is the length of the argument.
2757 When {expr} is a String or a Number the length in bytes is
2758 used, as with |strlen()|.
2759 When {expr} is a List the number of items in the List is
2760 returned.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002761 When {expr} is a Dictionary the number of entries in the
2762 Dictionary is returned.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002763 Otherwise an error is given.
2764
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 *libcall()* *E364* *E368*
2766libcall({libname}, {funcname}, {argument})
2767 Call function {funcname} in the run-time library {libname}
2768 with single argument {argument}.
2769 This is useful to call functions in a library that you
2770 especially made to be used with Vim. Since only one argument
2771 is possible, calling standard library functions is rather
2772 limited.
2773 The result is the String returned by the function. If the
2774 function returns NULL, this will appear as an empty string ""
2775 to Vim.
2776 If the function returns a number, use libcallnr()!
2777 If {argument} is a number, it is passed to the function as an
2778 int; if {argument} is a string, it is passed as a
2779 null-terminated string.
2780 This function will fail in |restricted-mode|.
2781
2782 libcall() allows you to write your own 'plug-in' extensions to
2783 Vim without having to recompile the program. It is NOT a
2784 means to call system functions! If you try to do so Vim will
2785 very probably crash.
2786
2787 For Win32, the functions you write must be placed in a DLL
2788 and use the normal C calling convention (NOT Pascal which is
2789 used in Windows System DLLs). The function must take exactly
2790 one parameter, either a character pointer or a long integer,
2791 and must return a character pointer or NULL. The character
2792 pointer returned must point to memory that will remain valid
2793 after the function has returned (e.g. in static data in the
2794 DLL). If it points to allocated memory, that memory will
2795 leak away. Using a static buffer in the function should work,
2796 it's then freed when the DLL is unloaded.
2797
2798 WARNING: If the function returns a non-valid pointer, Vim may
2799 crash! This also happens if the function returns a number,
2800 because Vim thinks it's a pointer.
2801 For Win32 systems, {libname} should be the filename of the DLL
2802 without the ".DLL" suffix. A full path is only required if
2803 the DLL is not in the usual places.
2804 For Unix: When compiling your own plugins, remember that the
2805 object code must be compiled as position-independent ('PIC').
2806 {only in Win32 on some Unix versions, when the |+libcall|
2807 feature is present}
2808 Examples: >
2809 :echo libcall("libc.so", "getenv", "HOME")
2810 :echo libcallnr("/usr/lib/libc.so", "getpid", "")
2811<
2812 *libcallnr()*
2813libcallnr({libname}, {funcname}, {argument})
2814 Just like libcall(), but used for a function that returns an
2815 int instead of a string.
2816 {only in Win32 on some Unix versions, when the |+libcall|
2817 feature is present}
2818 Example (not very useful...): >
2819 :call libcallnr("libc.so", "printf", "Hello World!\n")
2820 :call libcallnr("libc.so", "sleep", 10)
2821<
2822 *line()*
2823line({expr}) The result is a Number, which is the line number of the file
2824 position given with {expr}. The accepted positions are:
2825 . the cursor position
2826 $ the last line in the current buffer
2827 'x position of mark x (if the mark is not set, 0 is
2828 returned)
2829 Note that only marks in the current file can be used.
2830 Examples: >
2831 line(".") line number of the cursor
2832 line("'t") line number of mark t
2833 line("'" . marker) line number of mark marker
2834< *last-position-jump*
2835 This autocommand jumps to the last known position in a file
2836 just after opening it, if the '" mark is set: >
2837 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002838
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839line2byte({lnum}) *line2byte()*
2840 Return the byte count from the start of the buffer for line
2841 {lnum}. This includes the end-of-line character, depending on
2842 the 'fileformat' option for the current buffer. The first
2843 line returns 1.
2844 This can also be used to get the byte count for the line just
2845 below the last line: >
2846 line2byte(line("$") + 1)
2847< This is the file size plus one.
2848 When {lnum} is invalid, or the |+byte_offset| feature has been
2849 disabled at compile time, -1 is returned.
2850 Also see |byte2line()|, |go| and |:goto|.
2851
2852lispindent({lnum}) *lispindent()*
2853 Get the amount of indent for line {lnum} according the lisp
2854 indenting rules, as with 'lisp'.
2855 The indent is counted in spaces, the value of 'tabstop' is
2856 relevant. {lnum} is used just like in |getline()|.
2857 When {lnum} is invalid or Vim was not compiled the
2858 |+lispindent| feature, -1 is returned.
2859
2860localtime() *localtime()*
2861 Return the current time, measured as seconds since 1st Jan
2862 1970. See also |strftime()| and |getftime()|.
2863
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002864
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002865map({expr}, {string}) *map()*
2866 {expr} must be a List or a Dictionary.
2867 Replace each item in {expr} with the result of evaluating
2868 {string}.
2869 Inside {string} |v:val| has the value of the current item.
2870 For a Dictionary |v:key| has the key of the current item.
2871 Example: >
2872 :call map(mylist, '"> " . v:val . " <"')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002873< This puts "> " before and " <" after each item in "mylist".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002874
2875 Note that {string} is the result of expression and is then
2876 used as an expression again. Often it is good to use a
2877 |literal-string| to avoid having to double backslashes.
2878
2879 The operation is done in-place. If you want a List or
2880 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002881 :let tlist = map(copy(mylist), ' & . "\t"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002882
2883< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002884
2885
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886maparg({name}[, {mode}]) *maparg()*
2887 Return the rhs of mapping {name} in mode {mode}. When there
2888 is no mapping for {name}, an empty String is returned.
2889 These characters can be used for {mode}:
2890 "n" Normal
2891 "v" Visual
2892 "o" Operator-pending
2893 "i" Insert
2894 "c" Cmd-line
2895 "l" langmap |language-mapping|
2896 "" Normal, Visual and Operator-pending
2897 When {mode} is omitted, the modes from "" are used.
2898 The {name} can have special key names, like in the ":map"
2899 command. The returned String has special characters
2900 translated like in the output of the ":map" command listing.
2901 The mappings local to the current buffer are checked first,
2902 then the global mappings.
2903
2904mapcheck({name}[, {mode}]) *mapcheck()*
2905 Check if there is a mapping that matches with {name} in mode
2906 {mode}. See |maparg()| for {mode} and special names in
2907 {name}.
2908 A match happens with a mapping that starts with {name} and
2909 with a mapping which is equal to the start of {name}.
2910
2911 matches mapping "a" "ab" "abc" ~
2912 mapcheck("a") yes yes yes
2913 mapcheck("abc") yes yes yes
2914 mapcheck("ax") yes no no
2915 mapcheck("b") no no no
2916
2917 The difference with maparg() is that mapcheck() finds a
2918 mapping that matches with {name}, while maparg() only finds a
2919 mapping for {name} exactly.
2920 When there is no mapping that starts with {name}, an empty
2921 String is returned. If there is one, the rhs of that mapping
2922 is returned. If there are several mappings that start with
2923 {name}, the rhs of one of them is returned.
2924 The mappings local to the current buffer are checked first,
2925 then the global mappings.
2926 This function can be used to check if a mapping can be added
2927 without being ambiguous. Example: >
2928 :if mapcheck("_vv") == ""
2929 : map _vv :set guifont=7x13<CR>
2930 :endif
2931< This avoids adding the "_vv" mapping when there already is a
2932 mapping for "_v" or for "_vvv".
2933
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002934match({expr}, {pat}[, {start}[, {count}]]) *match()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002935 When {expr} is a List then this returns the index of the first
2936 item where {pat} matches. Each item is used as a String,
2937 Lists and Dictionaries are used as echoed.
2938 Otherwise, {expr} is used as a String. The result is a
2939 Number, which gives the index (byte offset) in {expr} where
2940 {pat} matches.
2941 A match at the first character or List item returns zero.
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002942 If there is no match -1 is returned.
2943 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002944 :echo match("testing", "ing") " results in 4
2945 :echo match([1, 'x'], '\a') " results in 2
2946< See |string-match| for how {pat} is used.
2947
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002948 When {count} is given use the {count}'th match. When a match
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002949 is found in a String the search for the next one starts on
2950 character further. Thus this example results in 1: >
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002951 echo match("testing", "..", 0, 2)
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002952< In a List the search continues in the next item.
2953
2954 If {start} is given, the search starts from byte index
2955 {start} in a String or item {start} in a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 The result, however, is still the index counted from the
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002957 first character/item. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958 :echo match("testing", "ing", 2)
2959< result is again "4". >
2960 :echo match("testing", "ing", 4)
2961< result is again "4". >
2962 :echo match("testing", "t", 2)
2963< result is "3".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002964 For a String, if {start} < 0, it will be set to 0. For a list
2965 the index is counted from the end.
2966 If {start} is out of range (> strlen({expr} for a String or
2967 > len({expr} for a List) -1 is returned.
2968
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 See |pattern| for the patterns that are accepted.
2970 The 'ignorecase' option is used to set the ignore-caseness of
2971 the pattern. 'smartcase' is NOT used. The matching is always
2972 done like 'magic' is set and 'cpoptions' is empty.
2973
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002974matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 Same as match(), but return the index of first character after
2976 the match. Example: >
2977 :echo matchend("testing", "ing")
2978< results in "7".
2979 The {start}, if given, has the same meaning as for match(). >
2980 :echo matchend("testing", "ing", 2)
2981< results in "7". >
2982 :echo matchend("testing", "ing", 5)
2983< result is "-1".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002984 When {expr} is a List the result is equal to match().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002986matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 Same as match(), but return the matched string. Example: >
2988 :echo matchstr("testing", "ing")
2989< results in "ing".
2990 When there is no match "" is returned.
2991 The {start}, if given, has the same meaning as for match(). >
2992 :echo matchstr("testing", "ing", 2)
2993< results in "ing". >
2994 :echo matchstr("testing", "ing", 5)
2995< result is "".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002996 When {expr} is a List then the matching item is returned.
2997 The type isn't changed, it's not necessarily a String.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002999 *max()*
3000max({list}) Return the maximum value of all items in {list}.
3001 If {list} is not a list or one of the items in {list} cannot
3002 be used as a Number this results in an error.
3003 An empty List results in zero.
3004
3005 *min()*
3006min({list}) Return the minumum value of all items in {list}.
3007 If {list} is not a list or one of the items in {list} cannot
3008 be used as a Number this results in an error.
3009 An empty List results in zero.
3010
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 *mode()*
3012mode() Return a string that indicates the current mode:
3013 n Normal
3014 v Visual by character
3015 V Visual by line
3016 CTRL-V Visual blockwise
3017 s Select by character
3018 S Select by line
3019 CTRL-S Select blockwise
3020 i Insert
3021 R Replace
3022 c Command-line
3023 r Hit-enter prompt
3024 This is useful in the 'statusline' option. In most other
3025 places it always returns "c" or "n".
3026
3027nextnonblank({lnum}) *nextnonblank()*
3028 Return the line number of the first line at or below {lnum}
3029 that is not blank. Example: >
3030 if getline(nextnonblank(1)) =~ "Java"
3031< When {lnum} is invalid or there is no non-blank line at or
3032 below it, zero is returned.
3033 See also |prevnonblank()|.
3034
3035nr2char({expr}) *nr2char()*
3036 Return a string with a single character, which has the number
3037 value {expr}. Examples: >
3038 nr2char(64) returns "@"
3039 nr2char(32) returns " "
3040< The current 'encoding' is used. Example for "utf-8": >
3041 nr2char(300) returns I with bow character
3042< Note that a NUL character in the file is specified with
3043 nr2char(10), because NULs are represented with newline
3044 characters. nr2char(0) is a real NUL and terminates the
3045 string, thus isn't very useful.
3046
3047prevnonblank({lnum}) *prevnonblank()*
3048 Return the line number of the first line at or above {lnum}
3049 that is not blank. Example: >
3050 let ind = indent(prevnonblank(v:lnum - 1))
3051< When {lnum} is invalid or there is no non-blank line at or
3052 above it, zero is returned.
3053 Also see |nextnonblank()|.
3054
Bram Moolenaard8b02732005-01-14 21:48:43 +00003055range({expr} [, {max} [, {stride}]]) *range()*
3056 Returns a List with Numbers:
3057 - If only {expr} is specified: [0, 1, ..., {expr} - 1]
3058 - If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
3059 - If {stride} is specified: [{expr}, {expr} + {stride}, ...,
3060 {max}] (increasing {expr} with {stride} each time, not
3061 producing a value past {max}).
3062 Examples: >
3063 range(4) " [0, 1, 2, 3]
3064 range(2, 4) " [2, 3, 4]
3065 range(2, 9, 3) " [2, 5, 8]
3066 range(2, -2, -1) " [2, 1, 0, -1, -2]
3067<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 *remote_expr()* *E449*
3069remote_expr({server}, {string} [, {idvar}])
3070 Send the {string} to {server}. The string is sent as an
3071 expression and the result is returned after evaluation.
3072 If {idvar} is present, it is taken as the name of a
3073 variable and a {serverid} for later use with
3074 remote_read() is stored there.
3075 See also |clientserver| |RemoteReply|.
3076 This function is not available in the |sandbox|.
3077 {only available when compiled with the |+clientserver| feature}
3078 Note: Any errors will cause a local error message to be issued
3079 and the result will be the empty string.
3080 Examples: >
3081 :echo remote_expr("gvim", "2+2")
3082 :echo remote_expr("gvim1", "b:current_syntax")
3083<
3084
3085remote_foreground({server}) *remote_foreground()*
3086 Move the Vim server with the name {server} to the foreground.
3087 This works like: >
3088 remote_expr({server}, "foreground()")
3089< Except that on Win32 systems the client does the work, to work
3090 around the problem that the OS doesn't always allow the server
3091 to bring itself to the foreground.
3092 This function is not available in the |sandbox|.
3093 {only in the Win32, Athena, Motif and GTK GUI versions and the
3094 Win32 console version}
3095
3096
3097remote_peek({serverid} [, {retvar}]) *remote_peek()*
3098 Returns a positive number if there are available strings
3099 from {serverid}. Copies any reply string into the variable
3100 {retvar} if specified. {retvar} must be a string with the
3101 name of a variable.
3102 Returns zero if none are available.
3103 Returns -1 if something is wrong.
3104 See also |clientserver|.
3105 This function is not available in the |sandbox|.
3106 {only available when compiled with the |+clientserver| feature}
3107 Examples: >
3108 :let repl = ""
3109 :echo "PEEK: ".remote_peek(id, "repl").": ".repl
3110
3111remote_read({serverid}) *remote_read()*
3112 Return the oldest available reply from {serverid} and consume
3113 it. It blocks until a reply is available.
3114 See also |clientserver|.
3115 This function is not available in the |sandbox|.
3116 {only available when compiled with the |+clientserver| feature}
3117 Example: >
3118 :echo remote_read(id)
3119<
3120 *remote_send()* *E241*
3121remote_send({server}, {string} [, {idvar}])
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003122 Send the {string} to {server}. The string is sent as input
3123 keys and the function returns immediately. At the Vim server
3124 the keys are not mapped |:map|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 If {idvar} is present, it is taken as the name of a
3126 variable and a {serverid} for later use with
3127 remote_read() is stored there.
3128 See also |clientserver| |RemoteReply|.
3129 This function is not available in the |sandbox|.
3130 {only available when compiled with the |+clientserver| feature}
3131 Note: Any errors will be reported in the server and may mess
3132 up the display.
3133 Examples: >
3134 :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
3135 \ remote_read(serverid)
3136
3137 :autocmd NONE RemoteReply *
3138 \ echo remote_read(expand("<amatch>"))
3139 :echo remote_send("gvim", ":sleep 10 | echo ".
3140 \ 'server2client(expand("<client>"), "HELLO")<CR>')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003141<
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003142remove({list}, {idx} [, {end}]) *remove()*
3143 Without {end}: Remove the item at {idx} from List {list} and
3144 return it.
3145 With {end}: Remove items from {idx} to {end} (inclusive) and
3146 return a list with these items. When {idx} points to the same
3147 item as {end} a list with one item is returned. When {end}
3148 points to an item before {idx} this is an error.
3149 See |list-index| for possible values of {idx} and {end}.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003150 Example: >
3151 :echo "last item: " . remove(mylist, -1)
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003152 :call remove(mylist, 0, 9)
Bram Moolenaard8b02732005-01-14 21:48:43 +00003153remove({dict}, {key})
3154 Remove the entry from {dict} with key {key}. Example: >
3155 :echo "removed " . remove(dict, "one")
3156< If there is no {key} in {dict} this is an error.
3157
3158 Use |delete()| to remove a file.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003159
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160rename({from}, {to}) *rename()*
3161 Rename the file by the name {from} to the name {to}. This
3162 should also work to move files across file systems. The
3163 result is a Number, which is 0 if the file was renamed
3164 successfully, and non-zero when the renaming failed.
3165 This function is not available in the |sandbox|.
3166
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003167repeat({expr}, {count}) *repeat()*
3168 Repeat {expr} {count} times and return the concatenated
3169 result. Example: >
3170 :let seperator = repeat('-', 80)
3171< When {count} is zero or negative the result is empty.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003172 When {expr} is a List the result is {expr} concatenated
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003173 {count} times. Example: >
3174 :let longlist = repeat(['a', 'b'], 3)
3175< Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003176
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003177
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178resolve({filename}) *resolve()* *E655*
3179 On MS-Windows, when {filename} is a shortcut (a .lnk file),
3180 returns the path the shortcut points to in a simplified form.
3181 On Unix, repeat resolving symbolic links in all path
3182 components of {filename} and return the simplified result.
3183 To cope with link cycles, resolving of symbolic links is
3184 stopped after 100 iterations.
3185 On other systems, return the simplified {filename}.
3186 The simplification step is done as by |simplify()|.
3187 resolve() keeps a leading path component specifying the
3188 current directory (provided the result is still a relative
3189 path name) and also keeps a trailing path separator.
3190
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003191 *reverse()*
3192reverse({list}) Reverse the order of items in {list} in-place. Returns
3193 {list}.
3194 If you want a list to remain unmodified make a copy first: >
3195 :let revlist = reverse(copy(mylist))
3196
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197search({pattern} [, {flags}]) *search()*
3198 Search for regexp pattern {pattern}. The search starts at the
3199 cursor position.
3200 {flags} is a String, which can contain these character flags:
3201 'b' search backward instead of forward
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003202 'n' do Not move the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203 'w' wrap around the end of the file
3204 'W' don't wrap around the end of the file
3205 If neither 'w' or 'W' is given, the 'wrapscan' option applies.
3206
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003207 When a match has been found its line number is returned.
3208 The cursor will be positioned at the match, unless the 'n'
3209 flag is used).
3210 If there is no match a 0 is returned and the cursor doesn't
3211 move. No error message is given.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212
3213 Example (goes over all files in the argument list): >
3214 :let n = 1
3215 :while n <= argc() " loop over all files in arglist
3216 : exe "argument " . n
3217 : " start at the last char in the file and wrap for the
3218 : " first search to find match at start of file
3219 : normal G$
3220 : let flags = "w"
3221 : while search("foo", flags) > 0
3222 : s/foo/bar/g
3223 : let flags = "W"
3224 : endwhile
3225 : update " write the file if modified
3226 : let n = n + 1
3227 :endwhile
3228<
3229 *searchpair()*
3230searchpair({start}, {middle}, {end} [, {flags} [, {skip}]])
3231 Search for the match of a nested start-end pair. This can be
3232 used to find the "endif" that matches an "if", while other
3233 if/endif pairs in between are ignored.
3234 The search starts at the cursor. If a match is found, the
3235 cursor is positioned at it and the line number is returned.
3236 If no match is found 0 or -1 is returned and the cursor
3237 doesn't move. No error message is given.
3238
3239 {start}, {middle} and {end} are patterns, see |pattern|. They
3240 must not contain \( \) pairs. Use of \%( \) is allowed. When
3241 {middle} is not empty, it is found when searching from either
3242 direction, but only when not in a nested start-end pair. A
3243 typical use is: >
3244 searchpair('\<if\>', '\<else\>', '\<endif\>')
3245< By leaving {middle} empty the "else" is skipped.
3246
3247 {flags} are used like with |search()|. Additionally:
3248 'n' do Not move the cursor
3249 'r' Repeat until no more matches found; will find the
3250 outer pair
3251 'm' return number of Matches instead of line number with
3252 the match; will only be > 1 when 'r' is used.
3253
3254 When a match for {start}, {middle} or {end} is found, the
3255 {skip} expression is evaluated with the cursor positioned on
3256 the start of the match. It should return non-zero if this
3257 match is to be skipped. E.g., because it is inside a comment
3258 or a string.
3259 When {skip} is omitted or empty, every match is accepted.
3260 When evaluating {skip} causes an error the search is aborted
3261 and -1 returned.
3262
3263 The value of 'ignorecase' is used. 'magic' is ignored, the
3264 patterns are used like it's on.
3265
3266 The search starts exactly at the cursor. A match with
3267 {start}, {middle} or {end} at the next character, in the
3268 direction of searching, is the first one found. Example: >
3269 if 1
3270 if 2
3271 endif 2
3272 endif 1
3273< When starting at the "if 2", with the cursor on the "i", and
3274 searching forwards, the "endif 2" is found. When starting on
3275 the character just before the "if 2", the "endif 1" will be
3276 found. That's because the "if 2" will be found first, and
3277 then this is considered to be a nested if/endif from "if 2" to
3278 "endif 2".
3279 When searching backwards and {end} is more than one character,
3280 it may be useful to put "\zs" at the end of the pattern, so
3281 that when the cursor is inside a match with the end it finds
3282 the matching start.
3283
3284 Example, to find the "endif" command in a Vim script: >
3285
3286 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
3287 \ 'getline(".") =~ "^\\s*\""')
3288
3289< The cursor must be at or after the "if" for which a match is
3290 to be found. Note that single-quote strings are used to avoid
3291 having to double the backslashes. The skip expression only
3292 catches comments at the start of a line, not after a command.
3293 Also, a word "en" or "if" halfway a line is considered a
3294 match.
3295 Another example, to search for the matching "{" of a "}": >
3296
3297 :echo searchpair('{', '', '}', 'bW')
3298
3299< This works when the cursor is at or before the "}" for which a
3300 match is to be found. To reject matches that syntax
3301 highlighting recognized as strings: >
3302
3303 :echo searchpair('{', '', '}', 'bW',
3304 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
3305<
3306server2client( {clientid}, {string}) *server2client()*
3307 Send a reply string to {clientid}. The most recent {clientid}
3308 that sent a string can be retrieved with expand("<client>").
3309 {only available when compiled with the |+clientserver| feature}
3310 Note:
3311 This id has to be stored before the next command can be
3312 received. Ie. before returning from the received command and
3313 before calling any commands that waits for input.
3314 See also |clientserver|.
3315 Example: >
3316 :echo server2client(expand("<client>"), "HELLO")
3317<
3318serverlist() *serverlist()*
3319 Return a list of available server names, one per line.
3320 When there are no servers or the information is not available
3321 an empty string is returned. See also |clientserver|.
3322 {only available when compiled with the |+clientserver| feature}
3323 Example: >
3324 :echo serverlist()
3325<
3326setbufvar({expr}, {varname}, {val}) *setbufvar()*
3327 Set option or local variable {varname} in buffer {expr} to
3328 {val}.
3329 This also works for a global or local window option, but it
3330 doesn't work for a global or local window variable.
3331 For a local window option the global value is unchanged.
3332 For the use of {expr}, see |bufname()| above.
3333 Note that the variable name without "b:" must be used.
3334 Examples: >
3335 :call setbufvar(1, "&mod", 1)
3336 :call setbufvar("todo", "myvar", "foobar")
3337< This function is not available in the |sandbox|.
3338
3339setcmdpos({pos}) *setcmdpos()*
3340 Set the cursor position in the command line to byte position
3341 {pos}. The first position is 1.
3342 Use |getcmdpos()| to obtain the current position.
3343 Only works while editing the command line, thus you must use
Bram Moolenaard8b02732005-01-14 21:48:43 +00003344 |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
3345 |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
3346 set after the command line is set to the expression. For
3347 |c_CTRL-R_=| it is set after evaluating the expression but
3348 before inserting the resulting text.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 When the number is too big the cursor is put at the end of the
3350 line. A number smaller than one has undefined results.
3351 Returns 0 when successful, 1 when not editing the command
3352 line.
3353
3354setline({lnum}, {line}) *setline()*
3355 Set line {lnum} of the current buffer to {line}. If this
3356 succeeds, 0 is returned. If this fails (most likely because
3357 {lnum} is invalid) 1 is returned. Example: >
3358 :call setline(5, strftime("%c"))
3359< Note: The '[ and '] marks are not set.
3360
3361 *setreg()*
3362setreg({regname}, {value} [,{options}])
3363 Set the register {regname} to {value}.
3364 If {options} contains "a" or {regname} is upper case,
3365 then the value is appended.
3366 {options} can also contains a register type specification:
3367 "c" or "v" |characterwise| mode
3368 "l" or "V" |linewise| mode
3369 "b" or "<CTRL-V>" |blockwise-visual| mode
3370 If a number immediately follows "b" or "<CTRL-V>" then this is
3371 used as the width of the selection - if it is not specified
3372 then the width of the block is set to the number of characters
3373 in the longest line (counting a <TAB> as 1 character).
3374
3375 If {options} contains no register settings, then the default
3376 is to use character mode unless {value} ends in a <NL>.
3377 Setting the '=' register is not possible.
3378 Returns zero for success, non-zero for failure.
3379
3380 Examples: >
3381 :call setreg(v:register, @*)
3382 :call setreg('*', @%, 'ac')
3383 :call setreg('a', "1\n2\n3", 'b5')
3384
3385< This example shows using the functions to save and restore a
3386 register. >
3387 :let var_a = getreg('a')
3388 :let var_amode = getregtype('a')
3389 ....
3390 :call setreg('a', var_a, var_amode)
3391
3392< You can also change the type of a register by appending
3393 nothing: >
3394 :call setreg('a', '', 'al')
3395
3396setwinvar({nr}, {varname}, {val}) *setwinvar()*
3397 Set option or local variable {varname} in window {nr} to
3398 {val}.
3399 This also works for a global or local buffer option, but it
3400 doesn't work for a global or local buffer variable.
3401 For a local buffer option the global value is unchanged.
3402 Note that the variable name without "w:" must be used.
3403 Examples: >
3404 :call setwinvar(1, "&list", 0)
3405 :call setwinvar(2, "myvar", "foobar")
3406< This function is not available in the |sandbox|.
3407
3408simplify({filename}) *simplify()*
3409 Simplify the file name as much as possible without changing
3410 the meaning. Shortcuts (on MS-Windows) or symbolic links (on
3411 Unix) are not resolved. If the first path component in
3412 {filename} designates the current directory, this will be
3413 valid for the result as well. A trailing path separator is
3414 not removed either.
3415 Example: >
3416 simplify("./dir/.././/file/") == "./file/"
3417< Note: The combination "dir/.." is only removed if "dir" is
3418 a searchable directory or does not exist. On Unix, it is also
3419 removed when "dir" is a symbolic link within the same
3420 directory. In order to resolve all the involved symbolic
3421 links before simplifying the path name, use |resolve()|.
3422
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003423
Bram Moolenaar13065c42005-01-08 16:08:21 +00003424sort({list} [, {func}]) *sort()* *E702*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003425 Sort the items in {list} in-place. Returns {list}. If you
3426 want a list to remain unmodified make a copy first: >
3427 :let sortedlist = sort(copy(mylist))
3428< Uses the string representation of each item to sort on.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003429 Numbers sort after Strings, Lists after Numbers.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003430 When {func} is given and it is one then case is ignored.
3431 When {func} is a Funcref or a function name, this function is
3432 called to compare items. The function is invoked with two
3433 items as argument and must return zero if they are equal, 1 if
3434 the first one sorts after the second one, -1 if the first one
3435 sorts before the second one. Example: >
3436 func MyCompare(i1, i2)
3437 return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
3438 endfunc
3439 let sortedlist = sort(mylist, "MyCompare")
3440
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003441split({expr} [, {pattern}]) *split()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003442 Make a List out of {expr}. When {pattern} is omitted each
3443 white-separated sequence of characters becomes an item.
3444 Otherwise the string is split where {pattern} matches,
3445 removing the matched characters. Empty strings are omitted.
3446 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003447 :let words = split(getline('.'), '\W\+')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003448< Since empty strings are not added the "\+" isn't required but
3449 it makes the function work a bit faster.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003450 The opposite function is |join()|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003451
3452
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453strftime({format} [, {time}]) *strftime()*
3454 The result is a String, which is a formatted date and time, as
3455 specified by the {format} string. The given {time} is used,
3456 or the current time if no time is given. The accepted
3457 {format} depends on your system, thus this is not portable!
3458 See the manual page of the C function strftime() for the
3459 format. The maximum length of the result is 80 characters.
3460 See also |localtime()| and |getftime()|.
3461 The language can be changed with the |:language| command.
3462 Examples: >
3463 :echo strftime("%c") Sun Apr 27 11:49:23 1997
3464 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
3465 :echo strftime("%y%m%d %T") 970427 11:53:55
3466 :echo strftime("%H:%M") 11:55
3467 :echo strftime("%c", getftime("file.c"))
3468 Show mod time of file.c.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003469< Not available on all systems. To check use: >
3470 :if exists("*strftime")
3471
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472stridx({haystack}, {needle}) *stridx()*
3473 The result is a Number, which gives the index in {haystack} of
3474 the first occurrence of the String {needle} in the String
3475 {haystack}. The search is done case-sensitive. For advanced
3476 searches use |match()|.
3477 If the {needle} does not occur in {haystack} it returns -1.
3478 See also |strridx()|. Examples: >
3479 :echo stridx("An Example", "Example") 3
3480 :echo stridx("Starting point", "Start") 0
3481 :echo stridx("Starting point", "start") -1
3482<
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003483 *string()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003484string({expr}) Return {expr} converted to a String. If {expr} is a Number,
3485 String or a composition of them, then the result can be parsed
3486 back with |eval()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003487 {expr} type result ~
Bram Moolenaard8b02732005-01-14 21:48:43 +00003488 String 'string'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003489 Number 123
Bram Moolenaard8b02732005-01-14 21:48:43 +00003490 Funcref function('name')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003491 List [item, item]
Bram Moolenaard8b02732005-01-14 21:48:43 +00003492 Note that in String values the ' character is doubled.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003493
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 *strlen()*
3495strlen({expr}) The result is a Number, which is the length of the String
3496 {expr} in bytes. If you want to count the number of
3497 multi-byte characters use something like this: >
3498
3499 :let len = strlen(substitute(str, ".", "x", "g"))
3500
3501< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003502 If the argument is a Number it is first converted to a String.
3503 For other types an error is given.
3504 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505
3506strpart({src}, {start}[, {len}]) *strpart()*
3507 The result is a String, which is part of {src}, starting from
3508 byte {start}, with the length {len}.
3509 When non-existing bytes are included, this doesn't result in
3510 an error, the bytes are simply omitted.
3511 If {len} is missing, the copy continues from {start} till the
3512 end of the {src}. >
3513 strpart("abcdefg", 3, 2) == "de"
3514 strpart("abcdefg", -2, 4) == "ab"
3515 strpart("abcdefg", 5, 4) == "fg"
3516 strpart("abcdefg", 3) == "defg"
3517< Note: To get the first character, {start} must be 0. For
3518 example, to get three bytes under and after the cursor: >
3519 strpart(getline(line(".")), col(".") - 1, 3)
3520<
3521strridx({haystack}, {needle}) *strridx()*
3522 The result is a Number, which gives the index in {haystack} of
3523 the last occurrence of the String {needle} in the String
3524 {haystack}. The search is done case-sensitive. For advanced
3525 searches use |match()|.
3526 If the {needle} does not occur in {haystack} it returns -1.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003527 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 See also |stridx()|. Examples: >
3529 :echo strridx("an angry armadillo", "an") 3
3530<
3531strtrans({expr}) *strtrans()*
3532 The result is a String, which is {expr} with all unprintable
3533 characters translated into printable characters |'isprint'|.
3534 Like they are shown in a window. Example: >
3535 echo strtrans(@a)
3536< This displays a newline in register a as "^@" instead of
3537 starting a new line.
3538
3539submatch({nr}) *submatch()*
3540 Only for an expression in a |:substitute| command. Returns
3541 the {nr}'th submatch of the matched text. When {nr} is 0
3542 the whole matched text is returned.
3543 Example: >
3544 :s/\d\+/\=submatch(0) + 1/
3545< This finds the first number in the line and adds one to it.
3546 A line break is included as a newline character.
3547
3548substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
3549 The result is a String, which is a copy of {expr}, in which
3550 the first match of {pat} is replaced with {sub}. This works
3551 like the ":substitute" command (without any flags). But the
3552 matching with {pat} is always done like the 'magic' option is
3553 set and 'cpoptions' is empty (to make scripts portable).
3554 See |string-match| for how {pat} is used.
3555 And a "~" in {sub} is not replaced with the previous {sub}.
3556 Note that some codes in {sub} have a special meaning
3557 |sub-replace-special|. For example, to replace something with
3558 "\n" (two characters), use "\\\\n" or '\\n'.
3559 When {pat} does not match in {expr}, {expr} is returned
3560 unmodified.
3561 When {flags} is "g", all matches of {pat} in {expr} are
3562 replaced. Otherwise {flags} should be "".
3563 Example: >
3564 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
3565< This removes the last component of the 'path' option. >
3566 :echo substitute("testing", ".*", "\\U\\0", "")
3567< results in "TESTING".
3568
Bram Moolenaar47136d72004-10-12 20:02:24 +00003569synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00003571 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 The syntax ID can be used with |synIDattr()| and
3573 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00003574 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 line.
3576 When {trans} is non-zero, transparent items are reduced to the
3577 item that they reveal. This is useful when wanting to know
3578 the effective color. When {trans} is zero, the transparent
3579 item is returned. This is useful when wanting to know which
3580 syntax item is effective (e.g. inside parens).
3581 Warning: This function can be very slow. Best speed is
3582 obtained by going through the file in forward direction.
3583
3584 Example (echoes the name of the syntax item under the cursor): >
3585 :echo synIDattr(synID(line("."), col("."), 1), "name")
3586<
3587synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
3588 The result is a String, which is the {what} attribute of
3589 syntax ID {synID}. This can be used to obtain information
3590 about a syntax item.
3591 {mode} can be "gui", "cterm" or "term", to get the attributes
3592 for that mode. When {mode} is omitted, or an invalid value is
3593 used, the attributes for the currently active highlighting are
3594 used (GUI, cterm or term).
3595 Use synIDtrans() to follow linked highlight groups.
3596 {what} result
3597 "name" the name of the syntax item
3598 "fg" foreground color (GUI: color name used to set
3599 the color, cterm: color number as a string,
3600 term: empty string)
3601 "bg" background color (like "fg")
3602 "fg#" like "fg", but for the GUI and the GUI is
3603 running the name in "#RRGGBB" form
3604 "bg#" like "fg#" for "bg"
3605 "bold" "1" if bold
3606 "italic" "1" if italic
3607 "reverse" "1" if reverse
3608 "inverse" "1" if inverse (= reverse)
3609 "underline" "1" if underlined
3610
3611 Example (echoes the color of the syntax item under the
3612 cursor): >
3613 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
3614<
3615synIDtrans({synID}) *synIDtrans()*
3616 The result is a Number, which is the translated syntax ID of
3617 {synID}. This is the syntax group ID of what is being used to
3618 highlight the character. Highlight links given with
3619 ":highlight link" are followed.
3620
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003621system({expr} [, {input}]) *system()* *E677*
3622 Get the output of the shell command {expr}.
3623 When {input} is given, this string is written to a file and
3624 passed as stdin to the command. The string is written as-is,
3625 you need to take care of using the correct line separators
3626 yourself.
3627 Note: newlines in {expr} may cause the command to fail. The
3628 characters in 'shellquote' and 'shellxquote' may also cause
3629 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 This is not to be used for interactive commands.
3631 The result is a String. Example: >
3632
3633 :let files = system("ls")
3634
3635< To make the result more system-independent, the shell output
3636 is filtered to replace <CR> with <NL> for Macintosh, and
3637 <CR><NL> with <NL> for DOS-like systems.
3638 The command executed is constructed using several options:
3639 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
3640 ({tmp} is an automatically generated file name).
3641 For Unix and OS/2 braces are put around {expr} to allow for
3642 concatenated commands.
3643
3644 The resulting error code can be found in |v:shell_error|.
3645 This function will fail in |restricted-mode|.
3646 Unlike ":!cmd" there is no automatic check for changed files.
3647 Use |:checktime| to force a check.
3648
3649tempname() *tempname()* *temp-file-name*
3650 The result is a String, which is the name of a file that
3651 doesn't exist. It can be used for a temporary file. The name
3652 is different for at least 26 consecutive calls. Example: >
3653 :let tmpfile = tempname()
3654 :exe "redir > " . tmpfile
3655< For Unix, the file will be in a private directory (only
3656 accessible by the current user) to avoid security problems
3657 (e.g., a symlink attack or other people reading your file).
3658 When Vim exits the directory and all files in it are deleted.
3659 For MS-Windows forward slashes are used when the 'shellslash'
3660 option is set or when 'shellcmdflag' starts with '-'.
3661
3662tolower({expr}) *tolower()*
3663 The result is a copy of the String given, with all uppercase
3664 characters turned into lowercase (just like applying |gu| to
3665 the string).
3666
3667toupper({expr}) *toupper()*
3668 The result is a copy of the String given, with all lowercase
3669 characters turned into uppercase (just like applying |gU| to
3670 the string).
3671
Bram Moolenaar8299df92004-07-10 09:47:34 +00003672tr({src}, {fromstr}, {tostr}) *tr()*
3673 The result is a copy of the {src} string with all characters
3674 which appear in {fromstr} replaced by the character in that
3675 position in the {tostr} string. Thus the first character in
3676 {fromstr} is translated into the first character in {tostr}
3677 and so on. Exactly like the unix "tr" command.
3678 This code also deals with multibyte characters properly.
3679
3680 Examples: >
3681 echo tr("hello there", "ht", "HT")
3682< returns "Hello THere" >
3683 echo tr("<blob>", "<>", "{}")
3684< returns "{blob}"
3685
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003686 *type()*
3687type({expr}) The result is a Number, depending on the type of {expr}:
3688 Number: 0
3689 String: 1
3690 Funcref: 2
3691 List: 3
3692 To avoid the magic numbers it can be used this way: >
3693 :if type(myvar) == type(0)
3694 :if type(myvar) == type("")
3695 :if type(myvar) == type(function("tr"))
3696 :if type(myvar) == type([])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697
3698virtcol({expr}) *virtcol()*
3699 The result is a Number, which is the screen column of the file
3700 position given with {expr}. That is, the last screen position
3701 occupied by the character at that position, when the screen
3702 would be of unlimited width. When there is a <Tab> at the
3703 position, the returned Number will be the column at the end of
3704 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
3705 set to 8, it returns 8.
3706 For the byte position use |col()|.
3707 When Virtual editing is active in the current mode, a position
3708 beyond the end of the line can be returned. |'virtualedit'|
3709 The accepted positions are:
3710 . the cursor position
3711 $ the end of the cursor line (the result is the
3712 number of displayed characters in the cursor line
3713 plus one)
3714 'x position of mark x (if the mark is not set, 0 is
3715 returned)
3716 Note that only marks in the current file can be used.
3717 Examples: >
3718 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
3719 virtcol("$") with text "foo^Lbar", returns 9
3720 virtcol("'t") with text " there", with 't at 'h', returns 6
3721< The first column is 1. 0 is returned for an error.
3722
3723visualmode([expr]) *visualmode()*
3724 The result is a String, which describes the last Visual mode
3725 used. Initially it returns an empty string, but once Visual
3726 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
3727 single CTRL-V character) for character-wise, line-wise, or
3728 block-wise Visual mode respectively.
3729 Example: >
3730 :exe "normal " . visualmode()
3731< This enters the same Visual mode as before. It is also useful
3732 in scripts if you wish to act differently depending on the
3733 Visual mode that was used.
3734
3735 If an expression is supplied that results in a non-zero number
3736 or a non-empty string, then the Visual mode will be cleared
3737 and the old value is returned. Note that " " and "0" are also
3738 non-empty strings, thus cause the mode to be cleared.
3739
3740 *winbufnr()*
3741winbufnr({nr}) The result is a Number, which is the number of the buffer
3742 associated with window {nr}. When {nr} is zero, the number of
3743 the buffer in the current window is returned. When window
3744 {nr} doesn't exist, -1 is returned.
3745 Example: >
3746 :echo "The file in the current window is " . bufname(winbufnr(0))
3747<
3748 *wincol()*
3749wincol() The result is a Number, which is the virtual column of the
3750 cursor in the window. This is counting screen cells from the
3751 left side of the window. The leftmost column is one.
3752
3753winheight({nr}) *winheight()*
3754 The result is a Number, which is the height of window {nr}.
3755 When {nr} is zero, the height of the current window is
3756 returned. When window {nr} doesn't exist, -1 is returned.
3757 An existing window always has a height of zero or more.
3758 Examples: >
3759 :echo "The current window has " . winheight(0) . " lines."
3760<
3761 *winline()*
3762winline() The result is a Number, which is the screen line of the cursor
3763 in the window. This is counting screen lines from the top of
3764 the window. The first line is one.
3765
3766 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003767winnr([{arg}]) The result is a Number, which is the number of the current
3768 window. The top window has number 1.
3769 When the optional argument is "$", the number of the
3770 last window is returnd (the window count).
3771 When the optional argument is "#", the number of the last
3772 accessed window is returned (where |CTRL-W_p| goes to).
3773 If there is no previous window 0 is returned.
3774 The number can be used with |CTRL-W_w| and ":wincmd w"
3775 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776
3777 *winrestcmd()*
3778winrestcmd() Returns a sequence of |:resize| commands that should restore
3779 the current window sizes. Only works properly when no windows
3780 are opened or closed and the current window is unchanged.
3781 Example: >
3782 :let cmd = winrestcmd()
3783 :call MessWithWindowSizes()
3784 :exe cmd
3785
3786winwidth({nr}) *winwidth()*
3787 The result is a Number, which is the width of window {nr}.
3788 When {nr} is zero, the width of the current window is
3789 returned. When window {nr} doesn't exist, -1 is returned.
3790 An existing window always has a width of zero or more.
3791 Examples: >
3792 :echo "The current window has " . winwidth(0) . " columns."
3793 :if winwidth(0) <= 50
3794 : exe "normal 50\<C-W>|"
3795 :endif
3796<
3797
3798 *feature-list*
3799There are three types of features:
38001. Features that are only supported when they have been enabled when Vim
3801 was compiled |+feature-list|. Example: >
3802 :if has("cindent")
38032. Features that are only supported when certain conditions have been met.
3804 Example: >
3805 :if has("gui_running")
3806< *has-patch*
38073. Included patches. First check |v:version| for the version of Vim.
3808 Then the "patch123" feature means that patch 123 has been included for
3809 this version. Example (checking version 6.2.148 or later): >
3810 :if v:version > 602 || v:version == 602 && has("patch148")
3811
3812all_builtin_terms Compiled with all builtin terminals enabled.
3813amiga Amiga version of Vim.
3814arabic Compiled with Arabic support |Arabic|.
3815arp Compiled with ARP support (Amiga).
3816autocmd Compiled with autocommands support.
3817balloon_eval Compiled with |balloon-eval| support.
3818beos BeOS version of Vim.
3819browse Compiled with |:browse| support, and browse() will
3820 work.
3821builtin_terms Compiled with some builtin terminals.
3822byte_offset Compiled with support for 'o' in 'statusline'
3823cindent Compiled with 'cindent' support.
3824clientserver Compiled with remote invocation support |clientserver|.
3825clipboard Compiled with 'clipboard' support.
3826cmdline_compl Compiled with |cmdline-completion| support.
3827cmdline_hist Compiled with |cmdline-history| support.
3828cmdline_info Compiled with 'showcmd' and 'ruler' support.
3829comments Compiled with |'comments'| support.
3830cryptv Compiled with encryption support |encryption|.
3831cscope Compiled with |cscope| support.
3832compatible Compiled to be very Vi compatible.
3833debug Compiled with "DEBUG" defined.
3834dialog_con Compiled with console dialog support.
3835dialog_gui Compiled with GUI dialog support.
3836diff Compiled with |vimdiff| and 'diff' support.
3837digraphs Compiled with support for digraphs.
3838dnd Compiled with support for the "~ register |quote_~|.
3839dos32 32 bits DOS (DJGPP) version of Vim.
3840dos16 16 bits DOS version of Vim.
3841ebcdic Compiled on a machine with ebcdic character set.
3842emacs_tags Compiled with support for Emacs tags.
3843eval Compiled with expression evaluation support. Always
3844 true, of course!
3845ex_extra Compiled with extra Ex commands |+ex_extra|.
3846extra_search Compiled with support for |'incsearch'| and
3847 |'hlsearch'|
3848farsi Compiled with Farsi support |farsi|.
3849file_in_path Compiled with support for |gf| and |<cfile>|
3850find_in_path Compiled with support for include file searches
3851 |+find_in_path|.
3852fname_case Case in file names matters (for Amiga, MS-DOS, and
3853 Windows this is not present).
3854folding Compiled with |folding| support.
3855footer Compiled with GUI footer support. |gui-footer|
3856fork Compiled to use fork()/exec() instead of system().
3857gettext Compiled with message translation |multi-lang|
3858gui Compiled with GUI enabled.
3859gui_athena Compiled with Athena GUI.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003860gui_beos Compiled with BeOS GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861gui_gtk Compiled with GTK+ GUI (any version).
3862gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00003863gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864gui_mac Compiled with Macintosh GUI.
3865gui_motif Compiled with Motif GUI.
3866gui_photon Compiled with Photon GUI.
3867gui_win32 Compiled with MS Windows Win32 GUI.
3868gui_win32s idem, and Win32s system being used (Windows 3.1)
3869gui_running Vim is running in the GUI, or it will start soon.
3870hangul_input Compiled with Hangul input support. |hangul|
3871iconv Can use iconv() for conversion.
3872insert_expand Compiled with support for CTRL-X expansion commands in
3873 Insert mode.
3874jumplist Compiled with |jumplist| support.
3875keymap Compiled with 'keymap' support.
3876langmap Compiled with 'langmap' support.
3877libcall Compiled with |libcall()| support.
3878linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
3879 support.
3880lispindent Compiled with support for lisp indenting.
3881listcmds Compiled with commands for the buffer list |:files|
3882 and the argument list |arglist|.
3883localmap Compiled with local mappings and abbr. |:map-local|
3884mac Macintosh version of Vim.
3885macunix Macintosh version of Vim, using Unix files (OS-X).
3886menu Compiled with support for |:menu|.
3887mksession Compiled with support for |:mksession|.
3888modify_fname Compiled with file name modifiers. |filename-modifiers|
3889mouse Compiled with support mouse.
3890mouseshape Compiled with support for 'mouseshape'.
3891mouse_dec Compiled with support for Dec terminal mouse.
3892mouse_gpm Compiled with support for gpm (Linux console mouse)
3893mouse_netterm Compiled with support for netterm mouse.
3894mouse_pterm Compiled with support for qnx pterm mouse.
3895mouse_xterm Compiled with support for xterm mouse.
3896multi_byte Compiled with support for editing Korean et al.
3897multi_byte_ime Compiled with support for IME input method.
3898multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00003899mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00003901netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902ole Compiled with OLE automation support for Win32.
3903os2 OS/2 version of Vim.
3904osfiletype Compiled with support for osfiletypes |+osfiletype|
3905path_extra Compiled with up/downwards search in 'path' and 'tags'
3906perl Compiled with Perl interface.
3907postscript Compiled with PostScript file printing.
3908printer Compiled with |:hardcopy| support.
3909python Compiled with Python interface.
3910qnx QNX version of Vim.
3911quickfix Compiled with |quickfix| support.
3912rightleft Compiled with 'rightleft' support.
3913ruby Compiled with Ruby interface |ruby|.
3914scrollbind Compiled with 'scrollbind' support.
3915showcmd Compiled with 'showcmd' support.
3916signs Compiled with |:sign| support.
3917smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003918sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919statusline Compiled with support for 'statusline', 'rulerformat'
3920 and special formats of 'titlestring' and 'iconstring'.
3921sun_workshop Compiled with support for Sun |workshop|.
3922syntax Compiled with syntax highlighting support.
3923syntax_items There are active syntax highlighting items for the
3924 current buffer.
3925system Compiled to use system() instead of fork()/exec().
3926tag_binary Compiled with binary searching in tags files
3927 |tag-binary-search|.
3928tag_old_static Compiled with support for old static tags
3929 |tag-old-static|.
3930tag_any_white Compiled with support for any white characters in tags
3931 files |tag-any-white|.
3932tcl Compiled with Tcl interface.
3933terminfo Compiled with terminfo instead of termcap.
3934termresponse Compiled with support for |t_RV| and |v:termresponse|.
3935textobjects Compiled with support for |text-objects|.
3936tgetent Compiled with tgetent support, able to use a termcap
3937 or terminfo file.
3938title Compiled with window title support |'title'|.
3939toolbar Compiled with support for |gui-toolbar|.
3940unix Unix version of Vim.
3941user_commands User-defined commands.
3942viminfo Compiled with viminfo support.
3943vim_starting True while initial source'ing takes place.
3944vertsplit Compiled with vertically split windows |:vsplit|.
3945virtualedit Compiled with 'virtualedit' option.
3946visual Compiled with Visual mode.
3947visualextra Compiled with extra Visual mode commands.
3948 |blockwise-operators|.
3949vms VMS version of Vim.
3950vreplace Compiled with |gR| and |gr| commands.
3951wildignore Compiled with 'wildignore' option.
3952wildmenu Compiled with 'wildmenu' option.
3953windows Compiled with support for more than one window.
3954winaltkeys Compiled with 'winaltkeys' option.
3955win16 Win16 version of Vim (MS-Windows 3.1).
3956win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
3957win64 Win64 version of Vim (MS-Windows 64 bit).
3958win32unix Win32 version of Vim, using Unix files (Cygwin)
3959win95 Win32 version for MS-Windows 95/98/ME.
3960writebackup Compiled with 'writebackup' default on.
3961xfontset Compiled with X fontset support |xfontset|.
3962xim Compiled with X input method support |xim|.
3963xsmp Compiled with X session management support.
3964xsmp_interact Compiled with interactive X session management support.
3965xterm_clipboard Compiled with support for xterm clipboard.
3966xterm_save Compiled with support for saving and restoring the
3967 xterm screen.
3968x11 Compiled with X11 support.
3969
3970 *string-match*
3971Matching a pattern in a String
3972
3973A regexp pattern as explained at |pattern| is normally used to find a match in
3974the buffer lines. When a pattern is used to find a match in a String, almost
3975everything works in the same way. The difference is that a String is handled
3976like it is one line. When it contains a "\n" character, this is not seen as a
3977line break for the pattern. It can be matched with a "\n" in the pattern, or
3978with ".". Example: >
3979 :let a = "aaaa\nxxxx"
3980 :echo matchstr(a, "..\n..")
3981 aa
3982 xx
3983 :echo matchstr(a, "a.x")
3984 a
3985 x
3986
3987Don't forget that "^" will only match at the first character of the String and
3988"$" at the last character of the string. They don't match after or before a
3989"\n".
3990
3991==============================================================================
39925. Defining functions *user-functions*
3993
3994New functions can be defined. These can be called just like builtin
3995functions. The function executes a sequence of Ex commands. Normal mode
3996commands can be executed with the |:normal| command.
3997
3998The function name must start with an uppercase letter, to avoid confusion with
3999builtin functions. To prevent from using the same name in different scripts
4000avoid obvious, short names. A good habit is to start the function name with
4001the name of the script, e.g., "HTMLcolor()".
4002
4003It's also possible to use curly braces, see |curly-braces-names|.
4004
4005 *local-function*
4006A function local to a script must start with "s:". A local script function
4007can only be called from within the script and from functions, user commands
4008and autocommands defined in the script. It is also possible to call the
4009function from a mappings defined in the script, but then |<SID>| must be used
4010instead of "s:" when the mapping is expanded outside of the script.
4011
4012 *:fu* *:function* *E128* *E129* *E123*
4013:fu[nction] List all functions and their arguments.
4014
4015:fu[nction] {name} List function {name}.
4016 *E124* *E125*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004017:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 Define a new function by the name {name}. The name
4019 must be made of alphanumeric characters and '_', and
4020 must start with a capital or "s:" (see above).
4021 *function-argument* *a:var*
4022 An argument can be defined by giving its name. In the
4023 function this can then be used as "a:name" ("a:" for
4024 argument).
4025 Up to 20 arguments can be given, separated by commas.
4026 Finally, an argument "..." can be specified, which
4027 means that more arguments may be following. In the
4028 function they can be used as "a:1", "a:2", etc. "a:0"
4029 is set to the number of extra arguments (which can be
4030 0).
4031 When not using "...", the number of arguments in a
4032 function call must be equal to the number of named
4033 arguments. When using "...", the number of arguments
4034 may be larger.
4035 It is also possible to define a function without any
4036 arguments. You must still supply the () then.
4037 The body of the function follows in the next lines,
4038 until the matching |:endfunction|. It is allowed to
4039 define another function inside a function body.
4040 *E127* *E122*
4041 When a function by this name already exists and [!] is
4042 not used an error message is given. When [!] is used,
4043 an existing function is silently replaced. Unless it
4044 is currently being executed, that is an error.
4045 *a:firstline* *a:lastline*
4046 When the [range] argument is added, the function is
4047 expected to take care of a range itself. The range is
4048 passed as "a:firstline" and "a:lastline". If [range]
4049 is excluded, ":{range}call" will call the function for
4050 each line in the range, with the cursor on the start
4051 of each line. See |function-range-example|.
4052 When the [abort] argument is added, the function will
4053 abort as soon as an error is detected.
4054 The last used search pattern and the redo command "."
4055 will not be changed by the function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004056 When the [dict] argument is added, the function must
4057 be invoked through an entry in a Dictionary. The
4058 local variable "self" will then be set to the
4059 dictionary. See |Dictionary-function|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060
4061 *:endf* *:endfunction* *E126* *E193*
4062:endf[unction] The end of a function definition. Must be on a line
4063 by its own, without other commands.
4064
4065 *:delf* *:delfunction* *E130* *E131*
4066:delf[unction] {name} Delete function {name}.
4067
4068 *:retu* *:return* *E133*
4069:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
4070 evaluated and returned as the result of the function.
4071 If "[expr]" is not given, the number 0 is returned.
4072 When a function ends without an explicit ":return",
4073 the number 0 is returned.
4074 Note that there is no check for unreachable lines,
4075 thus there is no warning if commands follow ":return".
4076
4077 If the ":return" is used after a |:try| but before the
4078 matching |:finally| (if present), the commands
4079 following the ":finally" up to the matching |:endtry|
4080 are executed first. This process applies to all
4081 nested ":try"s inside the function. The function
4082 returns at the outermost ":endtry".
4083
4084
4085Inside a function variables can be used. These are local variables, which
4086will disappear when the function returns. Global variables need to be
4087accessed with "g:".
4088
4089Example: >
4090 :function Table(title, ...)
4091 : echohl Title
4092 : echo a:title
4093 : echohl None
4094 : let idx = 1
4095 : while idx <= a:0
4096 : echo a:{idx} . ' '
4097 : let idx = idx + 1
4098 : endwhile
4099 : return idx
4100 :endfunction
4101
4102This function can then be called with: >
4103 let lines = Table("Table", "line1", "line2")
4104 let lines = Table("Empty Table")
4105
4106To return more than one value, pass the name of a global variable: >
4107 :function Compute(n1, n2, divname)
4108 : if a:n2 == 0
4109 : return "fail"
4110 : endif
4111 : let g:{a:divname} = a:n1 / a:n2
4112 : return "ok"
4113 :endfunction
4114
4115This function can then be called with: >
4116 :let success = Compute(13, 1324, "div")
4117 :if success == "ok"
4118 : echo div
4119 :endif
4120
4121An alternative is to return a command that can be executed. This also works
4122with local variables in a calling function. Example: >
4123 :function Foo()
4124 : execute Bar()
4125 : echo "line " . lnum . " column " . col
4126 :endfunction
4127
4128 :function Bar()
4129 : return "let lnum = " . line(".") . " | let col = " . col(".")
4130 :endfunction
4131
4132The names "lnum" and "col" could also be passed as argument to Bar(), to allow
4133the caller to set the names.
4134
4135 *:cal* *:call* *E107*
4136:[range]cal[l] {name}([arguments])
4137 Call a function. The name of the function and its arguments
4138 are as specified with |:function|. Up to 20 arguments can be
4139 used.
4140 Without a range and for functions that accept a range, the
4141 function is called once. When a range is given the cursor is
4142 positioned at the start of the first line before executing the
4143 function.
4144 When a range is given and the function doesn't handle it
4145 itself, the function is executed for each line in the range,
4146 with the cursor in the first column of that line. The cursor
4147 is left at the last line (possibly moved by the last function
4148 call). The arguments are re-evaluated for each line. Thus
4149 this works:
4150 *function-range-example* >
4151 :function Mynumber(arg)
4152 : echo line(".") . " " . a:arg
4153 :endfunction
4154 :1,5call Mynumber(getline("."))
4155<
4156 The "a:firstline" and "a:lastline" are defined anyway, they
4157 can be used to do something different at the start or end of
4158 the range.
4159
4160 Example of a function that handles the range itself: >
4161
4162 :function Cont() range
4163 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
4164 :endfunction
4165 :4,8call Cont()
4166<
4167 This function inserts the continuation character "\" in front
4168 of all the lines in the range, except the first one.
4169
4170 *E132*
4171The recursiveness of user functions is restricted with the |'maxfuncdepth'|
4172option.
4173
4174 *autoload-functions*
4175When using many or large functions, it's possible to automatically define them
4176only when they are used. Use the FuncUndefined autocommand event with a
4177pattern that matches the function(s) to be defined. Example: >
4178
4179 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
4180
4181The file "~/vim/bufnetfuncs.vim" should then define functions that start with
4182"BufNet". Also see |FuncUndefined|.
4183
4184==============================================================================
41856. Curly braces names *curly-braces-names*
4186
4187Wherever you can use a variable, you can use a "curly braces name" variable.
4188This is a regular variable name with one or more expressions wrapped in braces
4189{} like this: >
4190 my_{adjective}_variable
4191
4192When Vim encounters this, it evaluates the expression inside the braces, puts
4193that in place of the expression, and re-interprets the whole as a variable
4194name. So in the above example, if the variable "adjective" was set to
4195"noisy", then the reference would be to "my_noisy_variable", whereas if
4196"adjective" was set to "quiet", then it would be to "my_quiet_variable".
4197
4198One application for this is to create a set of variables governed by an option
4199value. For example, the statement >
4200 echo my_{&background}_message
4201
4202would output the contents of "my_dark_message" or "my_light_message" depending
4203on the current value of 'background'.
4204
4205You can use multiple brace pairs: >
4206 echo my_{adverb}_{adjective}_message
4207..or even nest them: >
4208 echo my_{ad{end_of_word}}_message
4209where "end_of_word" is either "verb" or "jective".
4210
4211However, the expression inside the braces must evaluate to a valid single
4212variable name. e.g. this is invalid: >
4213 :let foo='a + b'
4214 :echo c{foo}d
4215.. since the result of expansion is "ca + bd", which is not a variable name.
4216
4217 *curly-braces-function-names*
4218You can call and define functions by an evaluated name in a similar way.
4219Example: >
4220 :let func_end='whizz'
4221 :call my_func_{func_end}(parameter)
4222
4223This would call the function "my_func_whizz(parameter)".
4224
4225==============================================================================
42267. Commands *expression-commands*
4227
4228:let {var-name} = {expr1} *:let* *E18*
4229 Set internal variable {var-name} to the result of the
4230 expression {expr1}. The variable will get the type
4231 from the {expr}. If {var-name} didn't exist yet, it
4232 is created.
4233
Bram Moolenaar13065c42005-01-08 16:08:21 +00004234:let {var-name}[{idx}] = {expr1} *E689*
4235 Set a list item to the result of the expression
4236 {expr1}. {var-name} must refer to a list and {idx}
4237 must be a valid index in that list. For nested list
4238 the index can be repeated.
4239 This cannot be used to add an item to a list.
4240
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004241:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710* *E711*
4242 Set a sequence of items in a List to the result of the
4243 expression {expr1}, which must be a list with the
4244 correct number of items.
4245 {idx1} can be omitted, zero is used instead.
4246 {idx2} can be omitted, meaning the end of the list.
4247 When the selected range of items is partly past the
4248 end of the list, items will be added.
4249
Bram Moolenaar071d4272004-06-13 20:20:40 +00004250:let ${env-name} = {expr1} *:let-environment* *:let-$*
4251 Set environment variable {env-name} to the result of
4252 the expression {expr1}. The type is always String.
4253
4254:let @{reg-name} = {expr1} *:let-register* *:let-@*
4255 Write the result of the expression {expr1} in register
4256 {reg-name}. {reg-name} must be a single letter, and
4257 must be the name of a writable register (see
4258 |registers|). "@@" can be used for the unnamed
4259 register, "@/" for the search pattern.
4260 If the result of {expr1} ends in a <CR> or <NL>, the
4261 register will be linewise, otherwise it will be set to
4262 characterwise.
4263 This can be used to clear the last search pattern: >
4264 :let @/ = ""
4265< This is different from searching for an empty string,
4266 that would match everywhere.
4267
4268:let &{option-name} = {expr1} *:let-option* *:let-star*
4269 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004270 expression {expr1}. A String or Number value is
4271 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 For an option local to a window or buffer the effect
4273 is just like using the |:set| command: both the local
4274 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004275 Example: >
4276 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277
4278:let &l:{option-name} = {expr1}
4279 Like above, but only set the local value of an option
4280 (if there is one). Works like |:setlocal|.
4281
4282:let &g:{option-name} = {expr1}
4283 Like above, but only set the global value of an option
4284 (if there is one). Works like |:setglobal|.
4285
Bram Moolenaar13065c42005-01-08 16:08:21 +00004286:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004287 {expr1} must evaluate to a List. The first item in
4288 the list is assigned to {name1}, the second item to
4289 {name2}, etc.
4290 The number of names must match the number of items in
4291 the List.
4292 Each name can be one of the items of the ":let"
4293 command as mentioned above.
4294 Example: >
4295 :let [s, item] = GetItem(s)
4296
4297:let [{name}, ..., ; {lastname}] = {expr1}
4298 Like above, but the List may have more items than
4299 there are names. A list of the remaining items is
4300 assigned to {lastname}. If there are no remaining
4301 items {lastname} is set to an empty list.
4302 Example: >
4303 :let [a, b; rest] = ["aval", "bval", 3, 4]
4304<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 *E106*
4306:let {var-name} .. List the value of variable {var-name}. Several
4307 variable names may be given.
4308
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00004309:let List the values of all variables. The type of the
4310 variable is indicated before the value:
4311 <nothing> String
4312 # Number
4313 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314
4315 *:unlet* *:unl* *E108*
4316:unl[et][!] {var-name} ...
4317 Remove the internal variable {var-name}. Several
4318 variable names can be given, they are all removed.
4319 With [!] no error message is given for non-existing
4320 variables.
Bram Moolenaar9cd15162005-01-16 22:02:49 +00004321 One or more items from a List can be removed: >
4322 :unlet list[3] " remove fourth item
4323 :unlet list[3:] " remove fourth item to last
4324< One item from a Dictionary can be removed at a time: >
4325 :unlet dict['two']
4326 :unlet dict.two
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327
4328:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
4329:en[dif] Execute the commands until the next matching ":else"
4330 or ":endif" if {expr1} evaluates to non-zero.
4331
4332 From Vim version 4.5 until 5.0, every Ex command in
4333 between the ":if" and ":endif" is ignored. These two
4334 commands were just to allow for future expansions in a
4335 backwards compatible way. Nesting was allowed. Note
4336 that any ":else" or ":elseif" was ignored, the "else"
4337 part was not executed either.
4338
4339 You can use this to remain compatible with older
4340 versions: >
4341 :if version >= 500
4342 : version-5-specific-commands
4343 :endif
4344< The commands still need to be parsed to find the
4345 "endif". Sometimes an older Vim has a problem with a
4346 new command. For example, ":silent" is recognized as
4347 a ":substitute" command. In that case ":execute" can
4348 avoid problems: >
4349 :if version >= 600
4350 : execute "silent 1,$delete"
4351 :endif
4352<
4353 NOTE: The ":append" and ":insert" commands don't work
4354 properly in between ":if" and ":endif".
4355
4356 *:else* *:el* *E581* *E583*
4357:el[se] Execute the commands until the next matching ":else"
4358 or ":endif" if they previously were not being
4359 executed.
4360
4361 *:elseif* *:elsei* *E582* *E584*
4362:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
4363 is no extra ":endif".
4364
4365:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
4366 *E170* *E585* *E588*
4367:endw[hile] Repeat the commands between ":while" and ":endwhile",
4368 as long as {expr1} evaluates to non-zero.
4369 When an error is detected from a command inside the
4370 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00004371 Example: >
4372 :let lnum = 1
4373 :while lnum <= line("$")
4374 :call FixLine(lnum)
4375 :let lnum = lnum + 1
4376 :endwhile
4377<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00004379 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380
Bram Moolenaar13065c42005-01-08 16:08:21 +00004381:for {var} in {list} *:for* *E690*
Bram Moolenaar12805862005-01-05 22:16:17 +00004382:endfo[r] *:endfo* *:endfor*
4383 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004384 each item in {list}. variable {var} is set to the
4385 value of each item.
4386 When an error is detected for a command inside the
Bram Moolenaar12805862005-01-05 22:16:17 +00004387 loop, execution continues after the "endfor".
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004388 Changing {list} affects what items are used. Make a
4389 copy if this is unwanted: >
4390 :for item in copy(mylist)
4391< When not making a copy, Vim stores a reference to the
4392 next item in the list, before executing the commands
4393 with the current item. Thus the current item can be
4394 removed without effect. Removing any later item means
4395 it will not be found. Thus the following example
4396 works (an inefficient way to make a list empty): >
4397 :for item in mylist
Bram Moolenaar12805862005-01-05 22:16:17 +00004398 :call remove(mylist, 0)
4399 :endfor
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004400< Note that reordering the list (e.g., with sort() or
4401 reverse()) may have unexpected effects.
4402 Note that the type of each list item should be
Bram Moolenaar12805862005-01-05 22:16:17 +00004403 identical to avoid errors for the type of {var}
4404 changing. Unlet the variable at the end of the loop
4405 to allow multiple item types.
4406
4407:for {var} in {string}
4408:endfo[r] Like ":for" above, but use each character in {string}
4409 as a list item.
4410 Composing characters are used as separate characters.
4411 A Number is first converted to a String.
4412
4413:for [{var1}, {var2}, ...] in {listlist}
4414:endfo[r]
4415 Like ":for" above, but each item in {listlist} must be
4416 a list, of which each item is assigned to {var1},
4417 {var2}, etc. Example: >
4418 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
4419 :echo getline(lnum)[col]
4420 :endfor
4421<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004422 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00004423:con[tinue] When used inside a ":while" or ":for" loop, jumps back
4424 to the start of the loop.
4425 If it is used after a |:try| inside the loop but
4426 before the matching |:finally| (if present), the
4427 commands following the ":finally" up to the matching
4428 |:endtry| are executed first. This process applies to
4429 all nested ":try"s inside the loop. The outermost
4430 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431
4432 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00004433:brea[k] When used inside a ":while" or ":for" loop, skips to
4434 the command after the matching ":endwhile" or
4435 ":endfor".
4436 If it is used after a |:try| inside the loop but
4437 before the matching |:finally| (if present), the
4438 commands following the ":finally" up to the matching
4439 |:endtry| are executed first. This process applies to
4440 all nested ":try"s inside the loop. The outermost
4441 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442
4443:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
4444:endt[ry] Change the error handling for the commands between
4445 ":try" and ":endtry" including everything being
4446 executed across ":source" commands, function calls,
4447 or autocommand invocations.
4448
4449 When an error or interrupt is detected and there is
4450 a |:finally| command following, execution continues
4451 after the ":finally". Otherwise, or when the
4452 ":endtry" is reached thereafter, the next
4453 (dynamically) surrounding ":try" is checked for
4454 a corresponding ":finally" etc. Then the script
4455 processing is terminated. (Whether a function
4456 definition has an "abort" argument does not matter.)
4457 Example: >
4458 :try | edit too much | finally | echo "cleanup" | endtry
4459 :echo "impossible" " not reached, script terminated above
4460<
4461 Moreover, an error or interrupt (dynamically) inside
4462 ":try" and ":endtry" is converted to an exception. It
4463 can be caught as if it were thrown by a |:throw|
4464 command (see |:catch|). In this case, the script
4465 processing is not terminated.
4466
4467 The value "Vim:Interrupt" is used for an interrupt
4468 exception. An error in a Vim command is converted
4469 to a value of the form "Vim({command}):{errmsg}",
4470 other errors are converted to a value of the form
4471 "Vim:{errmsg}". {command} is the full command name,
4472 and {errmsg} is the message that is displayed if the
4473 error exception is not caught, always beginning with
4474 the error number.
4475 Examples: >
4476 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
4477 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
4478<
4479 *:cat* *:catch* *E603* *E604* *E605*
4480:cat[ch] /{pattern}/ The following commands until the next ":catch",
4481 |:finally|, or |:endtry| that belongs to the same
4482 |:try| as the ":catch" are executed when an exception
4483 matching {pattern} is being thrown and has not yet
4484 been caught by a previous ":catch". Otherwise, these
4485 commands are skipped.
4486 When {pattern} is omitted all errors are caught.
4487 Examples: >
4488 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
4489 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
4490 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
4491 :catch /^Vim(write):/ " catch all errors in :write
4492 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
4493 :catch /my-exception/ " catch user exception
4494 :catch /.*/ " catch everything
4495 :catch " same as /.*/
4496<
4497 Another character can be used instead of / around the
4498 {pattern}, so long as it does not have a special
4499 meaning (e.g., '|' or '"') and doesn't occur inside
4500 {pattern}.
4501 NOTE: It is not reliable to ":catch" the TEXT of
4502 an error message because it may vary in different
4503 locales.
4504
4505 *:fina* *:finally* *E606* *E607*
4506:fina[lly] The following commands until the matching |:endtry|
4507 are executed whenever the part between the matching
4508 |:try| and the ":finally" is left: either by falling
4509 through to the ":finally" or by a |:continue|,
4510 |:break|, |:finish|, or |:return|, or by an error or
4511 interrupt or exception (see |:throw|).
4512
4513 *:th* *:throw* *E608*
4514:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
4515 If the ":throw" is used after a |:try| but before the
4516 first corresponding |:catch|, commands are skipped
4517 until the first ":catch" matching {expr1} is reached.
4518 If there is no such ":catch" or if the ":throw" is
4519 used after a ":catch" but before the |:finally|, the
4520 commands following the ":finally" (if present) up to
4521 the matching |:endtry| are executed. If the ":throw"
4522 is after the ":finally", commands up to the ":endtry"
4523 are skipped. At the ":endtry", this process applies
4524 again for the next dynamically surrounding ":try"
4525 (which may be found in a calling function or sourcing
4526 script), until a matching ":catch" has been found.
4527 If the exception is not caught, the command processing
4528 is terminated.
4529 Example: >
4530 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
4531<
4532
4533 *:ec* *:echo*
4534:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
4535 first {expr1} starts on a new line.
4536 Also see |:comment|.
4537 Use "\n" to start a new line. Use "\r" to move the
4538 cursor to the first column.
4539 Uses the highlighting set by the |:echohl| command.
4540 Cannot be followed by a comment.
4541 Example: >
4542 :echo "the value of 'shell' is" &shell
4543< A later redraw may make the message disappear again.
4544 To avoid that a command from before the ":echo" causes
4545 a redraw afterwards (redraws are often postponed until
4546 you type something), force a redraw with the |:redraw|
4547 command. Example: >
4548 :new | redraw | echo "there is a new window"
4549<
4550 *:echon*
4551:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
4552 |:comment|.
4553 Uses the highlighting set by the |:echohl| command.
4554 Cannot be followed by a comment.
4555 Example: >
4556 :echon "the value of 'shell' is " &shell
4557<
4558 Note the difference between using ":echo", which is a
4559 Vim command, and ":!echo", which is an external shell
4560 command: >
4561 :!echo % --> filename
4562< The arguments of ":!" are expanded, see |:_%|. >
4563 :!echo "%" --> filename or "filename"
4564< Like the previous example. Whether you see the double
4565 quotes or not depends on your 'shell'. >
4566 :echo % --> nothing
4567< The '%' is an illegal character in an expression. >
4568 :echo "%" --> %
4569< This just echoes the '%' character. >
4570 :echo expand("%") --> filename
4571< This calls the expand() function to expand the '%'.
4572
4573 *:echoh* *:echohl*
4574:echoh[l] {name} Use the highlight group {name} for the following
4575 |:echo|, |:echon| and |:echomsg| commands. Also used
4576 for the |input()| prompt. Example: >
4577 :echohl WarningMsg | echo "Don't panic!" | echohl None
4578< Don't forget to set the group back to "None",
4579 otherwise all following echo's will be highlighted.
4580
4581 *:echom* *:echomsg*
4582:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
4583 message in the |message-history|.
4584 Spaces are placed between the arguments as with the
4585 |:echo| command. But unprintable characters are
4586 displayed, not interpreted.
4587 Uses the highlighting set by the |:echohl| command.
4588 Example: >
4589 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
4590<
4591 *:echoe* *:echoerr*
4592:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
4593 message in the |message-history|. When used in a
4594 script or function the line number will be added.
4595 Spaces are placed between the arguments as with the
4596 :echo command. When used inside a try conditional,
4597 the message is raised as an error exception instead
4598 (see |try-echoerr|).
4599 Example: >
4600 :echoerr "This script just failed!"
4601< If you just want a highlighted message use |:echohl|.
4602 And to get a beep: >
4603 :exe "normal \<Esc>"
4604<
4605 *:exe* *:execute*
4606:exe[cute] {expr1} .. Executes the string that results from the evaluation
4607 of {expr1} as an Ex command. Multiple arguments are
4608 concatenated, with a space in between. {expr1} is
4609 used as the processed command, command line editing
4610 keys are not recognized.
4611 Cannot be followed by a comment.
4612 Examples: >
4613 :execute "buffer " nextbuf
4614 :execute "normal " count . "w"
4615<
4616 ":execute" can be used to append a command to commands
4617 that don't accept a '|'. Example: >
4618 :execute '!ls' | echo "theend"
4619
4620< ":execute" is also a nice way to avoid having to type
4621 control characters in a Vim script for a ":normal"
4622 command: >
4623 :execute "normal ixxx\<Esc>"
4624< This has an <Esc> character, see |expr-string|.
4625
4626 Note: The executed string may be any command-line, but
Bram Moolenaard8b02732005-01-14 21:48:43 +00004627 you cannot start or end a "while", "for" or "if"
4628 command. Thus this is illegal: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 :execute 'while i > 5'
4630 :execute 'echo "test" | break'
4631<
4632 It is allowed to have a "while" or "if" command
4633 completely in the executed string: >
4634 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
4635<
4636
4637 *:comment*
4638 ":execute", ":echo" and ":echon" cannot be followed by
4639 a comment directly, because they see the '"' as the
4640 start of a string. But, you can use '|' followed by a
4641 comment. Example: >
4642 :echo "foo" | "this is a comment
4643
4644==============================================================================
46458. Exception handling *exception-handling*
4646
4647The Vim script language comprises an exception handling feature. This section
4648explains how it can be used in a Vim script.
4649
4650Exceptions may be raised by Vim on an error or on interrupt, see
4651|catch-errors| and |catch-interrupt|. You can also explicitly throw an
4652exception by using the ":throw" command, see |throw-catch|.
4653
4654
4655TRY CONDITIONALS *try-conditionals*
4656
4657Exceptions can be caught or can cause cleanup code to be executed. You can
4658use a try conditional to specify catch clauses (that catch exceptions) and/or
4659a finally clause (to be executed for cleanup).
4660 A try conditional begins with a |:try| command and ends at the matching
4661|:endtry| command. In between, you can use a |:catch| command to start
4662a catch clause, or a |:finally| command to start a finally clause. There may
4663be none or multiple catch clauses, but there is at most one finally clause,
4664which must not be followed by any catch clauses. The lines before the catch
4665clauses and the finally clause is called a try block. >
4666
4667 :try
4668 : ...
4669 : ... TRY BLOCK
4670 : ...
4671 :catch /{pattern}/
4672 : ...
4673 : ... CATCH CLAUSE
4674 : ...
4675 :catch /{pattern}/
4676 : ...
4677 : ... CATCH CLAUSE
4678 : ...
4679 :finally
4680 : ...
4681 : ... FINALLY CLAUSE
4682 : ...
4683 :endtry
4684
4685The try conditional allows to watch code for exceptions and to take the
4686appropriate actions. Exceptions from the try block may be caught. Exceptions
4687from the try block and also the catch clauses may cause cleanup actions.
4688 When no exception is thrown during execution of the try block, the control
4689is transferred to the finally clause, if present. After its execution, the
4690script continues with the line following the ":endtry".
4691 When an exception occurs during execution of the try block, the remaining
4692lines in the try block are skipped. The exception is matched against the
4693patterns specified as arguments to the ":catch" commands. The catch clause
4694after the first matching ":catch" is taken, other catch clauses are not
4695executed. The catch clause ends when the next ":catch", ":finally", or
4696":endtry" command is reached - whatever is first. Then, the finally clause
4697(if present) is executed. When the ":endtry" is reached, the script execution
4698continues in the following line as usual.
4699 When an exception that does not match any of the patterns specified by the
4700":catch" commands is thrown in the try block, the exception is not caught by
4701that try conditional and none of the catch clauses is executed. Only the
4702finally clause, if present, is taken. The exception pends during execution of
4703the finally clause. It is resumed at the ":endtry", so that commands after
4704the ":endtry" are not executed and the exception might be caught elsewhere,
4705see |try-nesting|.
4706 When during execution of a catch clause another exception is thrown, the
4707remaining lines in that catch clause are not executed. The new exception is
4708not matched against the patterns in any of the ":catch" commands of the same
4709try conditional and none of its catch clauses is taken. If there is, however,
4710a finally clause, it is executed, and the exception pends during its
4711execution. The commands following the ":endtry" are not executed. The new
4712exception might, however, be caught elsewhere, see |try-nesting|.
4713 When during execution of the finally clause (if present) an exception is
4714thrown, the remaining lines in the finally clause are skipped. If the finally
4715clause has been taken because of an exception from the try block or one of the
4716catch clauses, the original (pending) exception is discarded. The commands
4717following the ":endtry" are not executed, and the exception from the finally
4718clause is propagated and can be caught elsewhere, see |try-nesting|.
4719
4720The finally clause is also executed, when a ":break" or ":continue" for
4721a ":while" loop enclosing the complete try conditional is executed from the
4722try block or a catch clause. Or when a ":return" or ":finish" is executed
4723from the try block or a catch clause of a try conditional in a function or
4724sourced script, respectively. The ":break", ":continue", ":return", or
4725":finish" pends during execution of the finally clause and is resumed when the
4726":endtry" is reached. It is, however, discarded when an exception is thrown
4727from the finally clause.
4728 When a ":break" or ":continue" for a ":while" loop enclosing the complete
4729try conditional or when a ":return" or ":finish" is encountered in the finally
4730clause, the rest of the finally clause is skipped, and the ":break",
4731":continue", ":return" or ":finish" is executed as usual. If the finally
4732clause has been taken because of an exception or an earlier ":break",
4733":continue", ":return", or ":finish" from the try block or a catch clause,
4734this pending exception or command is discarded.
4735
4736For examples see |throw-catch| and |try-finally|.
4737
4738
4739NESTING OF TRY CONDITIONALS *try-nesting*
4740
4741Try conditionals can be nested arbitrarily. That is, a complete try
4742conditional can be put into the try block, a catch clause, or the finally
4743clause of another try conditional. If the inner try conditional does not
4744catch an exception thrown in its try block or throws a new exception from one
4745of its catch clauses or its finally clause, the outer try conditional is
4746checked according to the rules above. If the inner try conditional is in the
4747try block of the outer try conditional, its catch clauses are checked, but
4748otherwise only the finally clause is executed. It does not matter for
4749nesting, whether the inner try conditional is directly contained in the outer
4750one, or whether the outer one sources a script or calls a function containing
4751the inner try conditional.
4752
4753When none of the active try conditionals catches an exception, just their
4754finally clauses are executed. Thereafter, the script processing terminates.
4755An error message is displayed in case of an uncaught exception explicitly
4756thrown by a ":throw" command. For uncaught error and interrupt exceptions
4757implicitly raised by Vim, the error message(s) or interrupt message are shown
4758as usual.
4759
4760For examples see |throw-catch|.
4761
4762
4763EXAMINING EXCEPTION HANDLING CODE *except-examine*
4764
4765Exception handling code can get tricky. If you are in doubt what happens, set
4766'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
4767script file. Then you see when an exception is thrown, discarded, caught, or
4768finished. When using a verbosity level of at least 14, things pending in
4769a finally clause are also shown. This information is also given in debug mode
4770(see |debug-scripts|).
4771
4772
4773THROWING AND CATCHING EXCEPTIONS *throw-catch*
4774
4775You can throw any number or string as an exception. Use the |:throw| command
4776and pass the value to be thrown as argument: >
4777 :throw 4711
4778 :throw "string"
4779< *throw-expression*
4780You can also specify an expression argument. The expression is then evaluated
4781first, and the result is thrown: >
4782 :throw 4705 + strlen("string")
4783 :throw strpart("strings", 0, 6)
4784
4785An exception might be thrown during evaluation of the argument of the ":throw"
4786command. Unless it is caught there, the expression evaluation is abandoned.
4787The ":throw" command then does not throw a new exception.
4788 Example: >
4789
4790 :function! Foo(arg)
4791 : try
4792 : throw a:arg
4793 : catch /foo/
4794 : endtry
4795 : return 1
4796 :endfunction
4797 :
4798 :function! Bar()
4799 : echo "in Bar"
4800 : return 4710
4801 :endfunction
4802 :
4803 :throw Foo("arrgh") + Bar()
4804
4805This throws "arrgh", and "in Bar" is not displayed since Bar() is not
4806executed. >
4807 :throw Foo("foo") + Bar()
4808however displays "in Bar" and throws 4711.
4809
4810Any other command that takes an expression as argument might also be
4811abandoned by an (uncaught) exception during the expression evaluation. The
4812exception is then propagated to the caller of the command.
4813 Example: >
4814
4815 :if Foo("arrgh")
4816 : echo "then"
4817 :else
4818 : echo "else"
4819 :endif
4820
4821Here neither of "then" or "else" is displayed.
4822
4823 *catch-order*
4824Exceptions can be caught by a try conditional with one or more |:catch|
4825commands, see |try-conditionals|. The values to be caught by each ":catch"
4826command can be specified as a pattern argument. The subsequent catch clause
4827gets executed when a matching exception is caught.
4828 Example: >
4829
4830 :function! Foo(value)
4831 : try
4832 : throw a:value
4833 : catch /^\d\+$/
4834 : echo "Number thrown"
4835 : catch /.*/
4836 : echo "String thrown"
4837 : endtry
4838 :endfunction
4839 :
4840 :call Foo(0x1267)
4841 :call Foo('string')
4842
4843The first call to Foo() displays "Number thrown", the second "String thrown".
4844An exception is matched against the ":catch" commands in the order they are
4845specified. Only the first match counts. So you should place the more
4846specific ":catch" first. The following order does not make sense: >
4847
4848 : catch /.*/
4849 : echo "String thrown"
4850 : catch /^\d\+$/
4851 : echo "Number thrown"
4852
4853The first ":catch" here matches always, so that the second catch clause is
4854never taken.
4855
4856 *throw-variables*
4857If you catch an exception by a general pattern, you may access the exact value
4858in the variable |v:exception|: >
4859
4860 : catch /^\d\+$/
4861 : echo "Number thrown. Value is" v:exception
4862
4863You may also be interested where an exception was thrown. This is stored in
4864|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
4865exception most recently caught as long it is not finished.
4866 Example: >
4867
4868 :function! Caught()
4869 : if v:exception != ""
4870 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
4871 : else
4872 : echo 'Nothing caught'
4873 : endif
4874 :endfunction
4875 :
4876 :function! Foo()
4877 : try
4878 : try
4879 : try
4880 : throw 4711
4881 : finally
4882 : call Caught()
4883 : endtry
4884 : catch /.*/
4885 : call Caught()
4886 : throw "oops"
4887 : endtry
4888 : catch /.*/
4889 : call Caught()
4890 : finally
4891 : call Caught()
4892 : endtry
4893 :endfunction
4894 :
4895 :call Foo()
4896
4897This displays >
4898
4899 Nothing caught
4900 Caught "4711" in function Foo, line 4
4901 Caught "oops" in function Foo, line 10
4902 Nothing caught
4903
4904A practical example: The following command ":LineNumber" displays the line
4905number in the script or function where it has been used: >
4906
4907 :function! LineNumber()
4908 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
4909 :endfunction
4910 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
4911<
4912 *try-nested*
4913An exception that is not caught by a try conditional can be caught by
4914a surrounding try conditional: >
4915
4916 :try
4917 : try
4918 : throw "foo"
4919 : catch /foobar/
4920 : echo "foobar"
4921 : finally
4922 : echo "inner finally"
4923 : endtry
4924 :catch /foo/
4925 : echo "foo"
4926 :endtry
4927
4928The inner try conditional does not catch the exception, just its finally
4929clause is executed. The exception is then caught by the outer try
4930conditional. The example displays "inner finally" and then "foo".
4931
4932 *throw-from-catch*
4933You can catch an exception and throw a new one to be caught elsewhere from the
4934catch clause: >
4935
4936 :function! Foo()
4937 : throw "foo"
4938 :endfunction
4939 :
4940 :function! Bar()
4941 : try
4942 : call Foo()
4943 : catch /foo/
4944 : echo "Caught foo, throw bar"
4945 : throw "bar"
4946 : endtry
4947 :endfunction
4948 :
4949 :try
4950 : call Bar()
4951 :catch /.*/
4952 : echo "Caught" v:exception
4953 :endtry
4954
4955This displays "Caught foo, throw bar" and then "Caught bar".
4956
4957 *rethrow*
4958There is no real rethrow in the Vim script language, but you may throw
4959"v:exception" instead: >
4960
4961 :function! Bar()
4962 : try
4963 : call Foo()
4964 : catch /.*/
4965 : echo "Rethrow" v:exception
4966 : throw v:exception
4967 : endtry
4968 :endfunction
4969< *try-echoerr*
4970Note that this method cannot be used to "rethrow" Vim error or interrupt
4971exceptions, because it is not possible to fake Vim internal exceptions.
4972Trying so causes an error exception. You should throw your own exception
4973denoting the situation. If you want to cause a Vim error exception containing
4974the original error exception value, you can use the |:echoerr| command: >
4975
4976 :try
4977 : try
4978 : asdf
4979 : catch /.*/
4980 : echoerr v:exception
4981 : endtry
4982 :catch /.*/
4983 : echo v:exception
4984 :endtry
4985
4986This code displays
4987
4988 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
4989
4990
4991CLEANUP CODE *try-finally*
4992
4993Scripts often change global settings and restore them at their end. If the
4994user however interrupts the script by pressing CTRL-C, the settings remain in
4995an inconsistent state. The same may happen to you in the development phase of
4996a script when an error occurs or you explicitly throw an exception without
4997catching it. You can solve these problems by using a try conditional with
4998a finally clause for restoring the settings. Its execution is guaranteed on
4999normal control flow, on error, on an explicit ":throw", and on interrupt.
5000(Note that errors and interrupts from inside the try conditional are converted
5001to exceptions. When not caught, they terminate the script after the finally
5002clause has been executed.)
5003Example: >
5004
5005 :try
5006 : let s:saved_ts = &ts
5007 : set ts=17
5008 :
5009 : " Do the hard work here.
5010 :
5011 :finally
5012 : let &ts = s:saved_ts
5013 : unlet s:saved_ts
5014 :endtry
5015
5016This method should be used locally whenever a function or part of a script
5017changes global settings which need to be restored on failure or normal exit of
5018that function or script part.
5019
5020 *break-finally*
5021Cleanup code works also when the try block or a catch clause is left by
5022a ":continue", ":break", ":return", or ":finish".
5023 Example: >
5024
5025 :let first = 1
5026 :while 1
5027 : try
5028 : if first
5029 : echo "first"
5030 : let first = 0
5031 : continue
5032 : else
5033 : throw "second"
5034 : endif
5035 : catch /.*/
5036 : echo v:exception
5037 : break
5038 : finally
5039 : echo "cleanup"
5040 : endtry
5041 : echo "still in while"
5042 :endwhile
5043 :echo "end"
5044
5045This displays "first", "cleanup", "second", "cleanup", and "end". >
5046
5047 :function! Foo()
5048 : try
5049 : return 4711
5050 : finally
5051 : echo "cleanup\n"
5052 : endtry
5053 : echo "Foo still active"
5054 :endfunction
5055 :
5056 :echo Foo() "returned by Foo"
5057
5058This displays "cleanup" and "4711 returned by Foo". You don't need to add an
5059extra ":return" in the finally clause. (Above all, this would override the
5060return value.)
5061
5062 *except-from-finally*
5063Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
5064a finally clause is possible, but not recommended since it abandons the
5065cleanup actions for the try conditional. But, of course, interrupt and error
5066exceptions might get raised from a finally clause.
5067 Example where an error in the finally clause stops an interrupt from
5068working correctly: >
5069
5070 :try
5071 : try
5072 : echo "Press CTRL-C for interrupt"
5073 : while 1
5074 : endwhile
5075 : finally
5076 : unlet novar
5077 : endtry
5078 :catch /novar/
5079 :endtry
5080 :echo "Script still running"
5081 :sleep 1
5082
5083If you need to put commands that could fail into a finally clause, you should
5084think about catching or ignoring the errors in these commands, see
5085|catch-errors| and |ignore-errors|.
5086
5087
5088CATCHING ERRORS *catch-errors*
5089
5090If you want to catch specific errors, you just have to put the code to be
5091watched in a try block and add a catch clause for the error message. The
5092presence of the try conditional causes all errors to be converted to an
5093exception. No message is displayed and |v:errmsg| is not set then. To find
5094the right pattern for the ":catch" command, you have to know how the format of
5095the error exception is.
5096 Error exceptions have the following format: >
5097
5098 Vim({cmdname}):{errmsg}
5099or >
5100 Vim:{errmsg}
5101
5102{cmdname} is the name of the command that failed; the second form is used when
5103the command name is not known. {errmsg} is the error message usually produced
5104when the error occurs outside try conditionals. It always begins with
5105a capital "E", followed by a two or three-digit error number, a colon, and
5106a space.
5107
5108Examples:
5109
5110The command >
5111 :unlet novar
5112normally produces the error message >
5113 E108: No such variable: "novar"
5114which is converted inside try conditionals to an exception >
5115 Vim(unlet):E108: No such variable: "novar"
5116
5117The command >
5118 :dwim
5119normally produces the error message >
5120 E492: Not an editor command: dwim
5121which is converted inside try conditionals to an exception >
5122 Vim:E492: Not an editor command: dwim
5123
5124You can catch all ":unlet" errors by a >
5125 :catch /^Vim(unlet):/
5126or all errors for misspelled command names by a >
5127 :catch /^Vim:E492:/
5128
5129Some error messages may be produced by different commands: >
5130 :function nofunc
5131and >
5132 :delfunction nofunc
5133both produce the error message >
5134 E128: Function name must start with a capital: nofunc
5135which is converted inside try conditionals to an exception >
5136 Vim(function):E128: Function name must start with a capital: nofunc
5137or >
5138 Vim(delfunction):E128: Function name must start with a capital: nofunc
5139respectively. You can catch the error by its number independently on the
5140command that caused it if you use the following pattern: >
5141 :catch /^Vim(\a\+):E128:/
5142
5143Some commands like >
5144 :let x = novar
5145produce multiple error messages, here: >
5146 E121: Undefined variable: novar
5147 E15: Invalid expression: novar
5148Only the first is used for the exception value, since it is the most specific
5149one (see |except-several-errors|). So you can catch it by >
5150 :catch /^Vim(\a\+):E121:/
5151
5152You can catch all errors related to the name "nofunc" by >
5153 :catch /\<nofunc\>/
5154
5155You can catch all Vim errors in the ":write" and ":read" commands by >
5156 :catch /^Vim(\(write\|read\)):E\d\+:/
5157
5158You can catch all Vim errors by the pattern >
5159 :catch /^Vim\((\a\+)\)\=:E\d\+:/
5160<
5161 *catch-text*
5162NOTE: You should never catch the error message text itself: >
5163 :catch /No such variable/
5164only works in the english locale, but not when the user has selected
5165a different language by the |:language| command. It is however helpful to
5166cite the message text in a comment: >
5167 :catch /^Vim(\a\+):E108:/ " No such variable
5168
5169
5170IGNORING ERRORS *ignore-errors*
5171
5172You can ignore errors in a specific Vim command by catching them locally: >
5173
5174 :try
5175 : write
5176 :catch
5177 :endtry
5178
5179But you are strongly recommended NOT to use this simple form, since it could
5180catch more than you want. With the ":write" command, some autocommands could
5181be executed and cause errors not related to writing, for instance: >
5182
5183 :au BufWritePre * unlet novar
5184
5185There could even be such errors you are not responsible for as a script
5186writer: a user of your script might have defined such autocommands. You would
5187then hide the error from the user.
5188 It is much better to use >
5189
5190 :try
5191 : write
5192 :catch /^Vim(write):/
5193 :endtry
5194
5195which only catches real write errors. So catch only what you'd like to ignore
5196intentionally.
5197
5198For a single command that does not cause execution of autocommands, you could
5199even suppress the conversion of errors to exceptions by the ":silent!"
5200command: >
5201 :silent! nunmap k
5202This works also when a try conditional is active.
5203
5204
5205CATCHING INTERRUPTS *catch-interrupt*
5206
5207When there are active try conditionals, an interrupt (CTRL-C) is converted to
5208the exception "Vim:Interrupt". You can catch it like every exception. The
5209script is not terminated, then.
5210 Example: >
5211
5212 :function! TASK1()
5213 : sleep 10
5214 :endfunction
5215
5216 :function! TASK2()
5217 : sleep 20
5218 :endfunction
5219
5220 :while 1
5221 : let command = input("Type a command: ")
5222 : try
5223 : if command == ""
5224 : continue
5225 : elseif command == "END"
5226 : break
5227 : elseif command == "TASK1"
5228 : call TASK1()
5229 : elseif command == "TASK2"
5230 : call TASK2()
5231 : else
5232 : echo "\nIllegal command:" command
5233 : continue
5234 : endif
5235 : catch /^Vim:Interrupt$/
5236 : echo "\nCommand interrupted"
5237 : " Caught the interrupt. Continue with next prompt.
5238 : endtry
5239 :endwhile
5240
5241You can interrupt a task here by pressing CTRL-C; the script then asks for
5242a new command. If you press CTRL-C at the prompt, the script is terminated.
5243
5244For testing what happens when CTRL-C would be pressed on a specific line in
5245your script, use the debug mode and execute the |>quit| or |>interrupt|
5246command on that line. See |debug-scripts|.
5247
5248
5249CATCHING ALL *catch-all*
5250
5251The commands >
5252
5253 :catch /.*/
5254 :catch //
5255 :catch
5256
5257catch everything, error exceptions, interrupt exceptions and exceptions
5258explicitly thrown by the |:throw| command. This is useful at the top level of
5259a script in order to catch unexpected things.
5260 Example: >
5261
5262 :try
5263 :
5264 : " do the hard work here
5265 :
5266 :catch /MyException/
5267 :
5268 : " handle known problem
5269 :
5270 :catch /^Vim:Interrupt$/
5271 : echo "Script interrupted"
5272 :catch /.*/
5273 : echo "Internal error (" . v:exception . ")"
5274 : echo " - occurred at " . v:throwpoint
5275 :endtry
5276 :" end of script
5277
5278Note: Catching all might catch more things than you want. Thus, you are
5279strongly encouraged to catch only for problems that you can really handle by
5280specifying a pattern argument to the ":catch".
5281 Example: Catching all could make it nearly impossible to interrupt a script
5282by pressing CTRL-C: >
5283
5284 :while 1
5285 : try
5286 : sleep 1
5287 : catch
5288 : endtry
5289 :endwhile
5290
5291
5292EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
5293
5294Exceptions may be used during execution of autocommands. Example: >
5295
5296 :autocmd User x try
5297 :autocmd User x throw "Oops!"
5298 :autocmd User x catch
5299 :autocmd User x echo v:exception
5300 :autocmd User x endtry
5301 :autocmd User x throw "Arrgh!"
5302 :autocmd User x echo "Should not be displayed"
5303 :
5304 :try
5305 : doautocmd User x
5306 :catch
5307 : echo v:exception
5308 :endtry
5309
5310This displays "Oops!" and "Arrgh!".
5311
5312 *except-autocmd-Pre*
5313For some commands, autocommands get executed before the main action of the
5314command takes place. If an exception is thrown and not caught in the sequence
5315of autocommands, the sequence and the command that caused its execution are
5316abandoned and the exception is propagated to the caller of the command.
5317 Example: >
5318
5319 :autocmd BufWritePre * throw "FAIL"
5320 :autocmd BufWritePre * echo "Should not be displayed"
5321 :
5322 :try
5323 : write
5324 :catch
5325 : echo "Caught:" v:exception "from" v:throwpoint
5326 :endtry
5327
5328Here, the ":write" command does not write the file currently being edited (as
5329you can see by checking 'modified'), since the exception from the BufWritePre
5330autocommand abandons the ":write". The exception is then caught and the
5331script displays: >
5332
5333 Caught: FAIL from BufWrite Auto commands for "*"
5334<
5335 *except-autocmd-Post*
5336For some commands, autocommands get executed after the main action of the
5337command has taken place. If this main action fails and the command is inside
5338an active try conditional, the autocommands are skipped and an error exception
5339is thrown that can be caught by the caller of the command.
5340 Example: >
5341
5342 :autocmd BufWritePost * echo "File successfully written!"
5343 :
5344 :try
5345 : write /i/m/p/o/s/s/i/b/l/e
5346 :catch
5347 : echo v:exception
5348 :endtry
5349
5350This just displays: >
5351
5352 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
5353
5354If you really need to execute the autocommands even when the main action
5355fails, trigger the event from the catch clause.
5356 Example: >
5357
5358 :autocmd BufWritePre * set noreadonly
5359 :autocmd BufWritePost * set readonly
5360 :
5361 :try
5362 : write /i/m/p/o/s/s/i/b/l/e
5363 :catch
5364 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
5365 :endtry
5366<
5367You can also use ":silent!": >
5368
5369 :let x = "ok"
5370 :let v:errmsg = ""
5371 :autocmd BufWritePost * if v:errmsg != ""
5372 :autocmd BufWritePost * let x = "after fail"
5373 :autocmd BufWritePost * endif
5374 :try
5375 : silent! write /i/m/p/o/s/s/i/b/l/e
5376 :catch
5377 :endtry
5378 :echo x
5379
5380This displays "after fail".
5381
5382If the main action of the command does not fail, exceptions from the
5383autocommands will be catchable by the caller of the command: >
5384
5385 :autocmd BufWritePost * throw ":-("
5386 :autocmd BufWritePost * echo "Should not be displayed"
5387 :
5388 :try
5389 : write
5390 :catch
5391 : echo v:exception
5392 :endtry
5393<
5394 *except-autocmd-Cmd*
5395For some commands, the normal action can be replaced by a sequence of
5396autocommands. Exceptions from that sequence will be catchable by the caller
5397of the command.
5398 Example: For the ":write" command, the caller cannot know whether the file
5399had actually been written when the exception occurred. You need to tell it in
5400some way. >
5401
5402 :if !exists("cnt")
5403 : let cnt = 0
5404 :
5405 : autocmd BufWriteCmd * if &modified
5406 : autocmd BufWriteCmd * let cnt = cnt + 1
5407 : autocmd BufWriteCmd * if cnt % 3 == 2
5408 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5409 : autocmd BufWriteCmd * endif
5410 : autocmd BufWriteCmd * write | set nomodified
5411 : autocmd BufWriteCmd * if cnt % 3 == 0
5412 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5413 : autocmd BufWriteCmd * endif
5414 : autocmd BufWriteCmd * echo "File successfully written!"
5415 : autocmd BufWriteCmd * endif
5416 :endif
5417 :
5418 :try
5419 : write
5420 :catch /^BufWriteCmdError$/
5421 : if &modified
5422 : echo "Error on writing (file contents not changed)"
5423 : else
5424 : echo "Error after writing"
5425 : endif
5426 :catch /^Vim(write):/
5427 : echo "Error on writing"
5428 :endtry
5429
5430When this script is sourced several times after making changes, it displays
5431first >
5432 File successfully written!
5433then >
5434 Error on writing (file contents not changed)
5435then >
5436 Error after writing
5437etc.
5438
5439 *except-autocmd-ill*
5440You cannot spread a try conditional over autocommands for different events.
5441The following code is ill-formed: >
5442
5443 :autocmd BufWritePre * try
5444 :
5445 :autocmd BufWritePost * catch
5446 :autocmd BufWritePost * echo v:exception
5447 :autocmd BufWritePost * endtry
5448 :
5449 :write
5450
5451
5452EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
5453
5454Some programming languages allow to use hierarchies of exception classes or to
5455pass additional information with the object of an exception class. You can do
5456similar things in Vim.
5457 In order to throw an exception from a hierarchy, just throw the complete
5458class name with the components separated by a colon, for instance throw the
5459string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
5460 When you want to pass additional information with your exception class, add
5461it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
5462for an error when writing "myfile".
5463 With the appropriate patterns in the ":catch" command, you can catch for
5464base classes or derived classes of your hierarchy. Additional information in
5465parentheses can be cut out from |v:exception| with the ":substitute" command.
5466 Example: >
5467
5468 :function! CheckRange(a, func)
5469 : if a:a < 0
5470 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
5471 : endif
5472 :endfunction
5473 :
5474 :function! Add(a, b)
5475 : call CheckRange(a:a, "Add")
5476 : call CheckRange(a:b, "Add")
5477 : let c = a:a + a:b
5478 : if c < 0
5479 : throw "EXCEPT:MATHERR:OVERFLOW"
5480 : endif
5481 : return c
5482 :endfunction
5483 :
5484 :function! Div(a, b)
5485 : call CheckRange(a:a, "Div")
5486 : call CheckRange(a:b, "Div")
5487 : if (a:b == 0)
5488 : throw "EXCEPT:MATHERR:ZERODIV"
5489 : endif
5490 : return a:a / a:b
5491 :endfunction
5492 :
5493 :function! Write(file)
5494 : try
5495 : execute "write" a:file
5496 : catch /^Vim(write):/
5497 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
5498 : endtry
5499 :endfunction
5500 :
5501 :try
5502 :
5503 : " something with arithmetics and I/O
5504 :
5505 :catch /^EXCEPT:MATHERR:RANGE/
5506 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
5507 : echo "Range error in" function
5508 :
5509 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
5510 : echo "Math error"
5511 :
5512 :catch /^EXCEPT:IO/
5513 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
5514 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
5515 : if file !~ '^/'
5516 : let file = dir . "/" . file
5517 : endif
5518 : echo 'I/O error for "' . file . '"'
5519 :
5520 :catch /^EXCEPT/
5521 : echo "Unspecified error"
5522 :
5523 :endtry
5524
5525The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
5526a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
5527exceptions with the "Vim" prefix; they are reserved for Vim.
5528 Vim error exceptions are parameterized with the name of the command that
5529failed, if known. See |catch-errors|.
5530
5531
5532PECULIARITIES
5533 *except-compat*
5534The exception handling concept requires that the command sequence causing the
5535exception is aborted immediately and control is transferred to finally clauses
5536and/or a catch clause.
5537
5538In the Vim script language there are cases where scripts and functions
5539continue after an error: in functions without the "abort" flag or in a command
5540after ":silent!", control flow goes to the following line, and outside
5541functions, control flow goes to the line following the outermost ":endwhile"
5542or ":endif". On the other hand, errors should be catchable as exceptions
5543(thus, requiring the immediate abortion).
5544
5545This problem has been solved by converting errors to exceptions and using
5546immediate abortion (if not suppressed by ":silent!") only when a try
5547conditional is active. This is no restriction since an (error) exception can
5548be caught only from an active try conditional. If you want an immediate
5549termination without catching the error, just use a try conditional without
5550catch clause. (You can cause cleanup code being executed before termination
5551by specifying a finally clause.)
5552
5553When no try conditional is active, the usual abortion and continuation
5554behavior is used instead of immediate abortion. This ensures compatibility of
5555scripts written for Vim 6.1 and earlier.
5556
5557However, when sourcing an existing script that does not use exception handling
5558commands (or when calling one of its functions) from inside an active try
5559conditional of a new script, you might change the control flow of the existing
5560script on error. You get the immediate abortion on error and can catch the
5561error in the new script. If however the sourced script suppresses error
5562messages by using the ":silent!" command (checking for errors by testing
5563|v:errmsg| if appropriate), its execution path is not changed. The error is
5564not converted to an exception. (See |:silent|.) So the only remaining cause
5565where this happens is for scripts that don't care about errors and produce
5566error messages. You probably won't want to use such code from your new
5567scripts.
5568
5569 *except-syntax-err*
5570Syntax errors in the exception handling commands are never caught by any of
5571the ":catch" commands of the try conditional they belong to. Its finally
5572clauses, however, is executed.
5573 Example: >
5574
5575 :try
5576 : try
5577 : throw 4711
5578 : catch /\(/
5579 : echo "in catch with syntax error"
5580 : catch
5581 : echo "inner catch-all"
5582 : finally
5583 : echo "inner finally"
5584 : endtry
5585 :catch
5586 : echo 'outer catch-all caught "' . v:exception . '"'
5587 : finally
5588 : echo "outer finally"
5589 :endtry
5590
5591This displays: >
5592 inner finally
5593 outer catch-all caught "Vim(catch):E54: Unmatched \("
5594 outer finally
5595The original exception is discarded and an error exception is raised, instead.
5596
5597 *except-single-line*
5598The ":try", ":catch", ":finally", and ":endtry" commands can be put on
5599a single line, but then syntax errors may make it difficult to recognize the
5600"catch" line, thus you better avoid this.
5601 Example: >
5602 :try | unlet! foo # | catch | endtry
5603raises an error exception for the trailing characters after the ":unlet!"
5604argument, but does not see the ":catch" and ":endtry" commands, so that the
5605error exception is discarded and the "E488: Trailing characters" message gets
5606displayed.
5607
5608 *except-several-errors*
5609When several errors appear in a single command, the first error message is
5610usually the most specific one and therefor converted to the error exception.
5611 Example: >
5612 echo novar
5613causes >
5614 E121: Undefined variable: novar
5615 E15: Invalid expression: novar
5616The value of the error exception inside try conditionals is: >
5617 Vim(echo):E121: Undefined variable: novar
5618< *except-syntax-error*
5619But when a syntax error is detected after a normal error in the same command,
5620the syntax error is used for the exception being thrown.
5621 Example: >
5622 unlet novar #
5623causes >
5624 E108: No such variable: "novar"
5625 E488: Trailing characters
5626The value of the error exception inside try conditionals is: >
5627 Vim(unlet):E488: Trailing characters
5628This is done because the syntax error might change the execution path in a way
5629not intended by the user. Example: >
5630 try
5631 try | unlet novar # | catch | echo v:exception | endtry
5632 catch /.*/
5633 echo "outer catch:" v:exception
5634 endtry
5635This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
5636a "E600: Missing :endtry" error message is given, see |except-single-line|.
5637
5638==============================================================================
56399. Examples *eval-examples*
5640
5641Printing in Hex ~
5642>
5643 :" The function Nr2Hex() returns the Hex string of a number.
5644 :func Nr2Hex(nr)
5645 : let n = a:nr
5646 : let r = ""
5647 : while n
5648 : let r = '0123456789ABCDEF'[n % 16] . r
5649 : let n = n / 16
5650 : endwhile
5651 : return r
5652 :endfunc
5653
5654 :" The function String2Hex() converts each character in a string to a two
5655 :" character Hex string.
5656 :func String2Hex(str)
5657 : let out = ''
5658 : let ix = 0
5659 : while ix < strlen(a:str)
5660 : let out = out . Nr2Hex(char2nr(a:str[ix]))
5661 : let ix = ix + 1
5662 : endwhile
5663 : return out
5664 :endfunc
5665
5666Example of its use: >
5667 :echo Nr2Hex(32)
5668result: "20" >
5669 :echo String2Hex("32")
5670result: "3332"
5671
5672
5673Sorting lines (by Robert Webb) ~
5674
5675Here is a Vim script to sort lines. Highlight the lines in Vim and type
5676":Sort". This doesn't call any external programs so it'll work on any
5677platform. The function Sort() actually takes the name of a comparison
5678function as its argument, like qsort() does in C. So you could supply it
5679with different comparison functions in order to sort according to date etc.
5680>
5681 :" Function for use with Sort(), to compare two strings.
5682 :func! Strcmp(str1, str2)
5683 : if (a:str1 < a:str2)
5684 : return -1
5685 : elseif (a:str1 > a:str2)
5686 : return 1
5687 : else
5688 : return 0
5689 : endif
5690 :endfunction
5691
5692 :" Sort lines. SortR() is called recursively.
5693 :func! SortR(start, end, cmp)
5694 : if (a:start >= a:end)
5695 : return
5696 : endif
5697 : let partition = a:start - 1
5698 : let middle = partition
5699 : let partStr = getline((a:start + a:end) / 2)
5700 : let i = a:start
5701 : while (i <= a:end)
5702 : let str = getline(i)
5703 : exec "let result = " . a:cmp . "(str, partStr)"
5704 : if (result <= 0)
5705 : " Need to put it before the partition. Swap lines i and partition.
5706 : let partition = partition + 1
5707 : if (result == 0)
5708 : let middle = partition
5709 : endif
5710 : if (i != partition)
5711 : let str2 = getline(partition)
5712 : call setline(i, str2)
5713 : call setline(partition, str)
5714 : endif
5715 : endif
5716 : let i = i + 1
5717 : endwhile
5718
5719 : " Now we have a pointer to the "middle" element, as far as partitioning
5720 : " goes, which could be anywhere before the partition. Make sure it is at
5721 : " the end of the partition.
5722 : if (middle != partition)
5723 : let str = getline(middle)
5724 : let str2 = getline(partition)
5725 : call setline(middle, str2)
5726 : call setline(partition, str)
5727 : endif
5728 : call SortR(a:start, partition - 1, a:cmp)
5729 : call SortR(partition + 1, a:end, a:cmp)
5730 :endfunc
5731
5732 :" To Sort a range of lines, pass the range to Sort() along with the name of a
5733 :" function that will compare two lines.
5734 :func! Sort(cmp) range
5735 : call SortR(a:firstline, a:lastline, a:cmp)
5736 :endfunc
5737
5738 :" :Sort takes a range of lines and sorts them.
5739 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
5740<
5741 *sscanf*
5742There is no sscanf() function in Vim. If you need to extract parts from a
5743line, you can use matchstr() and substitute() to do it. This example shows
5744how to get the file name, line number and column number out of a line like
5745"foobar.txt, 123, 45". >
5746 :" Set up the match bit
5747 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
5748 :"get the part matching the whole expression
5749 :let l = matchstr(line, mx)
5750 :"get each item out of the match
5751 :let file = substitute(l, mx, '\1', '')
5752 :let lnum = substitute(l, mx, '\2', '')
5753 :let col = substitute(l, mx, '\3', '')
5754
5755The input is in the variable "line", the results in the variables "file",
5756"lnum" and "col". (idea from Michael Geddes)
5757
5758==============================================================================
575910. No +eval feature *no-eval-feature*
5760
5761When the |+eval| feature was disabled at compile time, none of the expression
5762evaluation commands are available. To prevent this from causing Vim scripts
5763to generate all kinds of errors, the ":if" and ":endif" commands are still
5764recognized, though the argument of the ":if" and everything between the ":if"
5765and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
5766only if the commands are at the start of the line. The ":else" command is not
5767recognized.
5768
5769Example of how to avoid executing commands when the |+eval| feature is
5770missing: >
5771
5772 :if 1
5773 : echo "Expression evaluation is compiled in"
5774 :else
5775 : echo "You will _never_ see this message"
5776 :endif
5777
5778==============================================================================
577911. The sandbox *eval-sandbox* *sandbox* *E48*
5780
5781The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
5782options are evaluated in a sandbox. This means that you are protected from
5783these expressions having nasty side effects. This gives some safety for when
5784these options are set from a modeline. It is also used when the command from
5785a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005786The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787
5788These items are not allowed in the sandbox:
5789 - changing the buffer text
5790 - defining or changing mapping, autocommands, functions, user commands
5791 - setting certain options (see |option-summary|)
5792 - executing a shell command
5793 - reading or writing a file
5794 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005795This is not guaranteed 100% secure, but it should block most attacks.
5796
5797 *:san* *:sandbox*
5798:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
5799 option that may have been set from a modeline, e.g.
5800 'foldexpr'.
5801
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802
5803 vim:tw=78:ts=8:ft=help:norl: