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