blob: 2b7276b0134079ece6249938fad8b068367dd2c1 [file] [log] [blame]
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Jan 17
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 ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +000038 *E712*
Bram Moolenaar13065c42005-01-08 16:08:21 +000039There 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")
Bram Moolenaar3a3a7232005-01-17 22:16:15 +000083< *E728* *E729* *E730* *E731*
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 Moolenaar3a3a7232005-01-17 22:16:15 +000096 *Funcref* *E695* *E703* *E718*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000097A Funcref variable is obtained with the |function()| function. It can be used
Bram Moolenaar3a3a7232005-01-17 22:16:15 +000098in an expression in the place of a function name, before the parenthesis
99around the arguments, to invoke the function it refers to. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000100
101 :let Fn = function("MyFunc")
102 :echo Fn()
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000103< *E704* *E705* *E707*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000104A Funcref variable must start with a capital, "s:", "w:" or "b:". You cannot
105have both a Funcref variable and a function with the same name.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000106
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000107A special case is defining a function and directly assigning its Funcref to a
108Dictionary entry. Example: >
109 :function dict.init() dict
110 : let self.val = 0
111 :endfunction
112
113The key of the Dictionary can start with a lower case letter. The actual
114function name is not used here. Also see |numbered-function|.
115
116A Funcref can also be used with the |:call| command: >
117 :call Fn()
118 :call dict.init()
Bram Moolenaar13065c42005-01-08 16:08:21 +0000119
120The name of the referenced function can be obtained with |string()|. >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000121 :let func = string(Myfunc)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000122
123You can use |call()| to invoke a Funcref and use a list variable for the
124arguments: >
125 :let r = call(Myfunc, mylist)
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000126
127
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001281.3 Lists ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000129 *List* *E686*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000130A List is an ordered sequence of items. An item can be of any type. Items
131can be accessed by their index number. Items can be added and removed at any
132position in the sequence.
133
Bram Moolenaar13065c42005-01-08 16:08:21 +0000134
135List creation ~
136 *E696* *E697*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000137A List is created with a comma separated list of items in square brackets.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000138Examples: >
139 :let mylist = [1, two, 3, "four"]
140 :let emptylist = []
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000141
142An item can be any expression. Using a List for an item creates a
Bram Moolenaar13065c42005-01-08 16:08:21 +0000143nested List: >
144 :let nestlist = [[11, 12], [21, 22], [31, 32]]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000145
146An extra comma after the last item is ignored.
147
Bram Moolenaar13065c42005-01-08 16:08:21 +0000148
149List index ~
150 *list-index* *E684*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000151An item in the List can be accessed by putting the index in square brackets
Bram Moolenaar13065c42005-01-08 16:08:21 +0000152after the List. Indexes are zero-based, thus the first item has index zero. >
153 :let item = mylist[0] " get the first item: 1
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000154 :let item = mylist[2] " get the third item: 3
Bram Moolenaar13065c42005-01-08 16:08:21 +0000155
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000156When the resulting item is a list this can be repeated: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000157 :let item = nestlist[0][1] " get the first list, second item: 12
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000158<
Bram Moolenaar13065c42005-01-08 16:08:21 +0000159A negative index is counted from the end. Index -1 refers to the last item in
160the List, -2 to the last but one item, etc. >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000161 :let last = mylist[-1] " get the last item: "four"
162
Bram Moolenaar13065c42005-01-08 16:08:21 +0000163To avoid an error for an invalid index use the |get()| function. When an item
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000164is not available it returns zero or the default value you specify: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000165 :echo get(mylist, idx)
166 :echo get(mylist, idx, "NONE")
167
168
169List concatenation ~
170
171Two lists can be concatenated with the "+" operator: >
172 :let longlist = mylist + [5, 6]
173
174To prepend or append an item turn the item into a list by putting [] around
175it. To change a list in-place see |list-modification| below.
176
177
178Sublist ~
179
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000180A part of the List can be obtained by specifying the first and last index,
181separated by a colon in square brackets: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000182 :let shortlist = mylist[2:-1] " get List [3, "four"]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000183
184Omitting the first index is similar to zero. Omitting the last index is
185similar to -1. The difference is that there is no error if the items are not
186available. >
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000187 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
188 :let shortlist = mylist[2:2] " List with one item: [3]
189 :let otherlist = mylist[:] " make a copy of the List
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000190
Bram Moolenaard8b02732005-01-14 21:48:43 +0000191The second index can be just before the first index. In that case the result
192is an empty list. If the second index is lower, this results in an error. >
193 :echo mylist[2:1] " result: []
194 :echo mylist[2:0] " error!
195
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000196
Bram Moolenaar13065c42005-01-08 16:08:21 +0000197List identity ~
Bram Moolenaard8b02732005-01-14 21:48:43 +0000198 *list-identity*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000199When variable "aa" is a list and you assign it to another variable "bb", both
200variables refer to the same list. Thus changing the list "aa" will also
201change "bb": >
202 :let aa = [1, 2, 3]
203 :let bb = aa
204 :call add(aa, 4)
205 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000206< [1, 2, 3, 4]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000207
208Making a copy of a list is done with the |copy()| function. Using [:] also
209works, as explained above. This creates a shallow copy of the list: Changing
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000210a list item in the list will also change the item in the copied list: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000211 :let aa = [[1, 'a'], 2, 3]
212 :let bb = copy(aa)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000213 :call add(aa, 4)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000214 :let aa[0][1] = 'aaa'
215 :echo aa
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000216< [[1, aaa], 2, 3, 4] >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000217 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000218< [[1, aaa], 2, 3]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000219
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000220To make a completely independent list use |deepcopy()|. This also makes a
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000221copy of the values in the list, recursively. Up to a hundred levels deep.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000222
223The operator "is" can be used to check if two variables refer to the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000224List. "isnot" does the opposite. In contrast "==" compares if two lists have
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000225the same value. >
226 :let alist = [1, 2, 3]
227 :let blist = [1, 2, 3]
228 :echo alist is blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000229< 0 >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000230 :echo alist == blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000231< 1
Bram Moolenaar13065c42005-01-08 16:08:21 +0000232
233
234List unpack ~
235
236To unpack the items in a list to individual variables, put the variables in
237square brackets, like list items: >
238 :let [var1, var2] = mylist
239
240When the number of variables does not match the number of items in the list
241this produces an error. To handle any extra items from the list append ";"
242and a variable name: >
243 :let [var1, var2; rest] = mylist
244
245This works like: >
246 :let var1 = mylist[0]
247 :let var2 = mylist[1]
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000248 :let rest = mylist[2:]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000249
250Except that there is no error if there are only two items. "rest" will be an
251empty list then.
252
253
254List modification ~
255 *list-modification*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000256To change a specific item of a list use |:let| this way: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000257 :let list[4] = "four"
258 :let listlist[0][3] = item
259
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000260To change part of a list you can specify the first and last item to be
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000261modified. The value must at least have the number of items in the range: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000262 :let list[3:5] = [3, 4, 5]
263
Bram Moolenaar13065c42005-01-08 16:08:21 +0000264Adding and removing items from a list is done with functions. Here are a few
265examples: >
266 :call insert(list, 'a') " prepend item 'a'
267 :call insert(list, 'a', 3) " insert item 'a' before list[3]
268 :call add(list, "new") " append String item
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000269 :call add(list, [1, 2]) " append a List as one new item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000270 :call extend(list, [1, 2]) " extend the list with two more items
271 :let i = remove(list, 3) " remove item 3
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000272 :unlet list[3] " idem
Bram Moolenaar13065c42005-01-08 16:08:21 +0000273 :let l = remove(list, 3, -1) " remove items 3 to last item
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000274 :unlet list[3 : ] " idem
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000275 :call filter(list, 'v:val !~ "x"') " remove items with an 'x'
Bram Moolenaar13065c42005-01-08 16:08:21 +0000276
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000277Changing the order of items in a list: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000278 :call sort(list) " sort a list alphabetically
279 :call reverse(list) " reverse the order of items
280
Bram Moolenaar13065c42005-01-08 16:08:21 +0000281
282For loop ~
283
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000284The |:for| loop executes commands for each item in a list. A variable is set
285to each item in the list in sequence. Example: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000286 :for item in mylist
287 : call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000288 :endfor
289
290This works like: >
291 :let index = 0
292 :while index < len(mylist)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000293 : let item = mylist[index]
294 : :call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000295 : let index = index + 1
296 :endwhile
297
298Note that all items in the list should be of the same type, otherwise this
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000299results in error |E706|. To avoid this |:unlet| the variable at the end of
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000300the loop.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000301
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000302If all you want to do is modify each item in the list then the |map()|
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000303function will be a simpler method than a for loop.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000304
Bram Moolenaar13065c42005-01-08 16:08:21 +0000305Just like the |:let| command, |:for| also accepts a list of variables. This
306requires the argument to be a list of lists. >
307 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
308 : call Doit(lnum, col)
309 :endfor
310
311This works like a |:let| command is done for each list item. Again, the types
312must remain the same to avoid an error.
313
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000314It is also possible to put remaining items in a List variable: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000315 :for [i, j; rest] in listlist
316 : call Doit(i, j)
317 : if !empty(rest)
318 : echo "remainder: " . string(rest)
319 : endif
320 :endfor
321
322
323List functions ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000324 *E714*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000325Functions that are useful with a List: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000326 :let r = call(funcname, list) " call a function with an argument list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000327 :if empty(list) " check if list is empty
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000328 :let l = len(list) " number of items in list
329 :let big = max(list) " maximum value in list
330 :let small = min(list) " minimum value in list
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000331 :let xs = count(list, 'x') " count nr of times 'x' appears in list
332 :let i = index(list, 'x') " index of first 'x' in list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000333 :let lines = getline(1, 10) " get ten text lines from buffer
334 :call append('$', lines) " append text lines in buffer
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000335 :let list = split("a b c") " create list from items in a string
336 :let string = join(list, ', ') " create string from list items
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000337 :let s = string(list) " String representation of list
338 :call map(list, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000339
340
Bram Moolenaard8b02732005-01-14 21:48:43 +00003411.4 Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000342 *Dictionaries* *Dictionary*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000343A Dictionary is an associative array: Each entry has a key and a value. The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000344entry can be located with the key. The entries are stored without a specific
345ordering.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000346
347
348Dictionary creation ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000349 *E720* *E721* *E722* *E723*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000350A Dictionary is created with a comma separated list of entries in curly
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000351braces. Each entry has a key and a value, separated by a colon. Each key can
352only appear once. Examples: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000353 :let mydict = {1: 'one', 2: 'two', 3: 'three'}
354 :let emptydict = {}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000355< *E713* *E716* *E717*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000356A key is always a String. You can use a Number, it will be converted to a
357String automatically. Thus the String '4' and the number 4 will find the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000358entry. Note that the String '04' and the Number 04 are different, since the
359Number will be converted to the String '4'.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000360
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000361A value can be any expression. Using a Dictionary for a value creates a
Bram Moolenaard8b02732005-01-14 21:48:43 +0000362nested Dictionary: >
363 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
364
365An extra comma after the last entry is ignored.
366
367
368Accessing entries ~
369
370The normal way to access an entry is by putting the key in square brackets: >
371 :let val = mydict["one"]
372 :let mydict["four"] = 4
373
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000374You can add new entries to an existing Dictionary this way, unlike Lists.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000375
376For keys that consist entirely of letters, digits and underscore the following
377form can be used |expr-entry|: >
378 :let val = mydict.one
379 :let mydict.four = 4
380
381Since an entry can be any type, also a List and a Dictionary, the indexing and
382key lookup can be repeated: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000383 :echo dict.key[idx].key
Bram Moolenaard8b02732005-01-14 21:48:43 +0000384
385
386Dictionary to List conversion ~
387
388You may want to loop over the entries in a dictionary. For this you need to
389turn the Dictionary into a List and pass it to |:for|.
390
391Most often you want to loop over the keys, using the |keys()| function: >
392 :for key in keys(mydict)
393 : echo key . ': ' . mydict[key]
394 :endfor
395
396The List of keys is unsorted. You may want to sort them first: >
397 :for key in sort(keys(mydict))
398
399To loop over the values use the |values()| function: >
400 :for v in values(mydict)
401 : echo "value: " . v
402 :endfor
403
404If you want both the key and the value use the |items()| function. It returns
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000405a List in which each item is a List with two items, the key and the value: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000406 :for entry in items(mydict)
407 : echo entry[0] . ': ' . entry[1]
408 :endfor
409
410
411Dictionary identity ~
412
413Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
414Dictionary. Otherwise, assignment results in referring to the same
415Dictionary: >
416 :let onedict = {'a': 1, 'b': 2}
417 :let adict = onedict
418 :let adict['a'] = 11
419 :echo onedict['a']
420 11
421
422For more info see |list-identity|.
423
424
425Dictionary modification ~
426 *dict-modification*
427To change an already existing entry of a Dictionary, or to add a new entry,
428use |:let| this way: >
429 :let dict[4] = "four"
430 :let dict['one'] = item
431
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000432Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
433Three ways to remove the entry with key "aaa" from dict: >
434 :let i = remove(dict, 'aaa')
435 :unlet dict.aaa
436 :unlet dict['aaa']
Bram Moolenaard8b02732005-01-14 21:48:43 +0000437
438Merging a Dictionary with another is done with |extend()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000439 :call extend(adict, bdict)
440This extends adict with all entries from bdict. Duplicate keys cause entries
441in adict to be overwritten. An optional third argument can change this.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000442
443Weeding out entries from a Dictionary can be done with |filter()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000444 :call filter(dict 'v:val =~ "x"')
445This removes all entries from "dict" with a value not matching 'x'.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000446
447
448Dictionary function ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000449 *Dictionary-function* *self* *E725*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000450When a function is defined with the "dict" attribute it can be used in a
451special way with a dictionary. Example: >
452 :function Mylen() dict
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000453 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000454 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000455 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
456 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000457
458This is like a method in object oriented programming. The entry in the
459Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
460the function was invoked from.
461
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000462It is also possible to add a function without the "dict" attribute as a
463Funcref to a Dictionary, but the "self" variable is not available then.
464
465 *numbered-function*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000466To avoid the extra name for the function it can be defined and directly
467assigned to a Dictionary in this way: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000468 :let mydict = {'data': [0, 1, 2, 3]}
469 :function mydict.len() dict
470 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000471 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000472 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000473
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000474The function will then get a number and the value of dict.len is a |Funcref|
475that references this function. The function can only be used through a
476|Funcref|. It will automatically be deleted when there is no |Funcref|
477remaining that refers to it.
478
479It is not necessary to use the "dict" attribute for a numbered function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000480
481
482Functions for Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000483 *E715*
484Functions that can be used with a Dictionary: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000485 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
486 :if empty(dict) " TRUE if dict is empty
487 :let l = len(dict) " number of items in dict
488 :let big = max(dict) " maximum value in dict
489 :let small = min(dict) " minimum value in dict
490 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
491 :let s = string(dict) " String representation of dict
492 :call map(dict, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaard8b02732005-01-14 21:48:43 +0000493
494
4951.5 More about variables ~
Bram Moolenaar13065c42005-01-08 16:08:21 +0000496 *more-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497If you need to know the type of a variable or expression, use the |type()|
498function.
499
500When the '!' flag is included in the 'viminfo' option, global variables that
501start with an uppercase letter, and don't contain a lowercase letter, are
502stored in the viminfo file |viminfo-file|.
503
504When the 'sessionoptions' option contains "global", global variables that
505start with an uppercase letter and contain at least one lowercase letter are
506stored in the session file |session-file|.
507
508variable name can be stored where ~
509my_var_6 not
510My_Var_6 session file
511MY_VAR_6 viminfo file
512
513
514It's possible to form a variable name with curly braces, see
515|curly-braces-names|.
516
517==============================================================================
5182. Expression syntax *expression-syntax*
519
520Expression syntax summary, from least to most significant:
521
522|expr1| expr2 ? expr1 : expr1 if-then-else
523
524|expr2| expr3 || expr3 .. logical OR
525
526|expr3| expr4 && expr4 .. logical AND
527
528|expr4| expr5 == expr5 equal
529 expr5 != expr5 not equal
530 expr5 > expr5 greater than
531 expr5 >= expr5 greater than or equal
532 expr5 < expr5 smaller than
533 expr5 <= expr5 smaller than or equal
534 expr5 =~ expr5 regexp matches
535 expr5 !~ expr5 regexp doesn't match
536
537 expr5 ==? expr5 equal, ignoring case
538 expr5 ==# expr5 equal, match case
539 etc. As above, append ? for ignoring case, # for
540 matching case
541
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000542 expr5 is expr5 same List instance
543 expr5 isnot expr5 different List instance
544
545|expr5| expr6 + expr6 .. number addition or list concatenation
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 expr6 - expr6 .. number subtraction
547 expr6 . expr6 .. string concatenation
548
549|expr6| expr7 * expr7 .. number multiplication
550 expr7 / expr7 .. number division
551 expr7 % expr7 .. number modulo
552
553|expr7| ! expr7 logical NOT
554 - expr7 unary minus
555 + expr7 unary plus
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000558|expr8| expr8[expr1] byte of a String or item of a List
559 expr8[expr1 : expr1] substring of a String or sublist of a List
560 expr8.name entry in a Dictionary
561 expr8(expr1, ...) function call with Funcref variable
562
563|expr9| number number constant
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000564 "string" string constant, backslash is special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000565 'string' string constant, ' is doubled
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000566 [expr1, ...] List
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000567 {expr1: expr1, ...} Dictionary
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568 &option option value
569 (expr1) nested expression
570 variable internal variable
571 va{ria}ble internal variable with curly braces
572 $VAR environment variable
573 @r contents of register 'r'
574 function(expr1, ...) function call
575 func{ti}on(expr1, ...) function call with curly braces
576
577
578".." indicates that the operations in this level can be concatenated.
579Example: >
580 &nu || &list && &shell == "csh"
581
582All expressions within one level are parsed from left to right.
583
584
585expr1 *expr1* *E109*
586-----
587
588expr2 ? expr1 : expr1
589
590The expression before the '?' is evaluated to a number. If it evaluates to
591non-zero, the result is the value of the expression between the '?' and ':',
592otherwise the result is the value of the expression after the ':'.
593Example: >
594 :echo lnum == 1 ? "top" : lnum
595
596Since the first expression is an "expr2", it cannot contain another ?:. The
597other two expressions can, thus allow for recursive use of ?:.
598Example: >
599 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
600
601To keep this readable, using |line-continuation| is suggested: >
602 :echo lnum == 1
603 :\ ? "top"
604 :\ : lnum == 1000
605 :\ ? "last"
606 :\ : lnum
607
608
609expr2 and expr3 *expr2* *expr3*
610---------------
611
612 *expr-barbar* *expr-&&*
613The "||" and "&&" operators take one argument on each side. The arguments
614are (converted to) Numbers. The result is:
615
616 input output ~
617n1 n2 n1 || n2 n1 && n2 ~
618zero zero zero zero
619zero non-zero non-zero zero
620non-zero zero non-zero zero
621non-zero non-zero non-zero non-zero
622
623The operators can be concatenated, for example: >
624
625 &nu || &list && &shell == "csh"
626
627Note that "&&" takes precedence over "||", so this has the meaning of: >
628
629 &nu || (&list && &shell == "csh")
630
631Once the result is known, the expression "short-circuits", that is, further
632arguments are not evaluated. This is like what happens in C. For example: >
633
634 let a = 1
635 echo a || b
636
637This is valid even if there is no variable called "b" because "a" is non-zero,
638so the result must be non-zero. Similarly below: >
639
640 echo exists("b") && b == "yes"
641
642This is valid whether "b" has been defined or not. The second clause will
643only be evaluated if "b" has been defined.
644
645
646expr4 *expr4*
647-----
648
649expr5 {cmp} expr5
650
651Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
652if it evaluates to true.
653
654 *expr-==* *expr-!=* *expr->* *expr->=*
655 *expr-<* *expr-<=* *expr-=~* *expr-!~*
656 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
657 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
658 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
659 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000660 *expr-is*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661 use 'ignorecase' match case ignore case ~
662equal == ==# ==?
663not equal != !=# !=?
664greater than > ># >?
665greater than or equal >= >=# >=?
666smaller than < <# <?
667smaller than or equal <= <=# <=?
668regexp matches =~ =~# =~?
669regexp doesn't match !~ !~# !~?
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000670same instance is
671different instance isnot
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672
673Examples:
674"abc" ==# "Abc" evaluates to 0
675"abc" ==? "Abc" evaluates to 1
676"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
677
Bram Moolenaar13065c42005-01-08 16:08:21 +0000678 *E691* *E692*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000679A List can only be compared with a List and only "equal", "not equal" and "is"
680can be used. This compares the values of the list, recursively. Ignoring
681case means case is ignored when comparing item values.
682
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000683 *E735* *E736*
684A Dictionary can only be compared with a Dictionary and only "equal", "not
685equal" and "is" can be used. This compares the key/values of the Dictionary,
686recursively. Ignoring case means case is ignored when comparing item values.
687
Bram Moolenaar13065c42005-01-08 16:08:21 +0000688 *E693* *E694*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000689A Funcref can only be compared with a Funcref and only "equal" and "not equal"
690can be used. Case is never ignored.
691
692When using "is" or "isnot" with a List this checks if the expressions are
693referring to the same List instance. A copy of a List is different from the
694original List. When using "is" without a List it is equivalent to using
695"equal", using "isnot" equivalent to using "not equal". Except that a
696different type means the values are different. "4 == '4'" is true, "4 is '4'"
697is false.
698
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699When comparing a String with a Number, the String is converted to a Number,
700and the comparison is done on Numbers. This means that "0 == 'x'" is TRUE,
701because 'x' converted to a Number is zero.
702
703When comparing two Strings, this is done with strcmp() or stricmp(). This
704results in the mathematical difference (comparing byte values), not
705necessarily the alphabetical difference in the local language.
706
707When using the operators with a trailing '#", or the short version and
708'ignorecase' is off, the comparing is done with strcmp().
709
710When using the operators with a trailing '?', or the short version and
711'ignorecase' is set, the comparing is done with stricmp().
712
713The "=~" and "!~" operators match the lefthand argument with the righthand
714argument, which is used as a pattern. See |pattern| for what a pattern is.
715This matching is always done like 'magic' was set and 'cpoptions' is empty, no
716matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
717portable. To avoid backslashes in the regexp pattern to be doubled, use a
718single-quote string, see |literal-string|.
719Since a string is considered to be a single line, a multi-line pattern
720(containing \n, backslash-n) will not match. However, a literal NL character
721can be matched like an ordinary character. Examples:
722 "foo\nbar" =~ "\n" evaluates to 1
723 "foo\nbar" =~ "\\n" evaluates to 0
724
725
726expr5 and expr6 *expr5* *expr6*
727---------------
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000728expr6 + expr6 .. Number addition or List concatenation *expr-+*
729expr6 - expr6 .. Number subtraction *expr--*
730expr6 . expr6 .. String concatenation *expr-.*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000732For Lists only "+" is possible and then both expr6 must be a list. The result
733is a new list with the two lists Concatenated.
734
735expr7 * expr7 .. number multiplication *expr-star*
736expr7 / expr7 .. number division *expr-/*
737expr7 % expr7 .. number modulo *expr-%*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738
739For all, except ".", Strings are converted to Numbers.
740
741Note the difference between "+" and ".":
742 "123" + "456" = 579
743 "123" . "456" = "123456"
744
745When the righthand side of '/' is zero, the result is 0x7fffffff.
746When the righthand side of '%' is zero, the result is 0.
747
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000748None of these work for Funcrefs.
749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750
751expr7 *expr7*
752-----
753! expr7 logical NOT *expr-!*
754- expr7 unary minus *expr-unary--*
755+ expr7 unary plus *expr-unary-+*
756
757For '!' non-zero becomes zero, zero becomes one.
758For '-' the sign of the number is changed.
759For '+' the number is unchanged.
760
761A String will be converted to a Number first.
762
763These three can be repeated and mixed. Examples:
764 !-1 == 0
765 !!8 == 1
766 --9 == 9
767
768
769expr8 *expr8*
770-----
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000771expr8[expr1] item of String or List *expr-[]* *E111*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000773If expr8 is a Number or String this results in a String that contains the
774expr1'th single byte from expr8. expr8 is used as a String, expr1 as a
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000775Number. Note that this doesn't recognize multi-byte encodings.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000777Index zero gives the first character. This is like it works in C. Careful:
778text column numbers start with one! Example, to get the character under the
779cursor: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780 :let c = getline(line("."))[col(".") - 1]
781
782If the length of the String is less than the index, the result is an empty
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000783String. A negative index always results in an empty string (reason: backwards
784compatibility). Use [-1:] to get the last byte.
785
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000786If expr8 is a List then it results the item at index expr1. See |list-index|
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000787for possible index values. If the index is out of range this results in an
788error. Example: >
789 :let item = mylist[-1] " get last item
790
791Generally, if a List index is equal to or higher than the length of the List,
792or more negative than the length of the List, this results in an error.
793
Bram Moolenaard8b02732005-01-14 21:48:43 +0000794
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000795expr8[expr1a : expr1b] substring or sublist *expr-[:]*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000796
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000797If expr8 is a Number or String this results in the substring with the bytes
798from expr1a to and including expr1b. expr8 is used as a String, expr1a and
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000799expr1b are used as a Number. Note that this doesn't recognize multi-byte
800encodings.
801
802If expr1a is omitted zero is used. If expr1b is omitted the length of the
803string minus one is used.
804
805A negative number can be used to measure from the end of the string. -1 is
806the last character, -2 the last but one, etc.
807
808If an index goes out of range for the string characters are omitted. If
809expr1b is smaller than expr1a the result is an empty string.
810
811Examples: >
812 :let c = name[-1:] " last byte of a string
813 :let c = name[-2:-2] " last but one byte of a string
814 :let s = line(".")[4:] " from the fifth byte to the end
815 :let s = s[:-3] " remove last two bytes
816
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000817If expr8 is a List this results in a new List with the items indicated by the
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000818indexes expr1a and expr1b. This works like with a String, as explained just
819above, except that indexes out of range cause an error. Examples: >
820 :let l = mylist[:3] " first four items
821 :let l = mylist[4:4] " List with one item
822 :let l = mylist[:] " shallow copy of a List
823
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000824Using expr8[expr1] or expr8[expr1a : expr1b] on a Funcref results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825
Bram Moolenaard8b02732005-01-14 21:48:43 +0000826
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000827expr8.name entry in a Dictionary *expr-entry*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000828
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000829If expr8 is a Dictionary and it is followed by a dot, then the following name
830will be used as a key in the Dictionary. This is just like: expr8[name].
Bram Moolenaard8b02732005-01-14 21:48:43 +0000831
832The name must consist of alphanumeric characters, just like a variable name,
833but it may start with a number. Curly braces cannot be used.
834
835There must not be white space before or after the dot.
836
837Examples: >
838 :let dict = {"one": 1, 2: "two"}
839 :echo dict.one
840 :echo dict .2
841
842Note that the dot is also used for String concatenation. To avoid confusion
843always put spaces around the dot for String concatenation.
844
845
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000846expr8(expr1, ...) Funcref function call
847
848When expr8 is a |Funcref| type variable, invoke the function it refers to.
849
850
851
852 *expr9*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853number
854------
855number number constant *expr-number*
856
857Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
858
859
860string *expr-string* *E114*
861------
862"string" string constant *expr-quote*
863
864Note that double quotes are used.
865
866A string constant accepts these special characters:
867\... three-digit octal number (e.g., "\316")
868\.. two-digit octal number (must be followed by non-digit)
869\. one-digit octal number (must be followed by non-digit)
870\x.. byte specified with two hex numbers (e.g., "\x1f")
871\x. byte specified with one hex number (must be followed by non-hex char)
872\X.. same as \x..
873\X. same as \x.
874\u.... character specified with up to 4 hex numbers, stored according to the
875 current value of 'encoding' (e.g., "\u02a4")
876\U.... same as \u....
877\b backspace <BS>
878\e escape <Esc>
879\f formfeed <FF>
880\n newline <NL>
881\r return <CR>
882\t tab <Tab>
883\\ backslash
884\" double quote
885\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W.
886
887Note that "\000" and "\x00" force the end of the string.
888
889
890literal-string *literal-string* *E115*
891---------------
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000892'string' string constant *expr-'*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893
894Note that single quotes are used.
895
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000896This string is taken as it is. No backslashes are removed or have a special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000897meaning. The only exception is that two quotes stand for one quote.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000898
899Single quoted strings are useful for patterns, so that backslashes do not need
900to be doubled. These two commands are equivalent: >
901 if a =~ "\\s*"
902 if a =~ '\s*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
904
905option *expr-option* *E112* *E113*
906------
907&option option value, local value if possible
908&g:option global option value
909&l:option local option value
910
911Examples: >
912 echo "tabstop is " . &tabstop
913 if &insertmode
914
915Any option name can be used here. See |options|. When using the local value
916and there is no buffer-local or window-local value, the global value is used
917anyway.
918
919
920register *expr-register*
921--------
922@r contents of register 'r'
923
924The result is the contents of the named register, as a single string.
925Newlines are inserted where required. To get the contents of the unnamed
926register use @" or @@. The '=' register can not be used here. See
927|registers| for an explanation of the available registers.
928
929
930nesting *expr-nesting* *E110*
931-------
932(expr1) nested expression
933
934
935environment variable *expr-env*
936--------------------
937$VAR environment variable
938
939The String value of any environment variable. When it is not defined, the
940result is an empty string.
941 *expr-env-expand*
942Note that there is a difference between using $VAR directly and using
943expand("$VAR"). Using it directly will only expand environment variables that
944are known inside the current Vim session. Using expand() will first try using
945the environment variables known inside the current Vim session. If that
946fails, a shell will be used to expand the variable. This can be slow, but it
947does expand all variables that the shell knows about. Example: >
948 :echo $version
949 :echo expand("$version")
950The first one probably doesn't echo anything, the second echoes the $version
951variable (if your shell supports it).
952
953
954internal variable *expr-variable*
955-----------------
956variable internal variable
957See below |internal-variables|.
958
959
960function call *expr-function* *E116* *E117* *E118* *E119* *E120*
961-------------
962function(expr1, ...) function call
963See below |functions|.
964
965
966==============================================================================
9673. Internal variable *internal-variables* *E121*
968 *E461*
969An internal variable name can be made up of letters, digits and '_'. But it
970cannot start with a digit. It's also possible to use curly braces, see
971|curly-braces-names|.
972
973An internal variable is created with the ":let" command |:let|.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000974An internal variable is explicitly destroyed with the ":unlet" command
975|:unlet|.
976Using a name that is not an internal variable or refers to a variable that has
977been destroyed results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979There are several name spaces for variables. Which one is to be used is
980specified by what is prepended:
981
982 (nothing) In a function: local to a function; otherwise: global
983|buffer-variable| b: Local to the current buffer.
984|window-variable| w: Local to the current window.
985|global-variable| g: Global.
986|local-variable| l: Local to a function.
987|script-variable| s: Local to a |:source|'ed Vim script.
988|function-argument| a: Function argument (only inside a function).
989|vim-variable| v: Global, predefined by Vim.
990
991 *buffer-variable* *b:var*
992A variable name that is preceded with "b:" is local to the current buffer.
993Thus you can have several "b:foo" variables, one for each buffer.
994This kind of variable is deleted when the buffer is wiped out or deleted with
995|:bdelete|.
996
997One local buffer variable is predefined:
998 *b:changedtick-variable* *changetick*
999b:changedtick The total number of changes to the current buffer. It is
1000 incremented for each change. An undo command is also a change
1001 in this case. This can be used to perform an action only when
1002 the buffer has changed. Example: >
1003 :if my_changedtick != b:changedtick
1004 : let my_changedtick = b:changedtick
1005 : call My_Update()
1006 :endif
1007<
1008 *window-variable* *w:var*
1009A variable name that is preceded with "w:" is local to the current window. It
1010is deleted when the window is closed.
1011
1012 *global-variable* *g:var*
1013Inside functions global variables are accessed with "g:". Omitting this will
1014access a variable local to a function. But "g:" can also be used in any other
1015place if you like.
1016
1017 *local-variable* *l:var*
1018Inside functions local variables are accessed without prepending anything.
1019But you can also prepend "l:" if you like.
1020
1021 *script-variable* *s:var*
1022In a Vim script variables starting with "s:" can be used. They cannot be
1023accessed from outside of the scripts, thus are local to the script.
1024
1025They can be used in:
1026- commands executed while the script is sourced
1027- functions defined in the script
1028- autocommands defined in the script
1029- functions and autocommands defined in functions and autocommands which were
1030 defined in the script (recursively)
1031- user defined commands defined in the script
1032Thus not in:
1033- other scripts sourced from this one
1034- mappings
1035- etc.
1036
1037script variables can be used to avoid conflicts with global variable names.
1038Take this example:
1039
1040 let s:counter = 0
1041 function MyCounter()
1042 let s:counter = s:counter + 1
1043 echo s:counter
1044 endfunction
1045 command Tick call MyCounter()
1046
1047You can now invoke "Tick" from any script, and the "s:counter" variable in
1048that script will not be changed, only the "s:counter" in the script where
1049"Tick" was defined is used.
1050
1051Another example that does the same: >
1052
1053 let s:counter = 0
1054 command Tick let s:counter = s:counter + 1 | echo s:counter
1055
1056When calling a function and invoking a user-defined command, the context for
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001057script variables is set to the script where the function or command was
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058defined.
1059
1060The script variables are also available when a function is defined inside a
1061function that is defined in a script. Example: >
1062
1063 let s:counter = 0
1064 function StartCounting(incr)
1065 if a:incr
1066 function MyCounter()
1067 let s:counter = s:counter + 1
1068 endfunction
1069 else
1070 function MyCounter()
1071 let s:counter = s:counter - 1
1072 endfunction
1073 endif
1074 endfunction
1075
1076This defines the MyCounter() function either for counting up or counting down
1077when calling StartCounting(). It doesn't matter from where StartCounting() is
1078called, the s:counter variable will be accessible in MyCounter().
1079
1080When the same script is sourced again it will use the same script variables.
1081They will remain valid as long as Vim is running. This can be used to
1082maintain a counter: >
1083
1084 if !exists("s:counter")
1085 let s:counter = 1
1086 echo "script executed for the first time"
1087 else
1088 let s:counter = s:counter + 1
1089 echo "script executed " . s:counter . " times now"
1090 endif
1091
1092Note that this means that filetype plugins don't get a different set of script
1093variables for each buffer. Use local buffer variables instead |b:var|.
1094
1095
1096Predefined Vim variables: *vim-variable* *v:var*
1097
1098 *v:charconvert_from* *charconvert_from-variable*
1099v:charconvert_from
1100 The name of the character encoding of a file to be converted.
1101 Only valid while evaluating the 'charconvert' option.
1102
1103 *v:charconvert_to* *charconvert_to-variable*
1104v:charconvert_to
1105 The name of the character encoding of a file after conversion.
1106 Only valid while evaluating the 'charconvert' option.
1107
1108 *v:cmdarg* *cmdarg-variable*
1109v:cmdarg This variable is used for two purposes:
1110 1. The extra arguments given to a file read/write command.
1111 Currently these are "++enc=" and "++ff=". This variable is
1112 set before an autocommand event for a file read/write
1113 command is triggered. There is a leading space to make it
1114 possible to append this variable directly after the
1115 read/write command. Note: The "+cmd" argument isn't
1116 included here, because it will be executed anyway.
1117 2. When printing a PostScript file with ":hardcopy" this is
1118 the argument for the ":hardcopy" command. This can be used
1119 in 'printexpr'.
1120
1121 *v:cmdbang* *cmdbang-variable*
1122v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1123 was used the value is 1, otherwise it is 0. Note that this
1124 can only be used in autocommands. For user commands |<bang>|
1125 can be used.
1126
1127 *v:count* *count-variable*
1128v:count The count given for the last Normal mode command. Can be used
1129 to get the count before a mapping. Read-only. Example: >
1130 :map _x :<C-U>echo "the count is " . v:count<CR>
1131< Note: The <C-U> is required to remove the line range that you
1132 get when typing ':' after a count.
1133 "count" also works, for backwards compatibility.
1134
1135 *v:count1* *count1-variable*
1136v:count1 Just like "v:count", but defaults to one when no count is
1137 used.
1138
1139 *v:ctype* *ctype-variable*
1140v:ctype The current locale setting for characters of the runtime
1141 environment. This allows Vim scripts to be aware of the
1142 current locale encoding. Technical: it's the value of
1143 LC_CTYPE. When not using a locale the value is "C".
1144 This variable can not be set directly, use the |:language|
1145 command.
1146 See |multi-lang|.
1147
1148 *v:dying* *dying-variable*
1149v:dying Normally zero. When a deadly signal is caught it's set to
1150 one. When multiple signals are caught the number increases.
1151 Can be used in an autocommand to check if Vim didn't
1152 terminate normally. {only works on Unix}
1153 Example: >
1154 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
1155<
1156 *v:errmsg* *errmsg-variable*
1157v:errmsg Last given error message. It's allowed to set this variable.
1158 Example: >
1159 :let v:errmsg = ""
1160 :silent! next
1161 :if v:errmsg != ""
1162 : ... handle error
1163< "errmsg" also works, for backwards compatibility.
1164
1165 *v:exception* *exception-variable*
1166v:exception The value of the exception most recently caught and not
1167 finished. See also |v:throwpoint| and |throw-variables|.
1168 Example: >
1169 :try
1170 : throw "oops"
1171 :catch /.*/
1172 : echo "caught" v:exception
1173 :endtry
1174< Output: "caught oops".
1175
1176 *v:fname_in* *fname_in-variable*
1177v:fname_in The name of the input file. Only valid while evaluating:
1178 option used for ~
1179 'charconvert' file to be converted
1180 'diffexpr' original file
1181 'patchexpr' original file
1182 'printexpr' file to be printed
1183
1184 *v:fname_out* *fname_out-variable*
1185v:fname_out The name of the output file. Only valid while
1186 evaluating:
1187 option used for ~
1188 'charconvert' resulting converted file (*)
1189 'diffexpr' output of diff
1190 'patchexpr' resulting patched file
1191 (*) When doing conversion for a write command (e.g., ":w
1192 file") it will be equal to v:fname_in. When doing conversion
1193 for a read command (e.g., ":e file") it will be a temporary
1194 file and different from v:fname_in.
1195
1196 *v:fname_new* *fname_new-variable*
1197v:fname_new The name of the new version of the file. Only valid while
1198 evaluating 'diffexpr'.
1199
1200 *v:fname_diff* *fname_diff-variable*
1201v:fname_diff The name of the diff (patch) file. Only valid while
1202 evaluating 'patchexpr'.
1203
1204 *v:folddashes* *folddashes-variable*
1205v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
1206 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001207 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208
1209 *v:foldlevel* *foldlevel-variable*
1210v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001211 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212
1213 *v:foldend* *foldend-variable*
1214v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001215 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216
1217 *v:foldstart* *foldstart-variable*
1218v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001219 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220
Bram Moolenaar843ee412004-06-30 16:16:41 +00001221 *v:insertmode* *insertmode-variable*
1222v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
1223 events. Values:
1224 i Insert mode
1225 r Replace mode
1226 v Virtual Replace mode
1227
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001228 *v:key* *key-variable*
1229v:key Key of the current item of a Dictionary. Only valid while
1230 evaluating the expression used with |map()| and |filter()|.
1231 Read-only.
1232
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 *v:lang* *lang-variable*
1234v:lang The current locale setting for messages of the runtime
1235 environment. This allows Vim scripts to be aware of the
1236 current language. Technical: it's the value of LC_MESSAGES.
1237 The value is system dependent.
1238 This variable can not be set directly, use the |:language|
1239 command.
1240 It can be different from |v:ctype| when messages are desired
1241 in a different language than what is used for character
1242 encoding. See |multi-lang|.
1243
1244 *v:lc_time* *lc_time-variable*
1245v:lc_time The current locale setting for time messages of the runtime
1246 environment. This allows Vim scripts to be aware of the
1247 current language. Technical: it's the value of LC_TIME.
1248 This variable can not be set directly, use the |:language|
1249 command. See |multi-lang|.
1250
1251 *v:lnum* *lnum-variable*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001252v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr'
1253 expressions. Only valid while one of these expressions is
1254 being evaluated. Read-only when in the |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255
1256 *v:prevcount* *prevcount-variable*
1257v:prevcount The count given for the last but one Normal mode command.
1258 This is the v:count value of the previous command. Useful if
1259 you want to cancel Visual mode and then use the count. >
1260 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
1261< Read-only.
1262
1263 *v:progname* *progname-variable*
1264v:progname Contains the name (with path removed) with which Vim was
1265 invoked. Allows you to do special initialisations for "view",
1266 "evim" etc., or any other name you might symlink to Vim.
1267 Read-only.
1268
1269 *v:register* *register-variable*
1270v:register The name of the register supplied to the last normal mode
1271 command. Empty if none were supplied. |getreg()| |setreg()|
1272
1273 *v:servername* *servername-variable*
1274v:servername The resulting registered |x11-clientserver| name if any.
1275 Read-only.
1276
1277 *v:shell_error* *shell_error-variable*
1278v:shell_error Result of the last shell command. When non-zero, the last
1279 shell command had an error. When zero, there was no problem.
1280 This only works when the shell returns the error code to Vim.
1281 The value -1 is often used when the command could not be
1282 executed. Read-only.
1283 Example: >
1284 :!mv foo bar
1285 :if v:shell_error
1286 : echo 'could not rename "foo" to "bar"!'
1287 :endif
1288< "shell_error" also works, for backwards compatibility.
1289
1290 *v:statusmsg* *statusmsg-variable*
1291v:statusmsg Last given status message. It's allowed to set this variable.
1292
1293 *v:termresponse* *termresponse-variable*
1294v:termresponse The escape sequence returned by the terminal for the |t_RV|
1295 termcap entry. It is set when Vim receives an escape sequence
1296 that starts with ESC [ or CSI and ends in a 'c', with only
1297 digits, ';' and '.' in between.
1298 When this option is set, the TermResponse autocommand event is
1299 fired, so that you can react to the response from the
1300 terminal.
1301 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
1302 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
1303 patch level (since this was introduced in patch 95, it's
1304 always 95 or bigger). Pc is always zero.
1305 {only when compiled with |+termresponse| feature}
1306
1307 *v:this_session* *this_session-variable*
1308v:this_session Full filename of the last loaded or saved session file. See
1309 |:mksession|. It is allowed to set this variable. When no
1310 session file has been saved, this variable is empty.
1311 "this_session" also works, for backwards compatibility.
1312
1313 *v:throwpoint* *throwpoint-variable*
1314v:throwpoint The point where the exception most recently caught and not
1315 finished was thrown. Not set when commands are typed. See
1316 also |v:exception| and |throw-variables|.
1317 Example: >
1318 :try
1319 : throw "oops"
1320 :catch /.*/
1321 : echo "Exception from" v:throwpoint
1322 :endtry
1323< Output: "Exception from test.vim, line 2"
1324
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001325 *v:val* *val-variable*
1326v:val Value of the current item of a List or Dictionary. Only valid
1327 while evaluating the expression used with |map()| and
1328 |filter()|. Read-only.
1329
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330 *v:version* *version-variable*
1331v:version Version number of Vim: Major version number times 100 plus
1332 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
1333 is 501. Read-only. "version" also works, for backwards
1334 compatibility.
1335 Use |has()| to check if a certain patch was included, e.g.: >
1336 if has("patch123")
1337< Note that patch numbers are specific to the version, thus both
1338 version 5.0 and 5.1 may have a patch 123, but these are
1339 completely different.
1340
1341 *v:warningmsg* *warningmsg-variable*
1342v:warningmsg Last given warning message. It's allowed to set this variable.
1343
1344==============================================================================
13454. Builtin Functions *functions*
1346
1347See |function-list| for a list grouped by what the function is used for.
1348
1349(Use CTRL-] on the function name to jump to the full explanation)
1350
1351USAGE RESULT DESCRIPTION ~
1352
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001353add( {list}, {item}) List append {item} to List {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001354append( {lnum}, {string}) Number append {string} below line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355argc() Number number of files in the argument list
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001356argidx() Number current index in the argument list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357argv( {nr}) String {nr} entry of the argument list
1358browse( {save}, {title}, {initdir}, {default})
1359 String put up a file requester
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001360browsedir( {title}, {initdir}) String put up a directory requester
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361bufexists( {expr}) Number TRUE if buffer {expr} exists
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001362buflisted( {expr}) Number TRUE if buffer {expr} is listed
1363bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364bufname( {expr}) String Name of the buffer {expr}
1365bufnr( {expr}) Number Number of the buffer {expr}
1366bufwinnr( {expr}) Number window number of buffer {expr}
1367byte2line( {byte}) Number line number at byte count {byte}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001368byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001369call( {func}, {arglist} [, {dict}])
1370 any call {func} with arguments {arglist}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371char2nr( {expr}) Number ASCII value of first char in {expr}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001372cindent( {lnum}) Number C indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373col( {expr}) Number column nr of cursor or mark
1374confirm( {msg} [, {choices} [, {default} [, {type}]]])
1375 Number number of choice picked by user
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001376copy( {expr}) any make a shallow copy of {expr}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001377count( {list}, {expr} [, {start} [, {ic}]])
1378 Number count how many {expr} are in {list}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379cscope_connection( [{num} , {dbpath} [, {prepend}]])
1380 Number checks existence of cscope connection
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001381cursor( {lnum}, {col}) Number position cursor at {lnum}, {col}
1382deepcopy( {expr}) any make a full copy of {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383delete( {fname}) Number delete file {fname}
1384did_filetype() Number TRUE if FileType autocommand event used
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001385diff_filler( {lnum}) Number diff filler lines about {lnum}
1386diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
Bram Moolenaar13065c42005-01-08 16:08:21 +00001387empty( {expr}) Number TRUE if {expr} is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388escape( {string}, {chars}) String escape {chars} in {string} with '\'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001389eval( {string}) any evaluate {string} into its value
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001390eventhandler( ) Number TRUE if inside an event handler
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391executable( {expr}) Number 1 if executable {expr} exists
1392exists( {expr}) Number TRUE if {expr} exists
1393expand( {expr}) String expand special keywords in {expr}
1394filereadable( {file}) Number TRUE if {file} is a readable file
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001395filter( {expr}, {string}) List/Dict remove items from {expr} where
1396 {string} is 0
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001397finddir( {name}[, {path}[, {count}]])
1398 String Find directory {name} in {path}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001399findfile( {name}[, {path}[, {count}]])
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001400 String Find file {name} in {path}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401filewritable( {file}) Number TRUE if {file} is a writable file
1402fnamemodify( {fname}, {mods}) String modify file name
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001403foldclosed( {lnum}) Number first line of fold at {lnum} if closed
1404foldclosedend( {lnum}) Number last line of fold at {lnum} if closed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405foldlevel( {lnum}) Number fold level at {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001406foldtext( ) String line displayed for closed fold
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407foreground( ) Number bring the Vim window to the foreground
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001408function( {name}) Funcref reference to function {name}
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001409get( {list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001410get( {dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001411getchar( [expr]) Number get one character from the user
1412getcharmod( ) Number modifiers for the last typed character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413getbufvar( {expr}, {varname}) variable {varname} in buffer {expr}
1414getcmdline() String return the current command-line
1415getcmdpos() Number return cursor position in command-line
1416getcwd() String the current working directory
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001417getfperm( {fname}) String file permissions of file {fname}
1418getfsize( {fname}) Number size in bytes of file {fname}
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001419getfontname( [{name}]) String name of font being used
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420getftime( {fname}) Number last modification time of file
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001421getftype( {fname}) String description of type of file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422getline( {lnum}) String line {lnum} from current buffer
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001423getreg( [{regname}]) String contents of register
1424getregtype( [{regname}]) String type of register
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425getwinposx() Number X coord in pixels of GUI Vim window
1426getwinposy() Number Y coord in pixels of GUI Vim window
1427getwinvar( {nr}, {varname}) variable {varname} in window {nr}
1428glob( {expr}) String expand file wildcards in {expr}
1429globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path}
1430has( {feature}) Number TRUE if feature {feature} supported
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001431has_key( {dict}, {key}) Number TRUE if {dict} has entry {key}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists
1433histadd( {history},{item}) String add an item to a history
1434histdel( {history} [, {item}]) String remove an item from a history
1435histget( {history} [, {index}]) String get the item {index} from a history
1436histnr( {history}) Number highest index of a history
1437hlexists( {name}) Number TRUE if highlight group {name} exists
1438hlID( {name}) Number syntax ID of highlight group {name}
1439hostname() String name of the machine Vim is running on
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001440iconv( {expr}, {from}, {to}) String convert encoding of {expr}
1441indent( {lnum}) Number indent of line {lnum}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001442index( {list}, {expr} [, {start} [, {ic}]])
1443 Number index in {list} where {expr} appears
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444input( {prompt} [, {text}]) String get input from the user
1445inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001446inputrestore() Number restore typeahead
1447inputsave() Number save and clear typeahead
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448inputsecret( {prompt} [, {text}]) String like input() but hiding the text
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001449insert( {list}, {item} [, {idx}]) List insert {item} in {list} [before {idx}]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450isdirectory( {directory}) Number TRUE if {directory} is a directory
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001451join( {list} [, {sep}]) String join {list} items into one String
Bram Moolenaard8b02732005-01-14 21:48:43 +00001452keys( {dict}) List List of keys in {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001453len( {expr}) Number the length of {expr}
1454libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number
1456line( {expr}) Number line nr of cursor, last line or mark
1457line2byte( {lnum}) Number byte count of line {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001458lispindent( {lnum}) Number Lisp indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459localtime() Number current time
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001460map( {expr}, {string}) List/Dict change each item in {expr} to {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
1462mapcheck( {name}[, {mode}]) String check for mappings matching {name}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001463match( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464 Number position where {pat} matches in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001465matchend( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 Number position where {pat} ends in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001467matchstr( {expr}, {pat}[, {start}[, {count}]])
1468 String {count}'th match of {pat} in {expr}
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001469max({list}) Number maximum value of items in {list}
1470min({list}) Number minumum value of items in {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001471mode() String current editing mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum}
1473nr2char( {expr}) String single char with ASCII value {expr}
1474prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001475range( {expr} [, {max} [, {stride}]])
1476 List items from {expr} to {max}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477remote_expr( {server}, {string} [, {idvar}])
1478 String send expression
1479remote_foreground( {server}) Number bring Vim server to the foreground
1480remote_peek( {serverid} [, {retvar}])
1481 Number check for reply string
1482remote_read( {serverid}) String read reply string
1483remote_send( {server}, {string} [, {idvar}])
1484 String send key sequence
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001485remove( {list}, {idx} [, {end}]) any remove items {idx}-{end} from {list}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001486remove( {dict}, {key}) any remove entry {key} from {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001487rename( {from}, {to}) Number rename (move) file from {from} to {to}
1488repeat( {expr}, {count}) String repeat {expr} {count} times
1489resolve( {filename}) String get filename a shortcut points to
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001490reverse( {list}) List reverse {list} in-place
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001491search( {pattern} [, {flags}]) Number search for {pattern}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001493 Number search for other end of start/end pair
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494server2client( {clientid}, {string})
1495 Number send reply string
1496serverlist() String get a list of available servers
1497setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val}
1498setcmdpos( {pos}) Number set cursor position in command-line
1499setline( {lnum}, {line}) Number set line {lnum} to {line}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001500setreg( {n}, {v}[, {opt}]) Number set register to value and type
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001502simplify( {filename}) String simplify filename as much as possible
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001503sort( {list} [, {func}]) List sort {list}, using {func} to compare
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001504split( {expr} [, {pat}]) List make List from {pat} separated {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505strftime( {format}[, {time}]) String time in specified format
1506stridx( {haystack}, {needle}) Number first index of {needle} in {haystack}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001507string( {expr}) String String representation of {expr} value
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508strlen( {expr}) Number length of the String {expr}
1509strpart( {src}, {start}[, {len}])
1510 String {len} characters of {src} at {start}
1511strridx( {haystack}, {needle}) Number last index of {needle} in {haystack}
1512strtrans( {expr}) String translate string to make it printable
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001513submatch( {nr}) String specific match in ":substitute"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514substitute( {expr}, {pat}, {sub}, {flags})
1515 String all {pat} in {expr} replaced with {sub}
Bram Moolenaar47136d72004-10-12 20:02:24 +00001516synID( {lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517synIDattr( {synID}, {what} [, {mode}])
1518 String attribute {what} of syntax ID {synID}
1519synIDtrans( {synID}) Number translated syntax ID of {synID}
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001520system( {expr} [, {input}]) String output of shell command/filter {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521tempname() String name for a temporary file
1522tolower( {expr}) String the String {expr} switched to lowercase
1523toupper( {expr}) String the String {expr} switched to uppercase
Bram Moolenaar8299df92004-07-10 09:47:34 +00001524tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr}
1525 to chars in {tostr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526type( {name}) Number type of variable {name}
1527virtcol( {expr}) Number screen column of cursor or mark
1528visualmode( [expr]) String last visual mode used
1529winbufnr( {nr}) Number buffer number of window {nr}
1530wincol() Number window column of the cursor
1531winheight( {nr}) Number height of window {nr}
1532winline() Number window line of the cursor
1533winnr() Number number of current window
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001534winrestcmd() String returns command to restore window sizes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535winwidth( {nr}) Number width of window {nr}
1536
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001537add({list}, {expr}) *add()*
1538 Append the item {expr} to List {list}. Returns the resulting
1539 List. Examples: >
1540 :let alist = add([1, 2, 3], item)
1541 :call add(mylist, "woodstock")
1542< Note that when {expr} is a List it is appended as a single
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001543 item. Use |extend()| to concatenate Lists.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001544 Use |insert()| to add an item at another position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001546
1547append({lnum}, {expr}) *append()*
1548 When {expr} is a List: Append each item of the list as a text
1549 line below line {lnum} in the current buffer.
1550 Otherwise append the text line {expr} below line {lnum} in the
1551 current buffer.
1552 {lnum} can be zero, to insert a line before the first one.
1553 Returns 1 for failure ({lnum} out of range or out of memory),
1554 0 for success. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001555 :let failed = append(line('$'), "# THE END")
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001556 :let failed = append(0, ["Chapter 1", "the beginning"])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001557<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 *argc()*
1559argc() The result is the number of files in the argument list of the
1560 current window. See |arglist|.
1561
1562 *argidx()*
1563argidx() The result is the current index in the argument list. 0 is
1564 the first file. argc() - 1 is the last one. See |arglist|.
1565
1566 *argv()*
1567argv({nr}) The result is the {nr}th file in the argument list of the
1568 current window. See |arglist|. "argv(0)" is the first one.
1569 Example: >
1570 :let i = 0
1571 :while i < argc()
1572 : let f = escape(argv(i), '. ')
1573 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
1574 : let i = i + 1
1575 :endwhile
1576<
1577 *browse()*
1578browse({save}, {title}, {initdir}, {default})
1579 Put up a file requester. This only works when "has("browse")"
1580 returns non-zero (only in some GUI versions).
1581 The input fields are:
1582 {save} when non-zero, select file to write
1583 {title} title for the requester
1584 {initdir} directory to start browsing in
1585 {default} default file name
1586 When the "Cancel" button is hit, something went wrong, or
1587 browsing is not possible, an empty string is returned.
1588
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001589 *browsedir()*
1590browsedir({title}, {initdir})
1591 Put up a directory requester. This only works when
1592 "has("browse")" returns non-zero (only in some GUI versions).
1593 On systems where a directory browser is not supported a file
1594 browser is used. In that case: select a file in the directory
1595 to be used.
1596 The input fields are:
1597 {title} title for the requester
1598 {initdir} directory to start browsing in
1599 When the "Cancel" button is hit, something went wrong, or
1600 browsing is not possible, an empty string is returned.
1601
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602bufexists({expr}) *bufexists()*
1603 The result is a Number, which is non-zero if a buffer called
1604 {expr} exists.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001605 If the {expr} argument is a number, buffer numbers are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 If the {expr} argument is a string it must match a buffer name
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001607 exactly. The name can be:
1608 - Relative to the current directory.
1609 - A full path.
1610 - The name of a buffer with 'filetype' set to "nofile".
1611 - A URL name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 Unlisted buffers will be found.
1613 Note that help files are listed by their short name in the
1614 output of |:buffers|, but bufexists() requires using their
1615 long name to be able to find them.
1616 Use "bufexists(0)" to test for the existence of an alternate
1617 file name.
1618 *buffer_exists()*
1619 Obsolete name: buffer_exists().
1620
1621buflisted({expr}) *buflisted()*
1622 The result is a Number, which is non-zero if a buffer called
1623 {expr} exists and is listed (has the 'buflisted' option set).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001624 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625
1626bufloaded({expr}) *bufloaded()*
1627 The result is a Number, which is non-zero if a buffer called
1628 {expr} exists and is loaded (shown in a window or hidden).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001629 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
1631bufname({expr}) *bufname()*
1632 The result is the name of a buffer, as it is displayed by the
1633 ":ls" command.
1634 If {expr} is a Number, that buffer number's name is given.
1635 Number zero is the alternate buffer for the current window.
1636 If {expr} is a String, it is used as a |file-pattern| to match
1637 with the buffer names. This is always done like 'magic' is
1638 set and 'cpoptions' is empty. When there is more than one
1639 match an empty string is returned.
1640 "" or "%" can be used for the current buffer, "#" for the
1641 alternate buffer.
1642 A full match is preferred, otherwise a match at the start, end
1643 or middle of the buffer name is accepted.
1644 Listed buffers are found first. If there is a single match
1645 with a listed buffer, that one is returned. Next unlisted
1646 buffers are searched for.
1647 If the {expr} is a String, but you want to use it as a buffer
1648 number, force it to be a Number by adding zero to it: >
1649 :echo bufname("3" + 0)
1650< If the buffer doesn't exist, or doesn't have a name, an empty
1651 string is returned. >
1652 bufname("#") alternate buffer name
1653 bufname(3) name of buffer 3
1654 bufname("%") name of current buffer
1655 bufname("file2") name of buffer where "file2" matches.
1656< *buffer_name()*
1657 Obsolete name: buffer_name().
1658
1659 *bufnr()*
1660bufnr({expr}) The result is the number of a buffer, as it is displayed by
1661 the ":ls" command. For the use of {expr}, see |bufname()|
1662 above. If the buffer doesn't exist, -1 is returned.
1663 bufnr("$") is the last buffer: >
1664 :let last_buffer = bufnr("$")
1665< The result is a Number, which is the highest buffer number
1666 of existing buffers. Note that not all buffers with a smaller
1667 number necessarily exist, because ":bwipeout" may have removed
1668 them. Use bufexists() to test for the existence of a buffer.
1669 *buffer_number()*
1670 Obsolete name: buffer_number().
1671 *last_buffer_nr()*
1672 Obsolete name for bufnr("$"): last_buffer_nr().
1673
1674bufwinnr({expr}) *bufwinnr()*
1675 The result is a Number, which is the number of the first
1676 window associated with buffer {expr}. For the use of {expr},
1677 see |bufname()| above. If buffer {expr} doesn't exist or
1678 there is no such window, -1 is returned. Example: >
1679
1680 echo "A window containing buffer 1 is " . (bufwinnr(1))
1681
1682< The number can be used with |CTRL-W_w| and ":wincmd w"
1683 |:wincmd|.
1684
1685
1686byte2line({byte}) *byte2line()*
1687 Return the line number that contains the character at byte
1688 count {byte} in the current buffer. This includes the
1689 end-of-line character, depending on the 'fileformat' option
1690 for the current buffer. The first character has byte count
1691 one.
1692 Also see |line2byte()|, |go| and |:goto|.
1693 {not available when compiled without the |+byte_offset|
1694 feature}
1695
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001696byteidx({expr}, {nr}) *byteidx()*
1697 Return byte index of the {nr}'th character in the string
1698 {expr}. Use zero for the first character, it returns zero.
1699 This function is only useful when there are multibyte
1700 characters, otherwise the returned value is equal to {nr}.
1701 Composing characters are counted as a separate character.
1702 Example : >
1703 echo matchstr(str, ".", byteidx(str, 3))
1704< will display the fourth character. Another way to do the
1705 same: >
1706 let s = strpart(str, byteidx(str, 3))
1707 echo strpart(s, 0, byteidx(s, 1))
1708< If there are less than {nr} characters -1 is returned.
1709 If there are exactly {nr} characters the length of the string
1710 is returned.
1711
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001712call({func}, {arglist} [, {dict}]) *call()* *E699*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001713 Call function {func} with the items in List {arglist} as
1714 arguments.
1715 {func} can either be a Funcref or the name of a function.
1716 a:firstline and a:lastline are set to the cursor line.
1717 Returns the return value of the called function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001718 {dict} is for functions with the "dict" attribute. It will be
1719 used to set the local variable "self". |Dictionary-function|
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001720
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721char2nr({expr}) *char2nr()*
1722 Return number value of the first char in {expr}. Examples: >
1723 char2nr(" ") returns 32
1724 char2nr("ABC") returns 65
1725< The current 'encoding' is used. Example for "utf-8": >
1726 char2nr("á") returns 225
1727 char2nr("á"[0]) returns 195
1728
1729cindent({lnum}) *cindent()*
1730 Get the amount of indent for line {lnum} according the C
1731 indenting rules, as with 'cindent'.
1732 The indent is counted in spaces, the value of 'tabstop' is
1733 relevant. {lnum} is used just like in |getline()|.
1734 When {lnum} is invalid or Vim was not compiled the |+cindent|
1735 feature, -1 is returned.
1736
1737 *col()*
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001738col({expr}) The result is a Number, which is the byte index of the column
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 position given with {expr}. The accepted positions are:
1740 . the cursor position
1741 $ the end of the cursor line (the result is the
1742 number of characters in the cursor line plus one)
1743 'x position of mark x (if the mark is not set, 0 is
1744 returned)
1745 For the screen column position use |virtcol()|.
1746 Note that only marks in the current file can be used.
1747 Examples: >
1748 col(".") column of cursor
1749 col("$") length of cursor line plus one
1750 col("'t") column of mark t
1751 col("'" . markname) column of mark markname
1752< The first column is 1. 0 is returned for an error.
1753 For the cursor position, when 'virtualedit' is active, the
1754 column is one higher if the cursor is after the end of the
1755 line. This can be used to obtain the column in Insert mode: >
1756 :imap <F2> <C-O>:let save_ve = &ve<CR>
1757 \<C-O>:set ve=all<CR>
1758 \<C-O>:echo col(".") . "\n" <Bar>
1759 \let &ve = save_ve<CR>
1760<
1761 *confirm()*
1762confirm({msg} [, {choices} [, {default} [, {type}]]])
1763 Confirm() offers the user a dialog, from which a choice can be
1764 made. It returns the number of the choice. For the first
1765 choice this is 1.
1766 Note: confirm() is only supported when compiled with dialog
1767 support, see |+dialog_con| and |+dialog_gui|.
1768 {msg} is displayed in a |dialog| with {choices} as the
1769 alternatives. When {choices} is missing or empty, "&OK" is
1770 used (and translated).
1771 {msg} is a String, use '\n' to include a newline. Only on
1772 some systems the string is wrapped when it doesn't fit.
1773 {choices} is a String, with the individual choices separated
1774 by '\n', e.g. >
1775 confirm("Save changes?", "&Yes\n&No\n&Cancel")
1776< The letter after the '&' is the shortcut key for that choice.
1777 Thus you can type 'c' to select "Cancel". The shortcut does
1778 not need to be the first letter: >
1779 confirm("file has been modified", "&Save\nSave &All")
1780< For the console, the first letter of each choice is used as
1781 the default shortcut key.
1782 The optional {default} argument is the number of the choice
1783 that is made if the user hits <CR>. Use 1 to make the first
1784 choice the default one. Use 0 to not set a default. If
1785 {default} is omitted, 1 is used.
1786 The optional {type} argument gives the type of dialog. This
1787 is only used for the icon of the Win32 GUI. It can be one of
1788 these values: "Error", "Question", "Info", "Warning" or
1789 "Generic". Only the first character is relevant. When {type}
1790 is omitted, "Generic" is used.
1791 If the user aborts the dialog by pressing <Esc>, CTRL-C,
1792 or another valid interrupt key, confirm() returns 0.
1793
1794 An example: >
1795 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
1796 :if choice == 0
1797 : echo "make up your mind!"
1798 :elseif choice == 3
1799 : echo "tasteful"
1800 :else
1801 : echo "I prefer bananas myself."
1802 :endif
1803< In a GUI dialog, buttons are used. The layout of the buttons
1804 depends on the 'v' flag in 'guioptions'. If it is included,
1805 the buttons are always put vertically. Otherwise, confirm()
1806 tries to put the buttons in one horizontal line. If they
1807 don't fit, a vertical layout is used anyway. For some systems
1808 the horizontal layout is always used.
1809
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001810 *copy()*
1811copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
1812 different from using {expr} directly.
1813 When {expr} is a List a shallow copy is created. This means
1814 that the original List can be changed without changing the
1815 copy, and vise versa. But the items are identical, thus
1816 changing an item changes the contents of both Lists. Also see
1817 |deepcopy()|.
1818
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001819count({comp}, {expr} [, {ic} [, {start}]]) *count()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001820 Return the number of times an item with value {expr} appears
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001821 in List or Dictionary {comp}.
1822 If {start} is given then start with the item with this index.
1823 {start} can only be used with a List.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001824 When {ic} is given and it's non-zero then case is ignored.
1825
1826
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 *cscope_connection()*
1828cscope_connection([{num} , {dbpath} [, {prepend}]])
1829 Checks for the existence of a |cscope| connection. If no
1830 parameters are specified, then the function returns:
1831 0, if cscope was not available (not compiled in), or
1832 if there are no cscope connections;
1833 1, if there is at least one cscope connection.
1834
1835 If parameters are specified, then the value of {num}
1836 determines how existence of a cscope connection is checked:
1837
1838 {num} Description of existence check
1839 ----- ------------------------------
1840 0 Same as no parameters (e.g., "cscope_connection()").
1841 1 Ignore {prepend}, and use partial string matches for
1842 {dbpath}.
1843 2 Ignore {prepend}, and use exact string matches for
1844 {dbpath}.
1845 3 Use {prepend}, use partial string matches for both
1846 {dbpath} and {prepend}.
1847 4 Use {prepend}, use exact string matches for both
1848 {dbpath} and {prepend}.
1849
1850 Note: All string comparisons are case sensitive!
1851
1852 Examples. Suppose we had the following (from ":cs show"): >
1853
1854 # pid database name prepend path
1855 0 27664 cscope.out /usr/local
1856<
1857 Invocation Return Val ~
1858 ---------- ---------- >
1859 cscope_connection() 1
1860 cscope_connection(1, "out") 1
1861 cscope_connection(2, "out") 0
1862 cscope_connection(3, "out") 0
1863 cscope_connection(3, "out", "local") 1
1864 cscope_connection(4, "out") 0
1865 cscope_connection(4, "out", "local") 0
1866 cscope_connection(4, "cscope.out", "/usr/local") 1
1867<
1868cursor({lnum}, {col}) *cursor()*
1869 Positions the cursor at the column {col} in the line {lnum}.
1870 Does not change the jumplist.
1871 If {lnum} is greater than the number of lines in the buffer,
1872 the cursor will be positioned at the last line in the buffer.
1873 If {lnum} is zero, the cursor will stay in the current line.
1874 If {col} is greater than the number of characters in the line,
1875 the cursor will be positioned at the last character in the
1876 line.
1877 If {col} is zero, the cursor will stay in the current column.
1878
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001879
Bram Moolenaar13065c42005-01-08 16:08:21 +00001880deepcopy({expr}) *deepcopy()* *E698*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001881 Make a copy of {expr}. For Numbers and Strings this isn't
1882 different from using {expr} directly.
1883 When {expr} is a List a full copy is created. This means
1884 that the original List can be changed without changing the
1885 copy, and vise versa. When an item is a List, a copy for it
1886 is made, recursively. Thus changing an item in the copy does
1887 not change the contents of the original List.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001888 *E724*
1889 Nesting is possible up to 100 levels. When there is an item
1890 that refers back to a higher level making a deep copy will
1891 fail.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001892 Also see |copy()|.
1893
1894delete({fname}) *delete()*
1895 Deletes the file by the name {fname}. The result is a Number,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 which is 0 if the file was deleted successfully, and non-zero
1897 when the deletion failed.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001898 Use |remove()| to delete an item from a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899
1900 *did_filetype()*
1901did_filetype() Returns non-zero when autocommands are being executed and the
1902 FileType event has been triggered at least once. Can be used
1903 to avoid triggering the FileType event again in the scripts
1904 that detect the file type. |FileType|
1905 When editing another file, the counter is reset, thus this
1906 really checks if the FileType event has been triggered for the
1907 current buffer. This allows an autocommand that starts
1908 editing another buffer to set 'filetype' and load a syntax
1909 file.
1910
Bram Moolenaar47136d72004-10-12 20:02:24 +00001911diff_filler({lnum}) *diff_filler()*
1912 Returns the number of filler lines above line {lnum}.
1913 These are the lines that were inserted at this point in
1914 another diff'ed window. These filler lines are shown in the
1915 display but don't exist in the buffer.
1916 {lnum} is used like with |getline()|. Thus "." is the current
1917 line, "'m" mark m, etc.
1918 Returns 0 if the current window is not in diff mode.
1919
1920diff_hlID({lnum}, {col}) *diff_hlID()*
1921 Returns the highlight ID for diff mode at line {lnum} column
1922 {col} (byte index). When the current line does not have a
1923 diff change zero is returned.
1924 {lnum} is used like with |getline()|. Thus "." is the current
1925 line, "'m" mark m, etc.
1926 {col} is 1 for the leftmost column, {lnum} is 1 for the first
1927 line.
1928 The highlight ID can be used with |synIDattr()| to obtain
1929 syntax information about the highlighting.
1930
Bram Moolenaar13065c42005-01-08 16:08:21 +00001931empty({expr}) *empty()*
1932 Return the Number 1 if {expr} is empty, zero otherwise.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001933 A List or Dictionary is empty when it does not have any items.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001934 A Number is empty when its value is zero.
1935 For a long List this is much faster then comparing the length
1936 with zero.
1937
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938escape({string}, {chars}) *escape()*
1939 Escape the characters in {chars} that occur in {string} with a
1940 backslash. Example: >
1941 :echo escape('c:\program files\vim', ' \')
1942< results in: >
1943 c:\\program\ files\\vim
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001944
1945< *eval()*
1946eval({string}) Evaluate {string} and return the result. Especially useful to
1947 turn the result of |string()| back into the original value.
1948 This works for Numbers, Strings and composites of them.
1949 Also works for Funcrefs that refer to existing functions.
1950
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951eventhandler() *eventhandler()*
1952 Returns 1 when inside an event handler. That is that Vim got
1953 interrupted while waiting for the user to type a character,
1954 e.g., when dropping a file on Vim. This means interactive
1955 commands cannot be used. Otherwise zero is returned.
1956
1957executable({expr}) *executable()*
1958 This function checks if an executable with the name {expr}
1959 exists. {expr} must be the name of the program without any
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001960 arguments.
1961 executable() uses the value of $PATH and/or the normal
1962 searchpath for programs. *PATHEXT*
1963 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
1964 optionally be included. Then the extensions in $PATHEXT are
1965 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
1966 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
1967 used. A dot by itself can be used in $PATHEXT to try using
1968 the name without an extension. When 'shell' looks like a
1969 Unix shell, then the name is also tried without adding an
1970 extension.
1971 On MS-DOS and MS-Windows it only checks if the file exists and
1972 is not a directory, not if it's really executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 The result is a Number:
1974 1 exists
1975 0 does not exist
1976 -1 not implemented on this system
1977
1978 *exists()*
1979exists({expr}) The result is a Number, which is non-zero if {expr} is
1980 defined, zero otherwise. The {expr} argument is a string,
1981 which contains one of these:
1982 &option-name Vim option (only checks if it exists,
1983 not if it really works)
1984 +option-name Vim option that works.
1985 $ENVNAME environment variable (could also be
1986 done by comparing with an empty
1987 string)
1988 *funcname built-in function (see |functions|)
1989 or user defined function (see
1990 |user-functions|).
1991 varname internal variable (see
1992 |internal-variables|). Does not work
1993 for |curly-braces-names|.
1994 :cmdname Ex command: built-in command, user
1995 command or command modifier |:command|.
1996 Returns:
1997 1 for match with start of a command
1998 2 full match with a command
1999 3 matches several user commands
2000 To check for a supported command
2001 always check the return value to be 2.
2002 #event autocommand defined for this event
2003 #event#pattern autocommand defined for this event and
2004 pattern (the pattern is taken
2005 literally and compared to the
2006 autocommand patterns character by
2007 character)
2008 For checking for a supported feature use |has()|.
2009
2010 Examples: >
2011 exists("&shortname")
2012 exists("$HOSTNAME")
2013 exists("*strftime")
2014 exists("*s:MyFunc")
2015 exists("bufcount")
2016 exists(":Make")
2017 exists("#CursorHold");
2018 exists("#BufReadPre#*.gz")
2019< There must be no space between the symbol (&/$/*/#) and the
2020 name.
2021 Note that the argument must be a string, not the name of the
2022 variable itself! For example: >
2023 exists(bufcount)
2024< This doesn't check for existence of the "bufcount" variable,
2025 but gets the contents of "bufcount", and checks if that
2026 exists.
2027
2028expand({expr} [, {flag}]) *expand()*
2029 Expand wildcards and the following special keywords in {expr}.
2030 The result is a String.
2031
2032 When there are several matches, they are separated by <NL>
2033 characters. [Note: in version 5.0 a space was used, which
2034 caused problems when a file name contains a space]
2035
2036 If the expansion fails, the result is an empty string. A name
2037 for a non-existing file is not included.
2038
2039 When {expr} starts with '%', '#' or '<', the expansion is done
2040 like for the |cmdline-special| variables with their associated
2041 modifiers. Here is a short overview:
2042
2043 % current file name
2044 # alternate file name
2045 #n alternate file name n
2046 <cfile> file name under the cursor
2047 <afile> autocmd file name
2048 <abuf> autocmd buffer number (as a String!)
2049 <amatch> autocmd matched name
2050 <sfile> sourced script file name
2051 <cword> word under the cursor
2052 <cWORD> WORD under the cursor
2053 <client> the {clientid} of the last received
2054 message |server2client()|
2055 Modifiers:
2056 :p expand to full path
2057 :h head (last path component removed)
2058 :t tail (last path component only)
2059 :r root (one extension removed)
2060 :e extension only
2061
2062 Example: >
2063 :let &tags = expand("%:p:h") . "/tags"
2064< Note that when expanding a string that starts with '%', '#' or
2065 '<', any following text is ignored. This does NOT work: >
2066 :let doesntwork = expand("%:h.bak")
2067< Use this: >
2068 :let doeswork = expand("%:h") . ".bak"
2069< Also note that expanding "<cfile>" and others only returns the
2070 referenced file name without further expansion. If "<cfile>"
2071 is "~/.cshrc", you need to do another expand() to have the
2072 "~/" expanded into the path of the home directory: >
2073 :echo expand(expand("<cfile>"))
2074<
2075 There cannot be white space between the variables and the
2076 following modifier. The |fnamemodify()| function can be used
2077 to modify normal file names.
2078
2079 When using '%' or '#', and the current or alternate file name
2080 is not defined, an empty string is used. Using "%:p" in a
2081 buffer with no name, results in the current directory, with a
2082 '/' added.
2083
2084 When {expr} does not start with '%', '#' or '<', it is
2085 expanded like a file name is expanded on the command line.
2086 'suffixes' and 'wildignore' are used, unless the optional
2087 {flag} argument is given and it is non-zero. Names for
2088 non-existing files are included.
2089
2090 Expand() can also be used to expand variables and environment
2091 variables that are only known in a shell. But this can be
2092 slow, because a shell must be started. See |expr-env-expand|.
2093 The expanded variable is still handled like a list of file
2094 names. When an environment variable cannot be expanded, it is
2095 left unchanged. Thus ":echo expand('$FOOBAR')" results in
2096 "$FOOBAR".
2097
2098 See |glob()| for finding existing files. See |system()| for
2099 getting the raw output of an external command.
2100
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002101extend({expr1}, {expr2} [, {expr3}]) *extend()*
2102 {expr1} and {expr2} must be both Lists or both Dictionaries.
2103
2104 If they are Lists: Append {expr2} to {expr1}.
2105 If {expr3} is given insert the items of {expr2} before item
2106 {expr3} in {expr1}. When {expr3} is zero insert before the
2107 first item. When {expr3} is equal to len({expr1}) then
2108 {expr2} is appended.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002109 Examples: >
2110 :echo sort(extend(mylist, [7, 5]))
2111 :call extend(mylist, [2, 3], 1)
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002112< Use |add()| to concatenate one item to a list. To concatenate
2113 two lists into a new list use the + operator: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002114 :let newlist = [1, 2, 3] + [4, 5]
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002115<
2116 If they are Dictionaries:
2117 Add all entries from {expr2} to {expr1}.
2118 If a key exists in both {expr1} and {expr2} then {expr3} is
2119 used to decide what to do:
2120 {expr3} = "keep": keep the value of {expr1}
2121 {expr3} = "force": use the value of {expr2}
2122 {expr3} = "error": give an error message
2123 When {expr3} is omitted then "force" is assumed.
2124
2125 {expr1} is changed when {expr2} is not empty. If necessary
2126 make a copy of {expr1} first.
2127 {expr2} remains unchanged.
2128 Returns {expr1}.
2129
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002130
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131filereadable({file}) *filereadable()*
2132 The result is a Number, which is TRUE when a file with the
2133 name {file} exists, and can be read. If {file} doesn't exist,
2134 or is a directory, the result is FALSE. {file} is any
2135 expression, which is used as a String.
2136 *file_readable()*
2137 Obsolete name: file_readable().
2138
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002139
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002140filter({expr}, {string}) *filter()*
2141 {expr} must be a List or a Dictionary.
2142 For each item in {expr} evaluate {string} and when the result
2143 is zero remove the item from the List or Dictionary.
2144 Inside {string} |v:val| has the value of the current item.
2145 For a Dictionary |v:key| has the key of the current item.
2146 Examples: >
2147 :call filter(mylist, 'v:val !~ "OLD"')
2148< Removes the items where "OLD" appears. >
2149 :call filter(mydict, 'v:key >= 8')
2150< Removes the items with a key below 8. >
2151 :call filter(var, 0)
Bram Moolenaard8b02732005-01-14 21:48:43 +00002152< Removes all the items, thus clears the List or Dictionary.
2153
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002154 Note that {string} is the result of expression and is then
2155 used as an expression again. Often it is good to use a
2156 |literal-string| to avoid having to double backslashes.
2157
2158 The operation is done in-place. If you want a List or
2159 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002160 :let l = filter(copy(mylist), '& =~ "KEEP"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002161
2162< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002163
2164
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002165finddir({name}[, {path}[, {count}]]) *finddir()*
2166 Find directory {name} in {path}.
2167 If {path} is omitted or empty then 'path' is used.
2168 If the optional {count} is given, find {count}'s occurrence of
2169 {name} in {path}.
2170 This is quite similar to the ex-command |:find|.
2171 When the found directory is below the current directory a
2172 relative path is returned. Otherwise a full path is returned.
2173 Example: >
2174 :echo findfile("tags.vim", ".;")
2175< Searches from the current directory upwards until it finds
2176 the file "tags.vim".
2177 {only available when compiled with the +file_in_path feature}
2178
2179findfile({name}[, {path}[, {count}]]) *findfile()*
2180 Just like |finddir()|, but find a file instead of a directory.
2181
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182filewritable({file}) *filewritable()*
2183 The result is a Number, which is 1 when a file with the
2184 name {file} exists, and can be written. If {file} doesn't
2185 exist, or is not writable, the result is 0. If (file) is a
2186 directory, and we can write to it, the result is 2.
2187
2188fnamemodify({fname}, {mods}) *fnamemodify()*
2189 Modify file name {fname} according to {mods}. {mods} is a
2190 string of characters like it is used for file names on the
2191 command line. See |filename-modifiers|.
2192 Example: >
2193 :echo fnamemodify("main.c", ":p:h")
2194< results in: >
2195 /home/mool/vim/vim/src
2196< Note: Environment variables and "~" don't work in {fname}, use
2197 |expand()| first then.
2198
2199foldclosed({lnum}) *foldclosed()*
2200 The result is a Number. If the line {lnum} is in a closed
2201 fold, the result is the number of the first line in that fold.
2202 If the line {lnum} is not in a closed fold, -1 is returned.
2203
2204foldclosedend({lnum}) *foldclosedend()*
2205 The result is a Number. If the line {lnum} is in a closed
2206 fold, the result is the number of the last line in that fold.
2207 If the line {lnum} is not in a closed fold, -1 is returned.
2208
2209foldlevel({lnum}) *foldlevel()*
2210 The result is a Number, which is the foldlevel of line {lnum}
2211 in the current buffer. For nested folds the deepest level is
2212 returned. If there is no fold at line {lnum}, zero is
2213 returned. It doesn't matter if the folds are open or closed.
2214 When used while updating folds (from 'foldexpr') -1 is
2215 returned for lines where folds are still to be updated and the
2216 foldlevel is unknown. As a special case the level of the
2217 previous line is usually available.
2218
2219 *foldtext()*
2220foldtext() Returns a String, to be displayed for a closed fold. This is
2221 the default function used for the 'foldtext' option and should
2222 only be called from evaluating 'foldtext'. It uses the
2223 |v:foldstart|, |v:foldend| and |v:folddashes| variables.
2224 The returned string looks like this: >
2225 +-- 45 lines: abcdef
2226< The number of dashes depends on the foldlevel. The "45" is
2227 the number of lines in the fold. "abcdef" is the text in the
2228 first non-blank line of the fold. Leading white space, "//"
2229 or "/*" and the text from the 'foldmarker' and 'commentstring'
2230 options is removed.
2231 {not available when compiled without the |+folding| feature}
2232
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002233foldtextresult({lnum}) *foldtextresult()*
2234 Returns the text that is displayed for the closed fold at line
2235 {lnum}. Evaluates 'foldtext' in the appropriate context.
2236 When there is no closed fold at {lnum} an empty string is
2237 returned.
2238 {lnum} is used like with |getline()|. Thus "." is the current
2239 line, "'m" mark m, etc.
2240 Useful when exporting folded text, e.g., to HTML.
2241 {not available when compiled without the |+folding| feature}
2242
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 *foreground()*
2244foreground() Move the Vim window to the foreground. Useful when sent from
2245 a client to a Vim server. |remote_send()|
2246 On Win32 systems this might not work, the OS does not always
2247 allow a window to bring itself to the foreground. Use
2248 |remote_foreground()| instead.
2249 {only in the Win32, Athena, Motif and GTK GUI versions and the
2250 Win32 console version}
2251
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002252
Bram Moolenaar13065c42005-01-08 16:08:21 +00002253function({name}) *function()* *E700*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002254 Return a Funcref variable that refers to function {name}.
2255 {name} can be a user defined function or an internal function.
2256
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002257
2258get({list}, {idx} [, {default}]) *get*
2259 Get item {idx} from List {list}. When this item is not
2260 available return {default}. Return zero when {default} is
2261 omitted.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002262get({dict}, {key} [, {default}])
2263 Get item with key {key} from Dictionary {dict}. When this
2264 item is not available return {default}. Return zero when
2265 {default} is omitted.
2266
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002267
2268getbufvar({expr}, {varname}) *getbufvar()*
2269 The result is the value of option or local buffer variable
2270 {varname} in buffer {expr}. Note that the name without "b:"
2271 must be used.
2272 This also works for a global or local window option, but it
2273 doesn't work for a global or local window variable.
2274 For the use of {expr}, see |bufname()| above.
2275 When the buffer or variable doesn't exist an empty string is
2276 returned, there is no error message.
2277 Examples: >
2278 :let bufmodified = getbufvar(1, "&mod")
2279 :echo "todo myvar = " . getbufvar("todo", "myvar")
2280<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281getchar([expr]) *getchar()*
2282 Get a single character from the user. If it is an 8-bit
2283 character, the result is a number. Otherwise a String is
2284 returned with the encoded character. For a special key it's a
2285 sequence of bytes starting with 0x80 (decimal: 128).
2286 If [expr] is omitted, wait until a character is available.
2287 If [expr] is 0, only get a character when one is available.
2288 If [expr] is 1, only check if a character is available, it is
2289 not consumed. If a normal character is
2290 available, it is returned, otherwise a
2291 non-zero value is returned.
2292 If a normal character available, it is returned as a Number.
2293 Use nr2char() to convert it to a String.
2294 The returned value is zero if no character is available.
2295 The returned value is a string of characters for special keys
2296 and when a modifier (shift, control, alt) was used.
2297 There is no prompt, you will somehow have to make clear to the
2298 user that a character has to be typed.
2299 There is no mapping for the character.
2300 Key codes are replaced, thus when the user presses the <Del>
2301 key you get the code for the <Del> key, not the raw character
2302 sequence. Examples: >
2303 getchar() == "\<Del>"
2304 getchar() == "\<S-Left>"
2305< This example redefines "f" to ignore case: >
2306 :nmap f :call FindChar()<CR>
2307 :function FindChar()
2308 : let c = nr2char(getchar())
2309 : while col('.') < col('$') - 1
2310 : normal l
2311 : if getline('.')[col('.') - 1] ==? c
2312 : break
2313 : endif
2314 : endwhile
2315 :endfunction
2316
2317getcharmod() *getcharmod()*
2318 The result is a Number which is the state of the modifiers for
2319 the last obtained character with getchar() or in another way.
2320 These values are added together:
2321 2 shift
2322 4 control
2323 8 alt (meta)
2324 16 mouse double click
2325 32 mouse triple click
2326 64 mouse quadruple click
2327 128 Macintosh only: command
2328 Only the modifiers that have not been included in the
2329 character itself are obtained. Thus Shift-a results in "A"
2330 with no modifier.
2331
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332getcmdline() *getcmdline()*
2333 Return the current command-line. Only works when the command
2334 line is being edited, thus requires use of |c_CTRL-\_e| or
2335 |c_CTRL-R_=|.
2336 Example: >
2337 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
2338< Also see |getcmdpos()| and |setcmdpos()|.
2339
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002340getcmdpos() *getcmdpos()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 Return the position of the cursor in the command line as a
2342 byte count. The first column is 1.
2343 Only works when editing the command line, thus requires use of
2344 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
2345 Also see |setcmdpos()| and |getcmdline()|.
2346
2347 *getcwd()*
2348getcwd() The result is a String, which is the name of the current
2349 working directory.
2350
2351getfsize({fname}) *getfsize()*
2352 The result is a Number, which is the size in bytes of the
2353 given file {fname}.
2354 If {fname} is a directory, 0 is returned.
2355 If the file {fname} can't be found, -1 is returned.
2356
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002357getfontname([{name}]) *getfontname()*
2358 Without an argument returns the name of the normal font being
2359 used. Like what is used for the Normal highlight group
2360 |hl-Normal|.
2361 With an argument a check is done whether {name} is a valid
2362 font name. If not then an empty string is returned.
2363 Otherwise the actual font name is returned, or {name} if the
2364 GUI does not support obtaining the real name.
2365 Only works when the GUI is running, thus not you your vimrc or
2366 Note that the GTK 2 GUI accepts any font name, thus checking
2367 for a valid name does not work.
2368 gvimrc file. Use the |GUIEnter| autocommand to use this
2369 function just after the GUI has started.
2370
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002371getfperm({fname}) *getfperm()*
2372 The result is a String, which is the read, write, and execute
2373 permissions of the given file {fname}.
2374 If {fname} does not exist or its directory cannot be read, an
2375 empty string is returned.
2376 The result is of the form "rwxrwxrwx", where each group of
2377 "rwx" flags represent, in turn, the permissions of the owner
2378 of the file, the group the file belongs to, and other users.
2379 If a user does not have a given permission the flag for this
2380 is replaced with the string "-". Example: >
2381 :echo getfperm("/etc/passwd")
2382< This will hopefully (from a security point of view) display
2383 the string "rw-r--r--" or even "rw-------".
2384
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385getftime({fname}) *getftime()*
2386 The result is a Number, which is the last modification time of
2387 the given file {fname}. The value is measured as seconds
2388 since 1st Jan 1970, and may be passed to strftime(). See also
2389 |localtime()| and |strftime()|.
2390 If the file {fname} can't be found -1 is returned.
2391
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002392getftype({fname}) *getftype()*
2393 The result is a String, which is a description of the kind of
2394 file of the given file {fname}.
2395 If {fname} does not exist an empty string is returned.
2396 Here is a table over different kinds of files and their
2397 results:
2398 Normal file "file"
2399 Directory "dir"
2400 Symbolic link "link"
2401 Block device "bdev"
2402 Character device "cdev"
2403 Socket "socket"
2404 FIFO "fifo"
2405 All other "other"
2406 Example: >
2407 getftype("/home")
2408< Note that a type such as "link" will only be returned on
2409 systems that support it. On some systems only "dir" and
2410 "file" are returned.
2411
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 *getline()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002413getline({lnum} [, {end}])
2414 Without {end} the result is a String, which is line {lnum}
2415 from the current buffer. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 getline(1)
2417< When {lnum} is a String that doesn't start with a
2418 digit, line() is called to translate the String into a Number.
2419 To get the line under the cursor: >
2420 getline(".")
2421< When {lnum} is smaller than 1 or bigger than the number of
2422 lines in the buffer, an empty string is returned.
2423
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002424 When {end} is given the result is a List where each item is a
2425 line from the current buffer in the range {lnum} to {end},
2426 including line {end}.
2427 {end} is used in the same way as {lnum}.
2428 Non-existing lines are silently omitted.
2429 When {end} is before {lnum} an error is given.
2430 Example: >
2431 :let start = line('.')
2432 :let end = search("^$") - 1
2433 :let lines = getline(start, end)
2434
2435
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436getreg([{regname}]) *getreg()*
2437 The result is a String, which is the contents of register
2438 {regname}. Example: >
2439 :let cliptext = getreg('*')
2440< getreg('=') returns the last evaluated value of the expression
2441 register. (For use in maps).
2442 If {regname} is not specified, |v:register| is used.
2443
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002444
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445getregtype([{regname}]) *getregtype()*
2446 The result is a String, which is type of register {regname}.
2447 The value will be one of:
2448 "v" for |characterwise| text
2449 "V" for |linewise| text
2450 "<CTRL-V>{width}" for |blockwise-visual| text
2451 0 for an empty or unknown register
2452 <CTRL-V> is one character with value 0x16.
2453 If {regname} is not specified, |v:register| is used.
2454
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002455
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 *getwinposx()*
2457getwinposx() The result is a Number, which is the X coordinate in pixels of
2458 the left hand side of the GUI Vim window. The result will be
2459 -1 if the information is not available.
2460
2461 *getwinposy()*
2462getwinposy() The result is a Number, which is the Y coordinate in pixels of
2463 the top of the GUI Vim window. The result will be -1 if the
2464 information is not available.
2465
2466getwinvar({nr}, {varname}) *getwinvar()*
2467 The result is the value of option or local window variable
2468 {varname} in window {nr}.
2469 This also works for a global or local buffer option, but it
2470 doesn't work for a global or local buffer variable.
2471 Note that the name without "w:" must be used.
2472 Examples: >
2473 :let list_is_on = getwinvar(2, '&list')
2474 :echo "myvar = " . getwinvar(1, 'myvar')
2475<
2476 *glob()*
2477glob({expr}) Expand the file wildcards in {expr}. The result is a String.
2478 When there are several matches, they are separated by <NL>
2479 characters.
2480 If the expansion fails, the result is an empty string.
2481 A name for a non-existing file is not included.
2482
2483 For most systems backticks can be used to get files names from
2484 any external command. Example: >
2485 :let tagfiles = glob("`find . -name tags -print`")
2486 :let &tags = substitute(tagfiles, "\n", ",", "g")
2487< The result of the program inside the backticks should be one
2488 item per line. Spaces inside an item are allowed.
2489
2490 See |expand()| for expanding special Vim variables. See
2491 |system()| for getting the raw output of an external command.
2492
2493globpath({path}, {expr}) *globpath()*
2494 Perform glob() on all directories in {path} and concatenate
2495 the results. Example: >
2496 :echo globpath(&rtp, "syntax/c.vim")
2497< {path} is a comma-separated list of directory names. Each
2498 directory name is prepended to {expr} and expanded like with
2499 glob(). A path separator is inserted when needed.
2500 To add a comma inside a directory name escape it with a
2501 backslash. Note that on MS-Windows a directory may have a
2502 trailing backslash, remove it if you put a comma after it.
2503 If the expansion fails for one of the directories, there is no
2504 error message.
2505 The 'wildignore' option applies: Names matching one of the
2506 patterns in 'wildignore' will be skipped.
2507
2508 *has()*
2509has({feature}) The result is a Number, which is 1 if the feature {feature} is
2510 supported, zero otherwise. The {feature} argument is a
2511 string. See |feature-list| below.
2512 Also see |exists()|.
2513
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002514
2515has_key({dict}, {key}) *has_key()*
2516 The result is a Number, which is 1 if Dictionary {dict} has an
2517 entry with key {key}. Zero otherwise.
2518
2519
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520hasmapto({what} [, {mode}]) *hasmapto()*
2521 The result is a Number, which is 1 if there is a mapping that
2522 contains {what} in somewhere in the rhs (what it is mapped to)
2523 and this mapping exists in one of the modes indicated by
2524 {mode}.
2525 Both the global mappings and the mappings local to the current
2526 buffer are checked for a match.
2527 If no matching mapping is found 0 is returned.
2528 The following characters are recognized in {mode}:
2529 n Normal mode
2530 v Visual mode
2531 o Operator-pending mode
2532 i Insert mode
2533 l Language-Argument ("r", "f", "t", etc.)
2534 c Command-line mode
2535 When {mode} is omitted, "nvo" is used.
2536
2537 This function is useful to check if a mapping already exists
2538 to a function in a Vim script. Example: >
2539 :if !hasmapto('\ABCdoit')
2540 : map <Leader>d \ABCdoit
2541 :endif
2542< This installs the mapping to "\ABCdoit" only if there isn't
2543 already a mapping to "\ABCdoit".
2544
2545histadd({history}, {item}) *histadd()*
2546 Add the String {item} to the history {history} which can be
2547 one of: *hist-names*
2548 "cmd" or ":" command line history
2549 "search" or "/" search pattern history
2550 "expr" or "=" typed expression history
2551 "input" or "@" input line history
2552 If {item} does already exist in the history, it will be
2553 shifted to become the newest entry.
2554 The result is a Number: 1 if the operation was successful,
2555 otherwise 0 is returned.
2556
2557 Example: >
2558 :call histadd("input", strftime("%Y %b %d"))
2559 :let date=input("Enter date: ")
2560< This function is not available in the |sandbox|.
2561
2562histdel({history} [, {item}]) *histdel()*
2563 Clear {history}, ie. delete all its entries. See |hist-names|
2564 for the possible values of {history}.
2565
2566 If the parameter {item} is given as String, this is seen
2567 as regular expression. All entries matching that expression
2568 will be removed from the history (if there are any).
2569 Upper/lowercase must match, unless "\c" is used |/\c|.
2570 If {item} is a Number, it will be interpreted as index, see
2571 |:history-indexing|. The respective entry will be removed
2572 if it exists.
2573
2574 The result is a Number: 1 for a successful operation,
2575 otherwise 0 is returned.
2576
2577 Examples:
2578 Clear expression register history: >
2579 :call histdel("expr")
2580<
2581 Remove all entries starting with "*" from the search history: >
2582 :call histdel("/", '^\*')
2583<
2584 The following three are equivalent: >
2585 :call histdel("search", histnr("search"))
2586 :call histdel("search", -1)
2587 :call histdel("search", '^'.histget("search", -1).'$')
2588<
2589 To delete the last search pattern and use the last-but-one for
2590 the "n" command and 'hlsearch': >
2591 :call histdel("search", -1)
2592 :let @/ = histget("search", -1)
2593
2594histget({history} [, {index}]) *histget()*
2595 The result is a String, the entry with Number {index} from
2596 {history}. See |hist-names| for the possible values of
2597 {history}, and |:history-indexing| for {index}. If there is
2598 no such entry, an empty String is returned. When {index} is
2599 omitted, the most recent item from the history is used.
2600
2601 Examples:
2602 Redo the second last search from history. >
2603 :execute '/' . histget("search", -2)
2604
2605< Define an Ex command ":H {num}" that supports re-execution of
2606 the {num}th entry from the output of |:history|. >
2607 :command -nargs=1 H execute histget("cmd", 0+<args>)
2608<
2609histnr({history}) *histnr()*
2610 The result is the Number of the current entry in {history}.
2611 See |hist-names| for the possible values of {history}.
2612 If an error occurred, -1 is returned.
2613
2614 Example: >
2615 :let inp_index = histnr("expr")
2616<
2617hlexists({name}) *hlexists()*
2618 The result is a Number, which is non-zero if a highlight group
2619 called {name} exists. This is when the group has been
2620 defined in some way. Not necessarily when highlighting has
2621 been defined for it, it may also have been used for a syntax
2622 item.
2623 *highlight_exists()*
2624 Obsolete name: highlight_exists().
2625
2626 *hlID()*
2627hlID({name}) The result is a Number, which is the ID of the highlight group
2628 with name {name}. When the highlight group doesn't exist,
2629 zero is returned.
2630 This can be used to retrieve information about the highlight
2631 group. For example, to get the background color of the
2632 "Comment" group: >
2633 :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
2634< *highlightID()*
2635 Obsolete name: highlightID().
2636
2637hostname() *hostname()*
2638 The result is a String, which is the name of the machine on
2639 which Vim is currently running. Machine names greater than
2640 256 characters long are truncated.
2641
2642iconv({expr}, {from}, {to}) *iconv()*
2643 The result is a String, which is the text {expr} converted
2644 from encoding {from} to encoding {to}.
2645 When the conversion fails an empty string is returned.
2646 The encoding names are whatever the iconv() library function
2647 can accept, see ":!man 3 iconv".
2648 Most conversions require Vim to be compiled with the |+iconv|
2649 feature. Otherwise only UTF-8 to latin1 conversion and back
2650 can be done.
2651 This can be used to display messages with special characters,
2652 no matter what 'encoding' is set to. Write the message in
2653 UTF-8 and use: >
2654 echo iconv(utf8_str, "utf-8", &enc)
2655< Note that Vim uses UTF-8 for all Unicode encodings, conversion
2656 from/to UCS-2 is automatically changed to use UTF-8. You
2657 cannot use UCS-2 in a string anyway, because of the NUL bytes.
2658 {only available when compiled with the +multi_byte feature}
2659
2660 *indent()*
2661indent({lnum}) The result is a Number, which is indent of line {lnum} in the
2662 current buffer. The indent is counted in spaces, the value
2663 of 'tabstop' is relevant. {lnum} is used just like in
2664 |getline()|.
2665 When {lnum} is invalid -1 is returned.
2666
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002667
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002668index({list}, {expr} [, {start} [, {ic}]]) *index()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002669 Return the lowest index in List {list} where the item has a
2670 value equal to {expr}.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002671 If {start} is given then skip items with a lower index.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002672 When {ic} is given and it is non-zero, ignore case. Otherwise
2673 case must match.
2674 -1 is returned when {expr} is not found in {list}.
2675 Example: >
2676 :let idx = index(words, "the")
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002677 :if index(numbers, 123) >= 0
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002678
2679
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680input({prompt} [, {text}]) *input()*
2681 The result is a String, which is whatever the user typed on
2682 the command-line. The parameter is either a prompt string, or
2683 a blank string (for no prompt). A '\n' can be used in the
2684 prompt to start a new line. The highlighting set with
2685 |:echohl| is used for the prompt. The input is entered just
2686 like a command-line, with the same editing commands and
2687 mappings. There is a separate history for lines typed for
2688 input().
2689 If the optional {text} is present, this is used for the
2690 default reply, as if the user typed this.
2691 NOTE: This must not be used in a startup file, for the
2692 versions that only run in GUI mode (e.g., the Win32 GUI).
2693 Note: When input() is called from within a mapping it will
2694 consume remaining characters from that mapping, because a
2695 mapping is handled like the characters were typed.
2696 Use |inputsave()| before input() and |inputrestore()|
2697 after input() to avoid that. Another solution is to avoid
2698 that further characters follow in the mapping, e.g., by using
2699 |:execute| or |:normal|.
2700
2701 Example: >
2702 :if input("Coffee or beer? ") == "beer"
2703 : echo "Cheers!"
2704 :endif
2705< Example with default text: >
2706 :let color = input("Color? ", "white")
2707< Example with a mapping: >
2708 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
2709 :function GetFoo()
2710 : call inputsave()
2711 : let g:Foo = input("enter search pattern: ")
2712 : call inputrestore()
2713 :endfunction
2714
2715inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
2716 Like input(), but when the GUI is running and text dialogs are
2717 supported, a dialog window pops up to input the text.
2718 Example: >
2719 :let n = inputdialog("value for shiftwidth", &sw)
2720 :if n != ""
2721 : let &sw = n
2722 :endif
2723< When the dialog is cancelled {cancelreturn} is returned. When
2724 omitted an empty string is returned.
2725 Hitting <Enter> works like pressing the OK button. Hitting
2726 <Esc> works like pressing the Cancel button.
2727
2728inputrestore() *inputrestore()*
2729 Restore typeahead that was saved with a previous inputsave().
2730 Should be called the same number of times inputsave() is
2731 called. Calling it more often is harmless though.
2732 Returns 1 when there is nothing to restore, 0 otherwise.
2733
2734inputsave() *inputsave()*
2735 Preserve typeahead (also from mappings) and clear it, so that
2736 a following prompt gets input from the user. Should be
2737 followed by a matching inputrestore() after the prompt. Can
2738 be used several times, in which case there must be just as
2739 many inputrestore() calls.
2740 Returns 1 when out of memory, 0 otherwise.
2741
2742inputsecret({prompt} [, {text}]) *inputsecret()*
2743 This function acts much like the |input()| function with but
2744 two exceptions:
2745 a) the user's response will be displayed as a sequence of
2746 asterisks ("*") thereby keeping the entry secret, and
2747 b) the user's response will not be recorded on the input
2748 |history| stack.
2749 The result is a String, which is whatever the user actually
2750 typed on the command-line in response to the issued prompt.
2751
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002752insert({list}, {item} [, {idx}]) *insert()*
2753 Insert {item} at the start of List {list}.
2754 If {idx} is specified insert {item} before the item with index
2755 {idx}. If {idx} is zero it goes before the first item, just
2756 like omitting {idx}. A negative {idx} is also possible, see
2757 |list-index|. -1 inserts just before the last item.
2758 Returns the resulting List. Examples: >
2759 :let mylist = insert([2, 3, 5], 1)
2760 :call insert(mylist, 4, -1)
2761 :call insert(mylist, 6, len(mylist))
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002762< The last example can be done simpler with |add()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002763 Note that when {item} is a List it is inserted as a single
2764 item. Use |extend()| to concatenate Lists.
2765
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766isdirectory({directory}) *isdirectory()*
2767 The result is a Number, which is non-zero when a directory
2768 with the name {directory} exists. If {directory} doesn't
2769 exist, or isn't a directory, the result is FALSE. {directory}
2770 is any expression, which is used as a String.
2771
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002772
2773join({list} [, {sep}]) *join()*
2774 Join the items in {list} together into one String.
2775 When {sep} is specified it is put in between the items. If
2776 {sep} is omitted a single space is used.
2777 Note that {sep} is not added at the end. You might want to
2778 add it there too: >
2779 let lines = join(mylist, "\n") . "\n"
2780< String items are used as-is. Lists and Dictionaries are
2781 converted into a string like with |string()|.
2782 The opposite function is |split()|.
2783
Bram Moolenaard8b02732005-01-14 21:48:43 +00002784keys({dict}) *keys()*
2785 Return a List with all the keys of {dict}. The List is in
2786 arbitrary order.
2787
Bram Moolenaar13065c42005-01-08 16:08:21 +00002788 *len()* *E701*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002789len({expr}) The result is a Number, which is the length of the argument.
2790 When {expr} is a String or a Number the length in bytes is
2791 used, as with |strlen()|.
2792 When {expr} is a List the number of items in the List is
2793 returned.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002794 When {expr} is a Dictionary the number of entries in the
2795 Dictionary is returned.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002796 Otherwise an error is given.
2797
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 *libcall()* *E364* *E368*
2799libcall({libname}, {funcname}, {argument})
2800 Call function {funcname} in the run-time library {libname}
2801 with single argument {argument}.
2802 This is useful to call functions in a library that you
2803 especially made to be used with Vim. Since only one argument
2804 is possible, calling standard library functions is rather
2805 limited.
2806 The result is the String returned by the function. If the
2807 function returns NULL, this will appear as an empty string ""
2808 to Vim.
2809 If the function returns a number, use libcallnr()!
2810 If {argument} is a number, it is passed to the function as an
2811 int; if {argument} is a string, it is passed as a
2812 null-terminated string.
2813 This function will fail in |restricted-mode|.
2814
2815 libcall() allows you to write your own 'plug-in' extensions to
2816 Vim without having to recompile the program. It is NOT a
2817 means to call system functions! If you try to do so Vim will
2818 very probably crash.
2819
2820 For Win32, the functions you write must be placed in a DLL
2821 and use the normal C calling convention (NOT Pascal which is
2822 used in Windows System DLLs). The function must take exactly
2823 one parameter, either a character pointer or a long integer,
2824 and must return a character pointer or NULL. The character
2825 pointer returned must point to memory that will remain valid
2826 after the function has returned (e.g. in static data in the
2827 DLL). If it points to allocated memory, that memory will
2828 leak away. Using a static buffer in the function should work,
2829 it's then freed when the DLL is unloaded.
2830
2831 WARNING: If the function returns a non-valid pointer, Vim may
2832 crash! This also happens if the function returns a number,
2833 because Vim thinks it's a pointer.
2834 For Win32 systems, {libname} should be the filename of the DLL
2835 without the ".DLL" suffix. A full path is only required if
2836 the DLL is not in the usual places.
2837 For Unix: When compiling your own plugins, remember that the
2838 object code must be compiled as position-independent ('PIC').
2839 {only in Win32 on some Unix versions, when the |+libcall|
2840 feature is present}
2841 Examples: >
2842 :echo libcall("libc.so", "getenv", "HOME")
2843 :echo libcallnr("/usr/lib/libc.so", "getpid", "")
2844<
2845 *libcallnr()*
2846libcallnr({libname}, {funcname}, {argument})
2847 Just like libcall(), but used for a function that returns an
2848 int instead of a string.
2849 {only in Win32 on some Unix versions, when the |+libcall|
2850 feature is present}
2851 Example (not very useful...): >
2852 :call libcallnr("libc.so", "printf", "Hello World!\n")
2853 :call libcallnr("libc.so", "sleep", 10)
2854<
2855 *line()*
2856line({expr}) The result is a Number, which is the line number of the file
2857 position given with {expr}. The accepted positions are:
2858 . the cursor position
2859 $ the last line in the current buffer
2860 'x position of mark x (if the mark is not set, 0 is
2861 returned)
2862 Note that only marks in the current file can be used.
2863 Examples: >
2864 line(".") line number of the cursor
2865 line("'t") line number of mark t
2866 line("'" . marker) line number of mark marker
2867< *last-position-jump*
2868 This autocommand jumps to the last known position in a file
2869 just after opening it, if the '" mark is set: >
2870 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002871
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872line2byte({lnum}) *line2byte()*
2873 Return the byte count from the start of the buffer for line
2874 {lnum}. This includes the end-of-line character, depending on
2875 the 'fileformat' option for the current buffer. The first
2876 line returns 1.
2877 This can also be used to get the byte count for the line just
2878 below the last line: >
2879 line2byte(line("$") + 1)
2880< This is the file size plus one.
2881 When {lnum} is invalid, or the |+byte_offset| feature has been
2882 disabled at compile time, -1 is returned.
2883 Also see |byte2line()|, |go| and |:goto|.
2884
2885lispindent({lnum}) *lispindent()*
2886 Get the amount of indent for line {lnum} according the lisp
2887 indenting rules, as with 'lisp'.
2888 The indent is counted in spaces, the value of 'tabstop' is
2889 relevant. {lnum} is used just like in |getline()|.
2890 When {lnum} is invalid or Vim was not compiled the
2891 |+lispindent| feature, -1 is returned.
2892
2893localtime() *localtime()*
2894 Return the current time, measured as seconds since 1st Jan
2895 1970. See also |strftime()| and |getftime()|.
2896
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002897
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002898map({expr}, {string}) *map()*
2899 {expr} must be a List or a Dictionary.
2900 Replace each item in {expr} with the result of evaluating
2901 {string}.
2902 Inside {string} |v:val| has the value of the current item.
2903 For a Dictionary |v:key| has the key of the current item.
2904 Example: >
2905 :call map(mylist, '"> " . v:val . " <"')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002906< This puts "> " before and " <" after each item in "mylist".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002907
2908 Note that {string} is the result of expression and is then
2909 used as an expression again. Often it is good to use a
2910 |literal-string| to avoid having to double backslashes.
2911
2912 The operation is done in-place. If you want a List or
2913 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002914 :let tlist = map(copy(mylist), ' & . "\t"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002915
2916< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002917
2918
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919maparg({name}[, {mode}]) *maparg()*
2920 Return the rhs of mapping {name} in mode {mode}. When there
2921 is no mapping for {name}, an empty String is returned.
2922 These characters can be used for {mode}:
2923 "n" Normal
2924 "v" Visual
2925 "o" Operator-pending
2926 "i" Insert
2927 "c" Cmd-line
2928 "l" langmap |language-mapping|
2929 "" Normal, Visual and Operator-pending
2930 When {mode} is omitted, the modes from "" are used.
2931 The {name} can have special key names, like in the ":map"
2932 command. The returned String has special characters
2933 translated like in the output of the ":map" command listing.
2934 The mappings local to the current buffer are checked first,
2935 then the global mappings.
2936
2937mapcheck({name}[, {mode}]) *mapcheck()*
2938 Check if there is a mapping that matches with {name} in mode
2939 {mode}. See |maparg()| for {mode} and special names in
2940 {name}.
2941 A match happens with a mapping that starts with {name} and
2942 with a mapping which is equal to the start of {name}.
2943
2944 matches mapping "a" "ab" "abc" ~
2945 mapcheck("a") yes yes yes
2946 mapcheck("abc") yes yes yes
2947 mapcheck("ax") yes no no
2948 mapcheck("b") no no no
2949
2950 The difference with maparg() is that mapcheck() finds a
2951 mapping that matches with {name}, while maparg() only finds a
2952 mapping for {name} exactly.
2953 When there is no mapping that starts with {name}, an empty
2954 String is returned. If there is one, the rhs of that mapping
2955 is returned. If there are several mappings that start with
2956 {name}, the rhs of one of them is returned.
2957 The mappings local to the current buffer are checked first,
2958 then the global mappings.
2959 This function can be used to check if a mapping can be added
2960 without being ambiguous. Example: >
2961 :if mapcheck("_vv") == ""
2962 : map _vv :set guifont=7x13<CR>
2963 :endif
2964< This avoids adding the "_vv" mapping when there already is a
2965 mapping for "_v" or for "_vvv".
2966
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002967match({expr}, {pat}[, {start}[, {count}]]) *match()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002968 When {expr} is a List then this returns the index of the first
2969 item where {pat} matches. Each item is used as a String,
2970 Lists and Dictionaries are used as echoed.
2971 Otherwise, {expr} is used as a String. The result is a
2972 Number, which gives the index (byte offset) in {expr} where
2973 {pat} matches.
2974 A match at the first character or List item returns zero.
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002975 If there is no match -1 is returned.
2976 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002977 :echo match("testing", "ing") " results in 4
2978 :echo match([1, 'x'], '\a') " results in 2
2979< See |string-match| for how {pat} is used.
2980
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002981 When {count} is given use the {count}'th match. When a match
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002982 is found in a String the search for the next one starts on
2983 character further. Thus this example results in 1: >
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002984 echo match("testing", "..", 0, 2)
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002985< In a List the search continues in the next item.
2986
2987 If {start} is given, the search starts from byte index
2988 {start} in a String or item {start} in a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 The result, however, is still the index counted from the
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002990 first character/item. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 :echo match("testing", "ing", 2)
2992< result is again "4". >
2993 :echo match("testing", "ing", 4)
2994< result is again "4". >
2995 :echo match("testing", "t", 2)
2996< result is "3".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002997 For a String, if {start} < 0, it will be set to 0. For a list
2998 the index is counted from the end.
2999 If {start} is out of range (> strlen({expr} for a String or
3000 > len({expr} for a List) -1 is returned.
3001
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 See |pattern| for the patterns that are accepted.
3003 The 'ignorecase' option is used to set the ignore-caseness of
3004 the pattern. 'smartcase' is NOT used. The matching is always
3005 done like 'magic' is set and 'cpoptions' is empty.
3006
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003007matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 Same as match(), but return the index of first character after
3009 the match. Example: >
3010 :echo matchend("testing", "ing")
3011< results in "7".
3012 The {start}, if given, has the same meaning as for match(). >
3013 :echo matchend("testing", "ing", 2)
3014< results in "7". >
3015 :echo matchend("testing", "ing", 5)
3016< result is "-1".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003017 When {expr} is a List the result is equal to match().
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003019matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 Same as match(), but return the matched string. Example: >
3021 :echo matchstr("testing", "ing")
3022< results in "ing".
3023 When there is no match "" is returned.
3024 The {start}, if given, has the same meaning as for match(). >
3025 :echo matchstr("testing", "ing", 2)
3026< results in "ing". >
3027 :echo matchstr("testing", "ing", 5)
3028< result is "".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003029 When {expr} is a List then the matching item is returned.
3030 The type isn't changed, it's not necessarily a String.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003032 *max()*
3033max({list}) Return the maximum value of all items in {list}.
3034 If {list} is not a list or one of the items in {list} cannot
3035 be used as a Number this results in an error.
3036 An empty List results in zero.
3037
3038 *min()*
3039min({list}) Return the minumum value of all items in {list}.
3040 If {list} is not a list or one of the items in {list} cannot
3041 be used as a Number this results in an error.
3042 An empty List results in zero.
3043
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 *mode()*
3045mode() Return a string that indicates the current mode:
3046 n Normal
3047 v Visual by character
3048 V Visual by line
3049 CTRL-V Visual blockwise
3050 s Select by character
3051 S Select by line
3052 CTRL-S Select blockwise
3053 i Insert
3054 R Replace
3055 c Command-line
3056 r Hit-enter prompt
3057 This is useful in the 'statusline' option. In most other
3058 places it always returns "c" or "n".
3059
3060nextnonblank({lnum}) *nextnonblank()*
3061 Return the line number of the first line at or below {lnum}
3062 that is not blank. Example: >
3063 if getline(nextnonblank(1)) =~ "Java"
3064< When {lnum} is invalid or there is no non-blank line at or
3065 below it, zero is returned.
3066 See also |prevnonblank()|.
3067
3068nr2char({expr}) *nr2char()*
3069 Return a string with a single character, which has the number
3070 value {expr}. Examples: >
3071 nr2char(64) returns "@"
3072 nr2char(32) returns " "
3073< The current 'encoding' is used. Example for "utf-8": >
3074 nr2char(300) returns I with bow character
3075< Note that a NUL character in the file is specified with
3076 nr2char(10), because NULs are represented with newline
3077 characters. nr2char(0) is a real NUL and terminates the
3078 string, thus isn't very useful.
3079
3080prevnonblank({lnum}) *prevnonblank()*
3081 Return the line number of the first line at or above {lnum}
3082 that is not blank. Example: >
3083 let ind = indent(prevnonblank(v:lnum - 1))
3084< When {lnum} is invalid or there is no non-blank line at or
3085 above it, zero is returned.
3086 Also see |nextnonblank()|.
3087
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003088 *E726* *E727*
Bram Moolenaard8b02732005-01-14 21:48:43 +00003089range({expr} [, {max} [, {stride}]]) *range()*
3090 Returns a List with Numbers:
3091 - If only {expr} is specified: [0, 1, ..., {expr} - 1]
3092 - If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
3093 - If {stride} is specified: [{expr}, {expr} + {stride}, ...,
3094 {max}] (increasing {expr} with {stride} each time, not
3095 producing a value past {max}).
3096 Examples: >
3097 range(4) " [0, 1, 2, 3]
3098 range(2, 4) " [2, 3, 4]
3099 range(2, 9, 3) " [2, 5, 8]
3100 range(2, -2, -1) " [2, 1, 0, -1, -2]
3101<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 *remote_expr()* *E449*
3103remote_expr({server}, {string} [, {idvar}])
3104 Send the {string} to {server}. The string is sent as an
3105 expression and the result is returned after evaluation.
3106 If {idvar} is present, it is taken as the name of a
3107 variable and a {serverid} for later use with
3108 remote_read() is stored there.
3109 See also |clientserver| |RemoteReply|.
3110 This function is not available in the |sandbox|.
3111 {only available when compiled with the |+clientserver| feature}
3112 Note: Any errors will cause a local error message to be issued
3113 and the result will be the empty string.
3114 Examples: >
3115 :echo remote_expr("gvim", "2+2")
3116 :echo remote_expr("gvim1", "b:current_syntax")
3117<
3118
3119remote_foreground({server}) *remote_foreground()*
3120 Move the Vim server with the name {server} to the foreground.
3121 This works like: >
3122 remote_expr({server}, "foreground()")
3123< Except that on Win32 systems the client does the work, to work
3124 around the problem that the OS doesn't always allow the server
3125 to bring itself to the foreground.
3126 This function is not available in the |sandbox|.
3127 {only in the Win32, Athena, Motif and GTK GUI versions and the
3128 Win32 console version}
3129
3130
3131remote_peek({serverid} [, {retvar}]) *remote_peek()*
3132 Returns a positive number if there are available strings
3133 from {serverid}. Copies any reply string into the variable
3134 {retvar} if specified. {retvar} must be a string with the
3135 name of a variable.
3136 Returns zero if none are available.
3137 Returns -1 if something is wrong.
3138 See also |clientserver|.
3139 This function is not available in the |sandbox|.
3140 {only available when compiled with the |+clientserver| feature}
3141 Examples: >
3142 :let repl = ""
3143 :echo "PEEK: ".remote_peek(id, "repl").": ".repl
3144
3145remote_read({serverid}) *remote_read()*
3146 Return the oldest available reply from {serverid} and consume
3147 it. It blocks until a reply is available.
3148 See also |clientserver|.
3149 This function is not available in the |sandbox|.
3150 {only available when compiled with the |+clientserver| feature}
3151 Example: >
3152 :echo remote_read(id)
3153<
3154 *remote_send()* *E241*
3155remote_send({server}, {string} [, {idvar}])
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003156 Send the {string} to {server}. The string is sent as input
3157 keys and the function returns immediately. At the Vim server
3158 the keys are not mapped |:map|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 If {idvar} is present, it is taken as the name of a
3160 variable and a {serverid} for later use with
3161 remote_read() is stored there.
3162 See also |clientserver| |RemoteReply|.
3163 This function is not available in the |sandbox|.
3164 {only available when compiled with the |+clientserver| feature}
3165 Note: Any errors will be reported in the server and may mess
3166 up the display.
3167 Examples: >
3168 :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
3169 \ remote_read(serverid)
3170
3171 :autocmd NONE RemoteReply *
3172 \ echo remote_read(expand("<amatch>"))
3173 :echo remote_send("gvim", ":sleep 10 | echo ".
3174 \ 'server2client(expand("<client>"), "HELLO")<CR>')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003175<
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003176remove({list}, {idx} [, {end}]) *remove()*
3177 Without {end}: Remove the item at {idx} from List {list} and
3178 return it.
3179 With {end}: Remove items from {idx} to {end} (inclusive) and
3180 return a list with these items. When {idx} points to the same
3181 item as {end} a list with one item is returned. When {end}
3182 points to an item before {idx} this is an error.
3183 See |list-index| for possible values of {idx} and {end}.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003184 Example: >
3185 :echo "last item: " . remove(mylist, -1)
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003186 :call remove(mylist, 0, 9)
Bram Moolenaard8b02732005-01-14 21:48:43 +00003187remove({dict}, {key})
3188 Remove the entry from {dict} with key {key}. Example: >
3189 :echo "removed " . remove(dict, "one")
3190< If there is no {key} in {dict} this is an error.
3191
3192 Use |delete()| to remove a file.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003193
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194rename({from}, {to}) *rename()*
3195 Rename the file by the name {from} to the name {to}. This
3196 should also work to move files across file systems. The
3197 result is a Number, which is 0 if the file was renamed
3198 successfully, and non-zero when the renaming failed.
3199 This function is not available in the |sandbox|.
3200
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003201repeat({expr}, {count}) *repeat()*
3202 Repeat {expr} {count} times and return the concatenated
3203 result. Example: >
3204 :let seperator = repeat('-', 80)
3205< When {count} is zero or negative the result is empty.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003206 When {expr} is a List the result is {expr} concatenated
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003207 {count} times. Example: >
3208 :let longlist = repeat(['a', 'b'], 3)
3209< Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003210
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003211
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212resolve({filename}) *resolve()* *E655*
3213 On MS-Windows, when {filename} is a shortcut (a .lnk file),
3214 returns the path the shortcut points to in a simplified form.
3215 On Unix, repeat resolving symbolic links in all path
3216 components of {filename} and return the simplified result.
3217 To cope with link cycles, resolving of symbolic links is
3218 stopped after 100 iterations.
3219 On other systems, return the simplified {filename}.
3220 The simplification step is done as by |simplify()|.
3221 resolve() keeps a leading path component specifying the
3222 current directory (provided the result is still a relative
3223 path name) and also keeps a trailing path separator.
3224
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003225 *reverse()*
3226reverse({list}) Reverse the order of items in {list} in-place. Returns
3227 {list}.
3228 If you want a list to remain unmodified make a copy first: >
3229 :let revlist = reverse(copy(mylist))
3230
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231search({pattern} [, {flags}]) *search()*
3232 Search for regexp pattern {pattern}. The search starts at the
3233 cursor position.
3234 {flags} is a String, which can contain these character flags:
3235 'b' search backward instead of forward
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003236 'n' do Not move the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 'w' wrap around the end of the file
3238 'W' don't wrap around the end of the file
3239 If neither 'w' or 'W' is given, the 'wrapscan' option applies.
3240
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003241 When a match has been found its line number is returned.
3242 The cursor will be positioned at the match, unless the 'n'
3243 flag is used).
3244 If there is no match a 0 is returned and the cursor doesn't
3245 move. No error message is given.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246
3247 Example (goes over all files in the argument list): >
3248 :let n = 1
3249 :while n <= argc() " loop over all files in arglist
3250 : exe "argument " . n
3251 : " start at the last char in the file and wrap for the
3252 : " first search to find match at start of file
3253 : normal G$
3254 : let flags = "w"
3255 : while search("foo", flags) > 0
3256 : s/foo/bar/g
3257 : let flags = "W"
3258 : endwhile
3259 : update " write the file if modified
3260 : let n = n + 1
3261 :endwhile
3262<
3263 *searchpair()*
3264searchpair({start}, {middle}, {end} [, {flags} [, {skip}]])
3265 Search for the match of a nested start-end pair. This can be
3266 used to find the "endif" that matches an "if", while other
3267 if/endif pairs in between are ignored.
3268 The search starts at the cursor. If a match is found, the
3269 cursor is positioned at it and the line number is returned.
3270 If no match is found 0 or -1 is returned and the cursor
3271 doesn't move. No error message is given.
3272
3273 {start}, {middle} and {end} are patterns, see |pattern|. They
3274 must not contain \( \) pairs. Use of \%( \) is allowed. When
3275 {middle} is not empty, it is found when searching from either
3276 direction, but only when not in a nested start-end pair. A
3277 typical use is: >
3278 searchpair('\<if\>', '\<else\>', '\<endif\>')
3279< By leaving {middle} empty the "else" is skipped.
3280
3281 {flags} are used like with |search()|. Additionally:
3282 'n' do Not move the cursor
3283 'r' Repeat until no more matches found; will find the
3284 outer pair
3285 'm' return number of Matches instead of line number with
3286 the match; will only be > 1 when 'r' is used.
3287
3288 When a match for {start}, {middle} or {end} is found, the
3289 {skip} expression is evaluated with the cursor positioned on
3290 the start of the match. It should return non-zero if this
3291 match is to be skipped. E.g., because it is inside a comment
3292 or a string.
3293 When {skip} is omitted or empty, every match is accepted.
3294 When evaluating {skip} causes an error the search is aborted
3295 and -1 returned.
3296
3297 The value of 'ignorecase' is used. 'magic' is ignored, the
3298 patterns are used like it's on.
3299
3300 The search starts exactly at the cursor. A match with
3301 {start}, {middle} or {end} at the next character, in the
3302 direction of searching, is the first one found. Example: >
3303 if 1
3304 if 2
3305 endif 2
3306 endif 1
3307< When starting at the "if 2", with the cursor on the "i", and
3308 searching forwards, the "endif 2" is found. When starting on
3309 the character just before the "if 2", the "endif 1" will be
3310 found. That's because the "if 2" will be found first, and
3311 then this is considered to be a nested if/endif from "if 2" to
3312 "endif 2".
3313 When searching backwards and {end} is more than one character,
3314 it may be useful to put "\zs" at the end of the pattern, so
3315 that when the cursor is inside a match with the end it finds
3316 the matching start.
3317
3318 Example, to find the "endif" command in a Vim script: >
3319
3320 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
3321 \ 'getline(".") =~ "^\\s*\""')
3322
3323< The cursor must be at or after the "if" for which a match is
3324 to be found. Note that single-quote strings are used to avoid
3325 having to double the backslashes. The skip expression only
3326 catches comments at the start of a line, not after a command.
3327 Also, a word "en" or "if" halfway a line is considered a
3328 match.
3329 Another example, to search for the matching "{" of a "}": >
3330
3331 :echo searchpair('{', '', '}', 'bW')
3332
3333< This works when the cursor is at or before the "}" for which a
3334 match is to be found. To reject matches that syntax
3335 highlighting recognized as strings: >
3336
3337 :echo searchpair('{', '', '}', 'bW',
3338 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
3339<
3340server2client( {clientid}, {string}) *server2client()*
3341 Send a reply string to {clientid}. The most recent {clientid}
3342 that sent a string can be retrieved with expand("<client>").
3343 {only available when compiled with the |+clientserver| feature}
3344 Note:
3345 This id has to be stored before the next command can be
3346 received. Ie. before returning from the received command and
3347 before calling any commands that waits for input.
3348 See also |clientserver|.
3349 Example: >
3350 :echo server2client(expand("<client>"), "HELLO")
3351<
3352serverlist() *serverlist()*
3353 Return a list of available server names, one per line.
3354 When there are no servers or the information is not available
3355 an empty string is returned. See also |clientserver|.
3356 {only available when compiled with the |+clientserver| feature}
3357 Example: >
3358 :echo serverlist()
3359<
3360setbufvar({expr}, {varname}, {val}) *setbufvar()*
3361 Set option or local variable {varname} in buffer {expr} to
3362 {val}.
3363 This also works for a global or local window option, but it
3364 doesn't work for a global or local window variable.
3365 For a local window option the global value is unchanged.
3366 For the use of {expr}, see |bufname()| above.
3367 Note that the variable name without "b:" must be used.
3368 Examples: >
3369 :call setbufvar(1, "&mod", 1)
3370 :call setbufvar("todo", "myvar", "foobar")
3371< This function is not available in the |sandbox|.
3372
3373setcmdpos({pos}) *setcmdpos()*
3374 Set the cursor position in the command line to byte position
3375 {pos}. The first position is 1.
3376 Use |getcmdpos()| to obtain the current position.
3377 Only works while editing the command line, thus you must use
Bram Moolenaard8b02732005-01-14 21:48:43 +00003378 |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
3379 |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
3380 set after the command line is set to the expression. For
3381 |c_CTRL-R_=| it is set after evaluating the expression but
3382 before inserting the resulting text.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 When the number is too big the cursor is put at the end of the
3384 line. A number smaller than one has undefined results.
3385 Returns 0 when successful, 1 when not editing the command
3386 line.
3387
3388setline({lnum}, {line}) *setline()*
3389 Set line {lnum} of the current buffer to {line}. If this
3390 succeeds, 0 is returned. If this fails (most likely because
3391 {lnum} is invalid) 1 is returned. Example: >
3392 :call setline(5, strftime("%c"))
3393< Note: The '[ and '] marks are not set.
3394
3395 *setreg()*
3396setreg({regname}, {value} [,{options}])
3397 Set the register {regname} to {value}.
3398 If {options} contains "a" or {regname} is upper case,
3399 then the value is appended.
3400 {options} can also contains a register type specification:
3401 "c" or "v" |characterwise| mode
3402 "l" or "V" |linewise| mode
3403 "b" or "<CTRL-V>" |blockwise-visual| mode
3404 If a number immediately follows "b" or "<CTRL-V>" then this is
3405 used as the width of the selection - if it is not specified
3406 then the width of the block is set to the number of characters
3407 in the longest line (counting a <TAB> as 1 character).
3408
3409 If {options} contains no register settings, then the default
3410 is to use character mode unless {value} ends in a <NL>.
3411 Setting the '=' register is not possible.
3412 Returns zero for success, non-zero for failure.
3413
3414 Examples: >
3415 :call setreg(v:register, @*)
3416 :call setreg('*', @%, 'ac')
3417 :call setreg('a', "1\n2\n3", 'b5')
3418
3419< This example shows using the functions to save and restore a
3420 register. >
3421 :let var_a = getreg('a')
3422 :let var_amode = getregtype('a')
3423 ....
3424 :call setreg('a', var_a, var_amode)
3425
3426< You can also change the type of a register by appending
3427 nothing: >
3428 :call setreg('a', '', 'al')
3429
3430setwinvar({nr}, {varname}, {val}) *setwinvar()*
3431 Set option or local variable {varname} in window {nr} to
3432 {val}.
3433 This also works for a global or local buffer option, but it
3434 doesn't work for a global or local buffer variable.
3435 For a local buffer option the global value is unchanged.
3436 Note that the variable name without "w:" must be used.
3437 Examples: >
3438 :call setwinvar(1, "&list", 0)
3439 :call setwinvar(2, "myvar", "foobar")
3440< This function is not available in the |sandbox|.
3441
3442simplify({filename}) *simplify()*
3443 Simplify the file name as much as possible without changing
3444 the meaning. Shortcuts (on MS-Windows) or symbolic links (on
3445 Unix) are not resolved. If the first path component in
3446 {filename} designates the current directory, this will be
3447 valid for the result as well. A trailing path separator is
3448 not removed either.
3449 Example: >
3450 simplify("./dir/.././/file/") == "./file/"
3451< Note: The combination "dir/.." is only removed if "dir" is
3452 a searchable directory or does not exist. On Unix, it is also
3453 removed when "dir" is a symbolic link within the same
3454 directory. In order to resolve all the involved symbolic
3455 links before simplifying the path name, use |resolve()|.
3456
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003457
Bram Moolenaar13065c42005-01-08 16:08:21 +00003458sort({list} [, {func}]) *sort()* *E702*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003459 Sort the items in {list} in-place. Returns {list}. If you
3460 want a list to remain unmodified make a copy first: >
3461 :let sortedlist = sort(copy(mylist))
3462< Uses the string representation of each item to sort on.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003463 Numbers sort after Strings, Lists after Numbers.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003464 When {func} is given and it is one then case is ignored.
3465 When {func} is a Funcref or a function name, this function is
3466 called to compare items. The function is invoked with two
3467 items as argument and must return zero if they are equal, 1 if
3468 the first one sorts after the second one, -1 if the first one
3469 sorts before the second one. Example: >
3470 func MyCompare(i1, i2)
3471 return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
3472 endfunc
3473 let sortedlist = sort(mylist, "MyCompare")
3474
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003475split({expr} [, {pattern}]) *split()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003476 Make a List out of {expr}. When {pattern} is omitted each
3477 white-separated sequence of characters becomes an item.
3478 Otherwise the string is split where {pattern} matches,
3479 removing the matched characters. Empty strings are omitted.
3480 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003481 :let words = split(getline('.'), '\W\+')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003482< Since empty strings are not added the "\+" isn't required but
3483 it makes the function work a bit faster.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003484 The opposite function is |join()|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003485
3486
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487strftime({format} [, {time}]) *strftime()*
3488 The result is a String, which is a formatted date and time, as
3489 specified by the {format} string. The given {time} is used,
3490 or the current time if no time is given. The accepted
3491 {format} depends on your system, thus this is not portable!
3492 See the manual page of the C function strftime() for the
3493 format. The maximum length of the result is 80 characters.
3494 See also |localtime()| and |getftime()|.
3495 The language can be changed with the |:language| command.
3496 Examples: >
3497 :echo strftime("%c") Sun Apr 27 11:49:23 1997
3498 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
3499 :echo strftime("%y%m%d %T") 970427 11:53:55
3500 :echo strftime("%H:%M") 11:55
3501 :echo strftime("%c", getftime("file.c"))
3502 Show mod time of file.c.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003503< Not available on all systems. To check use: >
3504 :if exists("*strftime")
3505
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506stridx({haystack}, {needle}) *stridx()*
3507 The result is a Number, which gives the index in {haystack} of
3508 the first occurrence of the String {needle} in the String
3509 {haystack}. The search is done case-sensitive. For advanced
3510 searches use |match()|.
3511 If the {needle} does not occur in {haystack} it returns -1.
3512 See also |strridx()|. Examples: >
3513 :echo stridx("An Example", "Example") 3
3514 :echo stridx("Starting point", "Start") 0
3515 :echo stridx("Starting point", "start") -1
3516<
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003517 *string()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003518string({expr}) Return {expr} converted to a String. If {expr} is a Number,
3519 String or a composition of them, then the result can be parsed
3520 back with |eval()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003521 {expr} type result ~
Bram Moolenaard8b02732005-01-14 21:48:43 +00003522 String 'string'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003523 Number 123
Bram Moolenaard8b02732005-01-14 21:48:43 +00003524 Funcref function('name')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003525 List [item, item]
Bram Moolenaard8b02732005-01-14 21:48:43 +00003526 Note that in String values the ' character is doubled.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003527
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 *strlen()*
3529strlen({expr}) The result is a Number, which is the length of the String
3530 {expr} in bytes. If you want to count the number of
3531 multi-byte characters use something like this: >
3532
3533 :let len = strlen(substitute(str, ".", "x", "g"))
3534
3535< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003536 If the argument is a Number it is first converted to a String.
3537 For other types an error is given.
3538 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539
3540strpart({src}, {start}[, {len}]) *strpart()*
3541 The result is a String, which is part of {src}, starting from
3542 byte {start}, with the length {len}.
3543 When non-existing bytes are included, this doesn't result in
3544 an error, the bytes are simply omitted.
3545 If {len} is missing, the copy continues from {start} till the
3546 end of the {src}. >
3547 strpart("abcdefg", 3, 2) == "de"
3548 strpart("abcdefg", -2, 4) == "ab"
3549 strpart("abcdefg", 5, 4) == "fg"
3550 strpart("abcdefg", 3) == "defg"
3551< Note: To get the first character, {start} must be 0. For
3552 example, to get three bytes under and after the cursor: >
3553 strpart(getline(line(".")), col(".") - 1, 3)
3554<
3555strridx({haystack}, {needle}) *strridx()*
3556 The result is a Number, which gives the index in {haystack} of
3557 the last occurrence of the String {needle} in the String
3558 {haystack}. The search is done case-sensitive. For advanced
3559 searches use |match()|.
3560 If the {needle} does not occur in {haystack} it returns -1.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003561 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 See also |stridx()|. Examples: >
3563 :echo strridx("an angry armadillo", "an") 3
3564<
3565strtrans({expr}) *strtrans()*
3566 The result is a String, which is {expr} with all unprintable
3567 characters translated into printable characters |'isprint'|.
3568 Like they are shown in a window. Example: >
3569 echo strtrans(@a)
3570< This displays a newline in register a as "^@" instead of
3571 starting a new line.
3572
3573submatch({nr}) *submatch()*
3574 Only for an expression in a |:substitute| command. Returns
3575 the {nr}'th submatch of the matched text. When {nr} is 0
3576 the whole matched text is returned.
3577 Example: >
3578 :s/\d\+/\=submatch(0) + 1/
3579< This finds the first number in the line and adds one to it.
3580 A line break is included as a newline character.
3581
3582substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
3583 The result is a String, which is a copy of {expr}, in which
3584 the first match of {pat} is replaced with {sub}. This works
3585 like the ":substitute" command (without any flags). But the
3586 matching with {pat} is always done like the 'magic' option is
3587 set and 'cpoptions' is empty (to make scripts portable).
3588 See |string-match| for how {pat} is used.
3589 And a "~" in {sub} is not replaced with the previous {sub}.
3590 Note that some codes in {sub} have a special meaning
3591 |sub-replace-special|. For example, to replace something with
3592 "\n" (two characters), use "\\\\n" or '\\n'.
3593 When {pat} does not match in {expr}, {expr} is returned
3594 unmodified.
3595 When {flags} is "g", all matches of {pat} in {expr} are
3596 replaced. Otherwise {flags} should be "".
3597 Example: >
3598 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
3599< This removes the last component of the 'path' option. >
3600 :echo substitute("testing", ".*", "\\U\\0", "")
3601< results in "TESTING".
3602
Bram Moolenaar47136d72004-10-12 20:02:24 +00003603synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00003605 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 The syntax ID can be used with |synIDattr()| and
3607 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00003608 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609 line.
3610 When {trans} is non-zero, transparent items are reduced to the
3611 item that they reveal. This is useful when wanting to know
3612 the effective color. When {trans} is zero, the transparent
3613 item is returned. This is useful when wanting to know which
3614 syntax item is effective (e.g. inside parens).
3615 Warning: This function can be very slow. Best speed is
3616 obtained by going through the file in forward direction.
3617
3618 Example (echoes the name of the syntax item under the cursor): >
3619 :echo synIDattr(synID(line("."), col("."), 1), "name")
3620<
3621synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
3622 The result is a String, which is the {what} attribute of
3623 syntax ID {synID}. This can be used to obtain information
3624 about a syntax item.
3625 {mode} can be "gui", "cterm" or "term", to get the attributes
3626 for that mode. When {mode} is omitted, or an invalid value is
3627 used, the attributes for the currently active highlighting are
3628 used (GUI, cterm or term).
3629 Use synIDtrans() to follow linked highlight groups.
3630 {what} result
3631 "name" the name of the syntax item
3632 "fg" foreground color (GUI: color name used to set
3633 the color, cterm: color number as a string,
3634 term: empty string)
3635 "bg" background color (like "fg")
3636 "fg#" like "fg", but for the GUI and the GUI is
3637 running the name in "#RRGGBB" form
3638 "bg#" like "fg#" for "bg"
3639 "bold" "1" if bold
3640 "italic" "1" if italic
3641 "reverse" "1" if reverse
3642 "inverse" "1" if inverse (= reverse)
3643 "underline" "1" if underlined
3644
3645 Example (echoes the color of the syntax item under the
3646 cursor): >
3647 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
3648<
3649synIDtrans({synID}) *synIDtrans()*
3650 The result is a Number, which is the translated syntax ID of
3651 {synID}. This is the syntax group ID of what is being used to
3652 highlight the character. Highlight links given with
3653 ":highlight link" are followed.
3654
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003655system({expr} [, {input}]) *system()* *E677*
3656 Get the output of the shell command {expr}.
3657 When {input} is given, this string is written to a file and
3658 passed as stdin to the command. The string is written as-is,
3659 you need to take care of using the correct line separators
3660 yourself.
3661 Note: newlines in {expr} may cause the command to fail. The
3662 characters in 'shellquote' and 'shellxquote' may also cause
3663 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 This is not to be used for interactive commands.
3665 The result is a String. Example: >
3666
3667 :let files = system("ls")
3668
3669< To make the result more system-independent, the shell output
3670 is filtered to replace <CR> with <NL> for Macintosh, and
3671 <CR><NL> with <NL> for DOS-like systems.
3672 The command executed is constructed using several options:
3673 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
3674 ({tmp} is an automatically generated file name).
3675 For Unix and OS/2 braces are put around {expr} to allow for
3676 concatenated commands.
3677
3678 The resulting error code can be found in |v:shell_error|.
3679 This function will fail in |restricted-mode|.
3680 Unlike ":!cmd" there is no automatic check for changed files.
3681 Use |:checktime| to force a check.
3682
3683tempname() *tempname()* *temp-file-name*
3684 The result is a String, which is the name of a file that
3685 doesn't exist. It can be used for a temporary file. The name
3686 is different for at least 26 consecutive calls. Example: >
3687 :let tmpfile = tempname()
3688 :exe "redir > " . tmpfile
3689< For Unix, the file will be in a private directory (only
3690 accessible by the current user) to avoid security problems
3691 (e.g., a symlink attack or other people reading your file).
3692 When Vim exits the directory and all files in it are deleted.
3693 For MS-Windows forward slashes are used when the 'shellslash'
3694 option is set or when 'shellcmdflag' starts with '-'.
3695
3696tolower({expr}) *tolower()*
3697 The result is a copy of the String given, with all uppercase
3698 characters turned into lowercase (just like applying |gu| to
3699 the string).
3700
3701toupper({expr}) *toupper()*
3702 The result is a copy of the String given, with all lowercase
3703 characters turned into uppercase (just like applying |gU| to
3704 the string).
3705
Bram Moolenaar8299df92004-07-10 09:47:34 +00003706tr({src}, {fromstr}, {tostr}) *tr()*
3707 The result is a copy of the {src} string with all characters
3708 which appear in {fromstr} replaced by the character in that
3709 position in the {tostr} string. Thus the first character in
3710 {fromstr} is translated into the first character in {tostr}
3711 and so on. Exactly like the unix "tr" command.
3712 This code also deals with multibyte characters properly.
3713
3714 Examples: >
3715 echo tr("hello there", "ht", "HT")
3716< returns "Hello THere" >
3717 echo tr("<blob>", "<>", "{}")
3718< returns "{blob}"
3719
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003720 *type()*
3721type({expr}) The result is a Number, depending on the type of {expr}:
3722 Number: 0
3723 String: 1
3724 Funcref: 2
3725 List: 3
3726 To avoid the magic numbers it can be used this way: >
3727 :if type(myvar) == type(0)
3728 :if type(myvar) == type("")
3729 :if type(myvar) == type(function("tr"))
3730 :if type(myvar) == type([])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731
3732virtcol({expr}) *virtcol()*
3733 The result is a Number, which is the screen column of the file
3734 position given with {expr}. That is, the last screen position
3735 occupied by the character at that position, when the screen
3736 would be of unlimited width. When there is a <Tab> at the
3737 position, the returned Number will be the column at the end of
3738 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
3739 set to 8, it returns 8.
3740 For the byte position use |col()|.
3741 When Virtual editing is active in the current mode, a position
3742 beyond the end of the line can be returned. |'virtualedit'|
3743 The accepted positions are:
3744 . the cursor position
3745 $ the end of the cursor line (the result is the
3746 number of displayed characters in the cursor line
3747 plus one)
3748 'x position of mark x (if the mark is not set, 0 is
3749 returned)
3750 Note that only marks in the current file can be used.
3751 Examples: >
3752 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
3753 virtcol("$") with text "foo^Lbar", returns 9
3754 virtcol("'t") with text " there", with 't at 'h', returns 6
3755< The first column is 1. 0 is returned for an error.
3756
3757visualmode([expr]) *visualmode()*
3758 The result is a String, which describes the last Visual mode
3759 used. Initially it returns an empty string, but once Visual
3760 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
3761 single CTRL-V character) for character-wise, line-wise, or
3762 block-wise Visual mode respectively.
3763 Example: >
3764 :exe "normal " . visualmode()
3765< This enters the same Visual mode as before. It is also useful
3766 in scripts if you wish to act differently depending on the
3767 Visual mode that was used.
3768
3769 If an expression is supplied that results in a non-zero number
3770 or a non-empty string, then the Visual mode will be cleared
3771 and the old value is returned. Note that " " and "0" are also
3772 non-empty strings, thus cause the mode to be cleared.
3773
3774 *winbufnr()*
3775winbufnr({nr}) The result is a Number, which is the number of the buffer
3776 associated with window {nr}. When {nr} is zero, the number of
3777 the buffer in the current window is returned. When window
3778 {nr} doesn't exist, -1 is returned.
3779 Example: >
3780 :echo "The file in the current window is " . bufname(winbufnr(0))
3781<
3782 *wincol()*
3783wincol() The result is a Number, which is the virtual column of the
3784 cursor in the window. This is counting screen cells from the
3785 left side of the window. The leftmost column is one.
3786
3787winheight({nr}) *winheight()*
3788 The result is a Number, which is the height of window {nr}.
3789 When {nr} is zero, the height of the current window is
3790 returned. When window {nr} doesn't exist, -1 is returned.
3791 An existing window always has a height of zero or more.
3792 Examples: >
3793 :echo "The current window has " . winheight(0) . " lines."
3794<
3795 *winline()*
3796winline() The result is a Number, which is the screen line of the cursor
3797 in the window. This is counting screen lines from the top of
3798 the window. The first line is one.
3799
3800 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003801winnr([{arg}]) The result is a Number, which is the number of the current
3802 window. The top window has number 1.
3803 When the optional argument is "$", the number of the
3804 last window is returnd (the window count).
3805 When the optional argument is "#", the number of the last
3806 accessed window is returned (where |CTRL-W_p| goes to).
3807 If there is no previous window 0 is returned.
3808 The number can be used with |CTRL-W_w| and ":wincmd w"
3809 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810
3811 *winrestcmd()*
3812winrestcmd() Returns a sequence of |:resize| commands that should restore
3813 the current window sizes. Only works properly when no windows
3814 are opened or closed and the current window is unchanged.
3815 Example: >
3816 :let cmd = winrestcmd()
3817 :call MessWithWindowSizes()
3818 :exe cmd
3819
3820winwidth({nr}) *winwidth()*
3821 The result is a Number, which is the width of window {nr}.
3822 When {nr} is zero, the width of the current window is
3823 returned. When window {nr} doesn't exist, -1 is returned.
3824 An existing window always has a width of zero or more.
3825 Examples: >
3826 :echo "The current window has " . winwidth(0) . " columns."
3827 :if winwidth(0) <= 50
3828 : exe "normal 50\<C-W>|"
3829 :endif
3830<
3831
3832 *feature-list*
3833There are three types of features:
38341. Features that are only supported when they have been enabled when Vim
3835 was compiled |+feature-list|. Example: >
3836 :if has("cindent")
38372. Features that are only supported when certain conditions have been met.
3838 Example: >
3839 :if has("gui_running")
3840< *has-patch*
38413. Included patches. First check |v:version| for the version of Vim.
3842 Then the "patch123" feature means that patch 123 has been included for
3843 this version. Example (checking version 6.2.148 or later): >
3844 :if v:version > 602 || v:version == 602 && has("patch148")
3845
3846all_builtin_terms Compiled with all builtin terminals enabled.
3847amiga Amiga version of Vim.
3848arabic Compiled with Arabic support |Arabic|.
3849arp Compiled with ARP support (Amiga).
3850autocmd Compiled with autocommands support.
3851balloon_eval Compiled with |balloon-eval| support.
3852beos BeOS version of Vim.
3853browse Compiled with |:browse| support, and browse() will
3854 work.
3855builtin_terms Compiled with some builtin terminals.
3856byte_offset Compiled with support for 'o' in 'statusline'
3857cindent Compiled with 'cindent' support.
3858clientserver Compiled with remote invocation support |clientserver|.
3859clipboard Compiled with 'clipboard' support.
3860cmdline_compl Compiled with |cmdline-completion| support.
3861cmdline_hist Compiled with |cmdline-history| support.
3862cmdline_info Compiled with 'showcmd' and 'ruler' support.
3863comments Compiled with |'comments'| support.
3864cryptv Compiled with encryption support |encryption|.
3865cscope Compiled with |cscope| support.
3866compatible Compiled to be very Vi compatible.
3867debug Compiled with "DEBUG" defined.
3868dialog_con Compiled with console dialog support.
3869dialog_gui Compiled with GUI dialog support.
3870diff Compiled with |vimdiff| and 'diff' support.
3871digraphs Compiled with support for digraphs.
3872dnd Compiled with support for the "~ register |quote_~|.
3873dos32 32 bits DOS (DJGPP) version of Vim.
3874dos16 16 bits DOS version of Vim.
3875ebcdic Compiled on a machine with ebcdic character set.
3876emacs_tags Compiled with support for Emacs tags.
3877eval Compiled with expression evaluation support. Always
3878 true, of course!
3879ex_extra Compiled with extra Ex commands |+ex_extra|.
3880extra_search Compiled with support for |'incsearch'| and
3881 |'hlsearch'|
3882farsi Compiled with Farsi support |farsi|.
3883file_in_path Compiled with support for |gf| and |<cfile>|
3884find_in_path Compiled with support for include file searches
3885 |+find_in_path|.
3886fname_case Case in file names matters (for Amiga, MS-DOS, and
3887 Windows this is not present).
3888folding Compiled with |folding| support.
3889footer Compiled with GUI footer support. |gui-footer|
3890fork Compiled to use fork()/exec() instead of system().
3891gettext Compiled with message translation |multi-lang|
3892gui Compiled with GUI enabled.
3893gui_athena Compiled with Athena GUI.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003894gui_beos Compiled with BeOS GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895gui_gtk Compiled with GTK+ GUI (any version).
3896gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00003897gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898gui_mac Compiled with Macintosh GUI.
3899gui_motif Compiled with Motif GUI.
3900gui_photon Compiled with Photon GUI.
3901gui_win32 Compiled with MS Windows Win32 GUI.
3902gui_win32s idem, and Win32s system being used (Windows 3.1)
3903gui_running Vim is running in the GUI, or it will start soon.
3904hangul_input Compiled with Hangul input support. |hangul|
3905iconv Can use iconv() for conversion.
3906insert_expand Compiled with support for CTRL-X expansion commands in
3907 Insert mode.
3908jumplist Compiled with |jumplist| support.
3909keymap Compiled with 'keymap' support.
3910langmap Compiled with 'langmap' support.
3911libcall Compiled with |libcall()| support.
3912linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
3913 support.
3914lispindent Compiled with support for lisp indenting.
3915listcmds Compiled with commands for the buffer list |:files|
3916 and the argument list |arglist|.
3917localmap Compiled with local mappings and abbr. |:map-local|
3918mac Macintosh version of Vim.
3919macunix Macintosh version of Vim, using Unix files (OS-X).
3920menu Compiled with support for |:menu|.
3921mksession Compiled with support for |:mksession|.
3922modify_fname Compiled with file name modifiers. |filename-modifiers|
3923mouse Compiled with support mouse.
3924mouseshape Compiled with support for 'mouseshape'.
3925mouse_dec Compiled with support for Dec terminal mouse.
3926mouse_gpm Compiled with support for gpm (Linux console mouse)
3927mouse_netterm Compiled with support for netterm mouse.
3928mouse_pterm Compiled with support for qnx pterm mouse.
3929mouse_xterm Compiled with support for xterm mouse.
3930multi_byte Compiled with support for editing Korean et al.
3931multi_byte_ime Compiled with support for IME input method.
3932multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00003933mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00003935netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936ole Compiled with OLE automation support for Win32.
3937os2 OS/2 version of Vim.
3938osfiletype Compiled with support for osfiletypes |+osfiletype|
3939path_extra Compiled with up/downwards search in 'path' and 'tags'
3940perl Compiled with Perl interface.
3941postscript Compiled with PostScript file printing.
3942printer Compiled with |:hardcopy| support.
3943python Compiled with Python interface.
3944qnx QNX version of Vim.
3945quickfix Compiled with |quickfix| support.
3946rightleft Compiled with 'rightleft' support.
3947ruby Compiled with Ruby interface |ruby|.
3948scrollbind Compiled with 'scrollbind' support.
3949showcmd Compiled with 'showcmd' support.
3950signs Compiled with |:sign| support.
3951smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003952sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953statusline Compiled with support for 'statusline', 'rulerformat'
3954 and special formats of 'titlestring' and 'iconstring'.
3955sun_workshop Compiled with support for Sun |workshop|.
3956syntax Compiled with syntax highlighting support.
3957syntax_items There are active syntax highlighting items for the
3958 current buffer.
3959system Compiled to use system() instead of fork()/exec().
3960tag_binary Compiled with binary searching in tags files
3961 |tag-binary-search|.
3962tag_old_static Compiled with support for old static tags
3963 |tag-old-static|.
3964tag_any_white Compiled with support for any white characters in tags
3965 files |tag-any-white|.
3966tcl Compiled with Tcl interface.
3967terminfo Compiled with terminfo instead of termcap.
3968termresponse Compiled with support for |t_RV| and |v:termresponse|.
3969textobjects Compiled with support for |text-objects|.
3970tgetent Compiled with tgetent support, able to use a termcap
3971 or terminfo file.
3972title Compiled with window title support |'title'|.
3973toolbar Compiled with support for |gui-toolbar|.
3974unix Unix version of Vim.
3975user_commands User-defined commands.
3976viminfo Compiled with viminfo support.
3977vim_starting True while initial source'ing takes place.
3978vertsplit Compiled with vertically split windows |:vsplit|.
3979virtualedit Compiled with 'virtualedit' option.
3980visual Compiled with Visual mode.
3981visualextra Compiled with extra Visual mode commands.
3982 |blockwise-operators|.
3983vms VMS version of Vim.
3984vreplace Compiled with |gR| and |gr| commands.
3985wildignore Compiled with 'wildignore' option.
3986wildmenu Compiled with 'wildmenu' option.
3987windows Compiled with support for more than one window.
3988winaltkeys Compiled with 'winaltkeys' option.
3989win16 Win16 version of Vim (MS-Windows 3.1).
3990win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
3991win64 Win64 version of Vim (MS-Windows 64 bit).
3992win32unix Win32 version of Vim, using Unix files (Cygwin)
3993win95 Win32 version for MS-Windows 95/98/ME.
3994writebackup Compiled with 'writebackup' default on.
3995xfontset Compiled with X fontset support |xfontset|.
3996xim Compiled with X input method support |xim|.
3997xsmp Compiled with X session management support.
3998xsmp_interact Compiled with interactive X session management support.
3999xterm_clipboard Compiled with support for xterm clipboard.
4000xterm_save Compiled with support for saving and restoring the
4001 xterm screen.
4002x11 Compiled with X11 support.
4003
4004 *string-match*
4005Matching a pattern in a String
4006
4007A regexp pattern as explained at |pattern| is normally used to find a match in
4008the buffer lines. When a pattern is used to find a match in a String, almost
4009everything works in the same way. The difference is that a String is handled
4010like it is one line. When it contains a "\n" character, this is not seen as a
4011line break for the pattern. It can be matched with a "\n" in the pattern, or
4012with ".". Example: >
4013 :let a = "aaaa\nxxxx"
4014 :echo matchstr(a, "..\n..")
4015 aa
4016 xx
4017 :echo matchstr(a, "a.x")
4018 a
4019 x
4020
4021Don't forget that "^" will only match at the first character of the String and
4022"$" at the last character of the string. They don't match after or before a
4023"\n".
4024
4025==============================================================================
40265. Defining functions *user-functions*
4027
4028New functions can be defined. These can be called just like builtin
4029functions. The function executes a sequence of Ex commands. Normal mode
4030commands can be executed with the |:normal| command.
4031
4032The function name must start with an uppercase letter, to avoid confusion with
4033builtin functions. To prevent from using the same name in different scripts
4034avoid obvious, short names. A good habit is to start the function name with
4035the name of the script, e.g., "HTMLcolor()".
4036
4037It's also possible to use curly braces, see |curly-braces-names|.
4038
4039 *local-function*
4040A function local to a script must start with "s:". A local script function
4041can only be called from within the script and from functions, user commands
4042and autocommands defined in the script. It is also possible to call the
4043function from a mappings defined in the script, but then |<SID>| must be used
4044instead of "s:" when the mapping is expanded outside of the script.
4045
4046 *:fu* *:function* *E128* *E129* *E123*
4047:fu[nction] List all functions and their arguments.
4048
4049:fu[nction] {name} List function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004050 {name} can also be a Dictionary entry that is a
4051 Funcref: >
4052 :function dict.init
4053< *E124* *E125*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004054:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 Define a new function by the name {name}. The name
4056 must be made of alphanumeric characters and '_', and
4057 must start with a capital or "s:" (see above).
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004058
4059 {name} can also be a Dictionary entry that is a
4060 Funcref: >
4061 :function dict.init(arg)
4062< "dict" must be an existing dictionary. The entry
4063 "init" is added if it didn't exist yet. Otherwise [!]
4064 is required to overwrite an existing function. The
4065 result is a |Funcref| to a numbered function. The
4066 function can only be used with a |Funcref| and will be
4067 deleted if there are no more references to it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 *function-argument* *a:var*
4069 An argument can be defined by giving its name. In the
4070 function this can then be used as "a:name" ("a:" for
4071 argument).
4072 Up to 20 arguments can be given, separated by commas.
4073 Finally, an argument "..." can be specified, which
4074 means that more arguments may be following. In the
4075 function they can be used as "a:1", "a:2", etc. "a:0"
4076 is set to the number of extra arguments (which can be
4077 0).
4078 When not using "...", the number of arguments in a
4079 function call must be equal to the number of named
4080 arguments. When using "...", the number of arguments
4081 may be larger.
4082 It is also possible to define a function without any
4083 arguments. You must still supply the () then.
4084 The body of the function follows in the next lines,
4085 until the matching |:endfunction|. It is allowed to
4086 define another function inside a function body.
4087 *E127* *E122*
4088 When a function by this name already exists and [!] is
4089 not used an error message is given. When [!] is used,
4090 an existing function is silently replaced. Unless it
4091 is currently being executed, that is an error.
4092 *a:firstline* *a:lastline*
4093 When the [range] argument is added, the function is
4094 expected to take care of a range itself. The range is
4095 passed as "a:firstline" and "a:lastline". If [range]
4096 is excluded, ":{range}call" will call the function for
4097 each line in the range, with the cursor on the start
4098 of each line. See |function-range-example|.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004099
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 When the [abort] argument is added, the function will
4101 abort as soon as an error is detected.
4102 The last used search pattern and the redo command "."
4103 will not be changed by the function.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004104
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004105 When the [dict] argument is added, the function must
4106 be invoked through an entry in a Dictionary. The
4107 local variable "self" will then be set to the
4108 dictionary. See |Dictionary-function|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109
4110 *:endf* *:endfunction* *E126* *E193*
4111:endf[unction] The end of a function definition. Must be on a line
4112 by its own, without other commands.
4113
4114 *:delf* *:delfunction* *E130* *E131*
4115:delf[unction] {name} Delete function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004116 {name} can also be a Dictionary entry that is a
4117 Funcref: >
4118 :delfunc dict.init
4119< This will remove the "init" entry from "dict". The
4120 function is deleted if there are no more references to
4121 it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 *:retu* *:return* *E133*
4123:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
4124 evaluated and returned as the result of the function.
4125 If "[expr]" is not given, the number 0 is returned.
4126 When a function ends without an explicit ":return",
4127 the number 0 is returned.
4128 Note that there is no check for unreachable lines,
4129 thus there is no warning if commands follow ":return".
4130
4131 If the ":return" is used after a |:try| but before the
4132 matching |:finally| (if present), the commands
4133 following the ":finally" up to the matching |:endtry|
4134 are executed first. This process applies to all
4135 nested ":try"s inside the function. The function
4136 returns at the outermost ":endtry".
4137
4138
4139Inside a function variables can be used. These are local variables, which
4140will disappear when the function returns. Global variables need to be
4141accessed with "g:".
4142
4143Example: >
4144 :function Table(title, ...)
4145 : echohl Title
4146 : echo a:title
4147 : echohl None
4148 : let idx = 1
4149 : while idx <= a:0
4150 : echo a:{idx} . ' '
4151 : let idx = idx + 1
4152 : endwhile
4153 : return idx
4154 :endfunction
4155
4156This function can then be called with: >
4157 let lines = Table("Table", "line1", "line2")
4158 let lines = Table("Empty Table")
4159
4160To return more than one value, pass the name of a global variable: >
4161 :function Compute(n1, n2, divname)
4162 : if a:n2 == 0
4163 : return "fail"
4164 : endif
4165 : let g:{a:divname} = a:n1 / a:n2
4166 : return "ok"
4167 :endfunction
4168
4169This function can then be called with: >
4170 :let success = Compute(13, 1324, "div")
4171 :if success == "ok"
4172 : echo div
4173 :endif
4174
4175An alternative is to return a command that can be executed. This also works
4176with local variables in a calling function. Example: >
4177 :function Foo()
4178 : execute Bar()
4179 : echo "line " . lnum . " column " . col
4180 :endfunction
4181
4182 :function Bar()
4183 : return "let lnum = " . line(".") . " | let col = " . col(".")
4184 :endfunction
4185
4186The names "lnum" and "col" could also be passed as argument to Bar(), to allow
4187the caller to set the names.
4188
4189 *:cal* *:call* *E107*
4190:[range]cal[l] {name}([arguments])
4191 Call a function. The name of the function and its arguments
4192 are as specified with |:function|. Up to 20 arguments can be
4193 used.
4194 Without a range and for functions that accept a range, the
4195 function is called once. When a range is given the cursor is
4196 positioned at the start of the first line before executing the
4197 function.
4198 When a range is given and the function doesn't handle it
4199 itself, the function is executed for each line in the range,
4200 with the cursor in the first column of that line. The cursor
4201 is left at the last line (possibly moved by the last function
4202 call). The arguments are re-evaluated for each line. Thus
4203 this works:
4204 *function-range-example* >
4205 :function Mynumber(arg)
4206 : echo line(".") . " " . a:arg
4207 :endfunction
4208 :1,5call Mynumber(getline("."))
4209<
4210 The "a:firstline" and "a:lastline" are defined anyway, they
4211 can be used to do something different at the start or end of
4212 the range.
4213
4214 Example of a function that handles the range itself: >
4215
4216 :function Cont() range
4217 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
4218 :endfunction
4219 :4,8call Cont()
4220<
4221 This function inserts the continuation character "\" in front
4222 of all the lines in the range, except the first one.
4223
4224 *E132*
4225The recursiveness of user functions is restricted with the |'maxfuncdepth'|
4226option.
4227
4228 *autoload-functions*
4229When using many or large functions, it's possible to automatically define them
4230only when they are used. Use the FuncUndefined autocommand event with a
4231pattern that matches the function(s) to be defined. Example: >
4232
4233 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
4234
4235The file "~/vim/bufnetfuncs.vim" should then define functions that start with
4236"BufNet". Also see |FuncUndefined|.
4237
4238==============================================================================
42396. Curly braces names *curly-braces-names*
4240
4241Wherever you can use a variable, you can use a "curly braces name" variable.
4242This is a regular variable name with one or more expressions wrapped in braces
4243{} like this: >
4244 my_{adjective}_variable
4245
4246When Vim encounters this, it evaluates the expression inside the braces, puts
4247that in place of the expression, and re-interprets the whole as a variable
4248name. So in the above example, if the variable "adjective" was set to
4249"noisy", then the reference would be to "my_noisy_variable", whereas if
4250"adjective" was set to "quiet", then it would be to "my_quiet_variable".
4251
4252One application for this is to create a set of variables governed by an option
4253value. For example, the statement >
4254 echo my_{&background}_message
4255
4256would output the contents of "my_dark_message" or "my_light_message" depending
4257on the current value of 'background'.
4258
4259You can use multiple brace pairs: >
4260 echo my_{adverb}_{adjective}_message
4261..or even nest them: >
4262 echo my_{ad{end_of_word}}_message
4263where "end_of_word" is either "verb" or "jective".
4264
4265However, the expression inside the braces must evaluate to a valid single
4266variable name. e.g. this is invalid: >
4267 :let foo='a + b'
4268 :echo c{foo}d
4269.. since the result of expansion is "ca + bd", which is not a variable name.
4270
4271 *curly-braces-function-names*
4272You can call and define functions by an evaluated name in a similar way.
4273Example: >
4274 :let func_end='whizz'
4275 :call my_func_{func_end}(parameter)
4276
4277This would call the function "my_func_whizz(parameter)".
4278
4279==============================================================================
42807. Commands *expression-commands*
4281
4282:let {var-name} = {expr1} *:let* *E18*
4283 Set internal variable {var-name} to the result of the
4284 expression {expr1}. The variable will get the type
4285 from the {expr}. If {var-name} didn't exist yet, it
4286 is created.
4287
Bram Moolenaar13065c42005-01-08 16:08:21 +00004288:let {var-name}[{idx}] = {expr1} *E689*
4289 Set a list item to the result of the expression
4290 {expr1}. {var-name} must refer to a list and {idx}
4291 must be a valid index in that list. For nested list
4292 the index can be repeated.
4293 This cannot be used to add an item to a list.
4294
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004295 *E711* *E719*
4296:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004297 Set a sequence of items in a List to the result of the
4298 expression {expr1}, which must be a list with the
4299 correct number of items.
4300 {idx1} can be omitted, zero is used instead.
4301 {idx2} can be omitted, meaning the end of the list.
4302 When the selected range of items is partly past the
4303 end of the list, items will be added.
4304
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004305:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
4306:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
4307:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
4308 These fail if {var} was not set yet and when the type
4309 of {var} and {expr1} don't fit the operator.
4310
4311
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312:let ${env-name} = {expr1} *:let-environment* *:let-$*
4313 Set environment variable {env-name} to the result of
4314 the expression {expr1}. The type is always String.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004315:let ${env-name} .= {expr1}
4316 Append {expr1} to the environment variable {env-name}.
4317 If the environment variable didn't exist yet this
4318 works like "=".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319
4320:let @{reg-name} = {expr1} *:let-register* *:let-@*
4321 Write the result of the expression {expr1} in register
4322 {reg-name}. {reg-name} must be a single letter, and
4323 must be the name of a writable register (see
4324 |registers|). "@@" can be used for the unnamed
4325 register, "@/" for the search pattern.
4326 If the result of {expr1} ends in a <CR> or <NL>, the
4327 register will be linewise, otherwise it will be set to
4328 characterwise.
4329 This can be used to clear the last search pattern: >
4330 :let @/ = ""
4331< This is different from searching for an empty string,
4332 that would match everywhere.
4333
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004334:let @{reg-name} .= {expr1}
4335 Append {expr1} to register {reg-name}. If the
4336 register was empty it's like setting it to {expr1}.
4337
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338:let &{option-name} = {expr1} *:let-option* *:let-star*
4339 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004340 expression {expr1}. A String or Number value is
4341 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 For an option local to a window or buffer the effect
4343 is just like using the |:set| command: both the local
4344 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004345 Example: >
4346 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004348:let &{option-name} .= {expr1}
4349 For a string option: Append {expr1} to the value.
4350 Does not insert a comma like |:set+=|.
4351
4352:let &{option-name} += {expr1}
4353:let &{option-name} -= {expr1}
4354 For a number or boolean option: Add or subtract
4355 {expr1}.
4356
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357:let &l:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004358:let &l:{option-name} .= {expr1}
4359:let &l:{option-name} += {expr1}
4360:let &l:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361 Like above, but only set the local value of an option
4362 (if there is one). Works like |:setlocal|.
4363
4364:let &g:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004365:let &g:{option-name} .= {expr1}
4366:let &g:{option-name} += {expr1}
4367:let &g:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 Like above, but only set the global value of an option
4369 (if there is one). Works like |:setglobal|.
4370
Bram Moolenaar13065c42005-01-08 16:08:21 +00004371:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004372 {expr1} must evaluate to a List. The first item in
4373 the list is assigned to {name1}, the second item to
4374 {name2}, etc.
4375 The number of names must match the number of items in
4376 the List.
4377 Each name can be one of the items of the ":let"
4378 command as mentioned above.
4379 Example: >
4380 :let [s, item] = GetItem(s)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004381< Detail: {expr1} is evaluated first, then the
4382 assignments are done in sequence. This matters if
4383 {name2} depends on {name1}. Example: >
4384 :let x = [0, 1]
4385 :let i = 0
4386 :let [i, x[i]] = [1, 2]
4387 :echo x
4388< The result is [0, 2].
4389
4390:let [{name1}, {name2}, ...] .= {expr1}
4391:let [{name1}, {name2}, ...] += {expr1}
4392:let [{name1}, {name2}, ...] -= {expr1}
4393 Like above, but append/add/subtract the value for each
4394 List item.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004395
4396:let [{name}, ..., ; {lastname}] = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004397 Like |let-unpack| above, but the List may have more
4398 items than there are names. A list of the remaining
4399 items is assigned to {lastname}. If there are no
4400 remaining items {lastname} is set to an empty list.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004401 Example: >
4402 :let [a, b; rest] = ["aval", "bval", 3, 4]
4403<
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004404:let [{name}, ..., ; {lastname}] .= {expr1}
4405:let [{name}, ..., ; {lastname}] += {expr1}
4406:let [{name}, ..., ; {lastname}] -= {expr1}
4407 Like above, but append/add/subtract the value for each
4408 List item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 *E106*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004410:let {var-name} .. List the value of variable {var-name}. Multiple
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 variable names may be given.
4412
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00004413:let List the values of all variables. The type of the
4414 variable is indicated before the value:
4415 <nothing> String
4416 # Number
4417 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418
4419 *:unlet* *:unl* *E108*
4420:unl[et][!] {var-name} ...
4421 Remove the internal variable {var-name}. Several
4422 variable names can be given, they are all removed.
4423 With [!] no error message is given for non-existing
4424 variables.
Bram Moolenaar9cd15162005-01-16 22:02:49 +00004425 One or more items from a List can be removed: >
4426 :unlet list[3] " remove fourth item
4427 :unlet list[3:] " remove fourth item to last
4428< One item from a Dictionary can be removed at a time: >
4429 :unlet dict['two']
4430 :unlet dict.two
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431
4432:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
4433:en[dif] Execute the commands until the next matching ":else"
4434 or ":endif" if {expr1} evaluates to non-zero.
4435
4436 From Vim version 4.5 until 5.0, every Ex command in
4437 between the ":if" and ":endif" is ignored. These two
4438 commands were just to allow for future expansions in a
4439 backwards compatible way. Nesting was allowed. Note
4440 that any ":else" or ":elseif" was ignored, the "else"
4441 part was not executed either.
4442
4443 You can use this to remain compatible with older
4444 versions: >
4445 :if version >= 500
4446 : version-5-specific-commands
4447 :endif
4448< The commands still need to be parsed to find the
4449 "endif". Sometimes an older Vim has a problem with a
4450 new command. For example, ":silent" is recognized as
4451 a ":substitute" command. In that case ":execute" can
4452 avoid problems: >
4453 :if version >= 600
4454 : execute "silent 1,$delete"
4455 :endif
4456<
4457 NOTE: The ":append" and ":insert" commands don't work
4458 properly in between ":if" and ":endif".
4459
4460 *:else* *:el* *E581* *E583*
4461:el[se] Execute the commands until the next matching ":else"
4462 or ":endif" if they previously were not being
4463 executed.
4464
4465 *:elseif* *:elsei* *E582* *E584*
4466:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
4467 is no extra ":endif".
4468
4469:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004470 *E170* *E585* *E588* *E733*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471:endw[hile] Repeat the commands between ":while" and ":endwhile",
4472 as long as {expr1} evaluates to non-zero.
4473 When an error is detected from a command inside the
4474 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00004475 Example: >
4476 :let lnum = 1
4477 :while lnum <= line("$")
4478 :call FixLine(lnum)
4479 :let lnum = lnum + 1
4480 :endwhile
4481<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00004483 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004485:for {var} in {list} *:for* *E690* *E732*
Bram Moolenaar12805862005-01-05 22:16:17 +00004486:endfo[r] *:endfo* *:endfor*
4487 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004488 each item in {list}. variable {var} is set to the
4489 value of each item.
4490 When an error is detected for a command inside the
Bram Moolenaar12805862005-01-05 22:16:17 +00004491 loop, execution continues after the "endfor".
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004492 Changing {list} affects what items are used. Make a
4493 copy if this is unwanted: >
4494 :for item in copy(mylist)
4495< When not making a copy, Vim stores a reference to the
4496 next item in the list, before executing the commands
4497 with the current item. Thus the current item can be
4498 removed without effect. Removing any later item means
4499 it will not be found. Thus the following example
4500 works (an inefficient way to make a list empty): >
4501 :for item in mylist
Bram Moolenaar12805862005-01-05 22:16:17 +00004502 :call remove(mylist, 0)
4503 :endfor
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004504< Note that reordering the list (e.g., with sort() or
4505 reverse()) may have unexpected effects.
4506 Note that the type of each list item should be
Bram Moolenaar12805862005-01-05 22:16:17 +00004507 identical to avoid errors for the type of {var}
4508 changing. Unlet the variable at the end of the loop
4509 to allow multiple item types.
4510
4511:for {var} in {string}
4512:endfo[r] Like ":for" above, but use each character in {string}
4513 as a list item.
4514 Composing characters are used as separate characters.
4515 A Number is first converted to a String.
4516
4517:for [{var1}, {var2}, ...] in {listlist}
4518:endfo[r]
4519 Like ":for" above, but each item in {listlist} must be
4520 a list, of which each item is assigned to {var1},
4521 {var2}, etc. Example: >
4522 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
4523 :echo getline(lnum)[col]
4524 :endfor
4525<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00004527:con[tinue] When used inside a ":while" or ":for" loop, jumps back
4528 to the start of the loop.
4529 If it is used after a |:try| inside the loop but
4530 before the matching |:finally| (if present), the
4531 commands following the ":finally" up to the matching
4532 |:endtry| are executed first. This process applies to
4533 all nested ":try"s inside the loop. The outermost
4534 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535
4536 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00004537:brea[k] When used inside a ":while" or ":for" loop, skips to
4538 the command after the matching ":endwhile" or
4539 ":endfor".
4540 If it is used after a |:try| inside the loop but
4541 before the matching |:finally| (if present), the
4542 commands following the ":finally" up to the matching
4543 |:endtry| are executed first. This process applies to
4544 all nested ":try"s inside the loop. The outermost
4545 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546
4547:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
4548:endt[ry] Change the error handling for the commands between
4549 ":try" and ":endtry" including everything being
4550 executed across ":source" commands, function calls,
4551 or autocommand invocations.
4552
4553 When an error or interrupt is detected and there is
4554 a |:finally| command following, execution continues
4555 after the ":finally". Otherwise, or when the
4556 ":endtry" is reached thereafter, the next
4557 (dynamically) surrounding ":try" is checked for
4558 a corresponding ":finally" etc. Then the script
4559 processing is terminated. (Whether a function
4560 definition has an "abort" argument does not matter.)
4561 Example: >
4562 :try | edit too much | finally | echo "cleanup" | endtry
4563 :echo "impossible" " not reached, script terminated above
4564<
4565 Moreover, an error or interrupt (dynamically) inside
4566 ":try" and ":endtry" is converted to an exception. It
4567 can be caught as if it were thrown by a |:throw|
4568 command (see |:catch|). In this case, the script
4569 processing is not terminated.
4570
4571 The value "Vim:Interrupt" is used for an interrupt
4572 exception. An error in a Vim command is converted
4573 to a value of the form "Vim({command}):{errmsg}",
4574 other errors are converted to a value of the form
4575 "Vim:{errmsg}". {command} is the full command name,
4576 and {errmsg} is the message that is displayed if the
4577 error exception is not caught, always beginning with
4578 the error number.
4579 Examples: >
4580 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
4581 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
4582<
4583 *:cat* *:catch* *E603* *E604* *E605*
4584:cat[ch] /{pattern}/ The following commands until the next ":catch",
4585 |:finally|, or |:endtry| that belongs to the same
4586 |:try| as the ":catch" are executed when an exception
4587 matching {pattern} is being thrown and has not yet
4588 been caught by a previous ":catch". Otherwise, these
4589 commands are skipped.
4590 When {pattern} is omitted all errors are caught.
4591 Examples: >
4592 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
4593 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
4594 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
4595 :catch /^Vim(write):/ " catch all errors in :write
4596 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
4597 :catch /my-exception/ " catch user exception
4598 :catch /.*/ " catch everything
4599 :catch " same as /.*/
4600<
4601 Another character can be used instead of / around the
4602 {pattern}, so long as it does not have a special
4603 meaning (e.g., '|' or '"') and doesn't occur inside
4604 {pattern}.
4605 NOTE: It is not reliable to ":catch" the TEXT of
4606 an error message because it may vary in different
4607 locales.
4608
4609 *:fina* *:finally* *E606* *E607*
4610:fina[lly] The following commands until the matching |:endtry|
4611 are executed whenever the part between the matching
4612 |:try| and the ":finally" is left: either by falling
4613 through to the ":finally" or by a |:continue|,
4614 |:break|, |:finish|, or |:return|, or by an error or
4615 interrupt or exception (see |:throw|).
4616
4617 *:th* *:throw* *E608*
4618:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
4619 If the ":throw" is used after a |:try| but before the
4620 first corresponding |:catch|, commands are skipped
4621 until the first ":catch" matching {expr1} is reached.
4622 If there is no such ":catch" or if the ":throw" is
4623 used after a ":catch" but before the |:finally|, the
4624 commands following the ":finally" (if present) up to
4625 the matching |:endtry| are executed. If the ":throw"
4626 is after the ":finally", commands up to the ":endtry"
4627 are skipped. At the ":endtry", this process applies
4628 again for the next dynamically surrounding ":try"
4629 (which may be found in a calling function or sourcing
4630 script), until a matching ":catch" has been found.
4631 If the exception is not caught, the command processing
4632 is terminated.
4633 Example: >
4634 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
4635<
4636
4637 *:ec* *:echo*
4638:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
4639 first {expr1} starts on a new line.
4640 Also see |:comment|.
4641 Use "\n" to start a new line. Use "\r" to move the
4642 cursor to the first column.
4643 Uses the highlighting set by the |:echohl| command.
4644 Cannot be followed by a comment.
4645 Example: >
4646 :echo "the value of 'shell' is" &shell
4647< A later redraw may make the message disappear again.
4648 To avoid that a command from before the ":echo" causes
4649 a redraw afterwards (redraws are often postponed until
4650 you type something), force a redraw with the |:redraw|
4651 command. Example: >
4652 :new | redraw | echo "there is a new window"
4653<
4654 *:echon*
4655:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
4656 |:comment|.
4657 Uses the highlighting set by the |:echohl| command.
4658 Cannot be followed by a comment.
4659 Example: >
4660 :echon "the value of 'shell' is " &shell
4661<
4662 Note the difference between using ":echo", which is a
4663 Vim command, and ":!echo", which is an external shell
4664 command: >
4665 :!echo % --> filename
4666< The arguments of ":!" are expanded, see |:_%|. >
4667 :!echo "%" --> filename or "filename"
4668< Like the previous example. Whether you see the double
4669 quotes or not depends on your 'shell'. >
4670 :echo % --> nothing
4671< The '%' is an illegal character in an expression. >
4672 :echo "%" --> %
4673< This just echoes the '%' character. >
4674 :echo expand("%") --> filename
4675< This calls the expand() function to expand the '%'.
4676
4677 *:echoh* *:echohl*
4678:echoh[l] {name} Use the highlight group {name} for the following
4679 |:echo|, |:echon| and |:echomsg| commands. Also used
4680 for the |input()| prompt. Example: >
4681 :echohl WarningMsg | echo "Don't panic!" | echohl None
4682< Don't forget to set the group back to "None",
4683 otherwise all following echo's will be highlighted.
4684
4685 *:echom* *:echomsg*
4686:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
4687 message in the |message-history|.
4688 Spaces are placed between the arguments as with the
4689 |:echo| command. But unprintable characters are
4690 displayed, not interpreted.
4691 Uses the highlighting set by the |:echohl| command.
4692 Example: >
4693 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
4694<
4695 *:echoe* *:echoerr*
4696:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
4697 message in the |message-history|. When used in a
4698 script or function the line number will be added.
4699 Spaces are placed between the arguments as with the
4700 :echo command. When used inside a try conditional,
4701 the message is raised as an error exception instead
4702 (see |try-echoerr|).
4703 Example: >
4704 :echoerr "This script just failed!"
4705< If you just want a highlighted message use |:echohl|.
4706 And to get a beep: >
4707 :exe "normal \<Esc>"
4708<
4709 *:exe* *:execute*
4710:exe[cute] {expr1} .. Executes the string that results from the evaluation
4711 of {expr1} as an Ex command. Multiple arguments are
4712 concatenated, with a space in between. {expr1} is
4713 used as the processed command, command line editing
4714 keys are not recognized.
4715 Cannot be followed by a comment.
4716 Examples: >
4717 :execute "buffer " nextbuf
4718 :execute "normal " count . "w"
4719<
4720 ":execute" can be used to append a command to commands
4721 that don't accept a '|'. Example: >
4722 :execute '!ls' | echo "theend"
4723
4724< ":execute" is also a nice way to avoid having to type
4725 control characters in a Vim script for a ":normal"
4726 command: >
4727 :execute "normal ixxx\<Esc>"
4728< This has an <Esc> character, see |expr-string|.
4729
4730 Note: The executed string may be any command-line, but
Bram Moolenaard8b02732005-01-14 21:48:43 +00004731 you cannot start or end a "while", "for" or "if"
4732 command. Thus this is illegal: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 :execute 'while i > 5'
4734 :execute 'echo "test" | break'
4735<
4736 It is allowed to have a "while" or "if" command
4737 completely in the executed string: >
4738 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
4739<
4740
4741 *:comment*
4742 ":execute", ":echo" and ":echon" cannot be followed by
4743 a comment directly, because they see the '"' as the
4744 start of a string. But, you can use '|' followed by a
4745 comment. Example: >
4746 :echo "foo" | "this is a comment
4747
4748==============================================================================
47498. Exception handling *exception-handling*
4750
4751The Vim script language comprises an exception handling feature. This section
4752explains how it can be used in a Vim script.
4753
4754Exceptions may be raised by Vim on an error or on interrupt, see
4755|catch-errors| and |catch-interrupt|. You can also explicitly throw an
4756exception by using the ":throw" command, see |throw-catch|.
4757
4758
4759TRY CONDITIONALS *try-conditionals*
4760
4761Exceptions can be caught or can cause cleanup code to be executed. You can
4762use a try conditional to specify catch clauses (that catch exceptions) and/or
4763a finally clause (to be executed for cleanup).
4764 A try conditional begins with a |:try| command and ends at the matching
4765|:endtry| command. In between, you can use a |:catch| command to start
4766a catch clause, or a |:finally| command to start a finally clause. There may
4767be none or multiple catch clauses, but there is at most one finally clause,
4768which must not be followed by any catch clauses. The lines before the catch
4769clauses and the finally clause is called a try block. >
4770
4771 :try
4772 : ...
4773 : ... TRY BLOCK
4774 : ...
4775 :catch /{pattern}/
4776 : ...
4777 : ... CATCH CLAUSE
4778 : ...
4779 :catch /{pattern}/
4780 : ...
4781 : ... CATCH CLAUSE
4782 : ...
4783 :finally
4784 : ...
4785 : ... FINALLY CLAUSE
4786 : ...
4787 :endtry
4788
4789The try conditional allows to watch code for exceptions and to take the
4790appropriate actions. Exceptions from the try block may be caught. Exceptions
4791from the try block and also the catch clauses may cause cleanup actions.
4792 When no exception is thrown during execution of the try block, the control
4793is transferred to the finally clause, if present. After its execution, the
4794script continues with the line following the ":endtry".
4795 When an exception occurs during execution of the try block, the remaining
4796lines in the try block are skipped. The exception is matched against the
4797patterns specified as arguments to the ":catch" commands. The catch clause
4798after the first matching ":catch" is taken, other catch clauses are not
4799executed. The catch clause ends when the next ":catch", ":finally", or
4800":endtry" command is reached - whatever is first. Then, the finally clause
4801(if present) is executed. When the ":endtry" is reached, the script execution
4802continues in the following line as usual.
4803 When an exception that does not match any of the patterns specified by the
4804":catch" commands is thrown in the try block, the exception is not caught by
4805that try conditional and none of the catch clauses is executed. Only the
4806finally clause, if present, is taken. The exception pends during execution of
4807the finally clause. It is resumed at the ":endtry", so that commands after
4808the ":endtry" are not executed and the exception might be caught elsewhere,
4809see |try-nesting|.
4810 When during execution of a catch clause another exception is thrown, the
4811remaining lines in that catch clause are not executed. The new exception is
4812not matched against the patterns in any of the ":catch" commands of the same
4813try conditional and none of its catch clauses is taken. If there is, however,
4814a finally clause, it is executed, and the exception pends during its
4815execution. The commands following the ":endtry" are not executed. The new
4816exception might, however, be caught elsewhere, see |try-nesting|.
4817 When during execution of the finally clause (if present) an exception is
4818thrown, the remaining lines in the finally clause are skipped. If the finally
4819clause has been taken because of an exception from the try block or one of the
4820catch clauses, the original (pending) exception is discarded. The commands
4821following the ":endtry" are not executed, and the exception from the finally
4822clause is propagated and can be caught elsewhere, see |try-nesting|.
4823
4824The finally clause is also executed, when a ":break" or ":continue" for
4825a ":while" loop enclosing the complete try conditional is executed from the
4826try block or a catch clause. Or when a ":return" or ":finish" is executed
4827from the try block or a catch clause of a try conditional in a function or
4828sourced script, respectively. The ":break", ":continue", ":return", or
4829":finish" pends during execution of the finally clause and is resumed when the
4830":endtry" is reached. It is, however, discarded when an exception is thrown
4831from the finally clause.
4832 When a ":break" or ":continue" for a ":while" loop enclosing the complete
4833try conditional or when a ":return" or ":finish" is encountered in the finally
4834clause, the rest of the finally clause is skipped, and the ":break",
4835":continue", ":return" or ":finish" is executed as usual. If the finally
4836clause has been taken because of an exception or an earlier ":break",
4837":continue", ":return", or ":finish" from the try block or a catch clause,
4838this pending exception or command is discarded.
4839
4840For examples see |throw-catch| and |try-finally|.
4841
4842
4843NESTING OF TRY CONDITIONALS *try-nesting*
4844
4845Try conditionals can be nested arbitrarily. That is, a complete try
4846conditional can be put into the try block, a catch clause, or the finally
4847clause of another try conditional. If the inner try conditional does not
4848catch an exception thrown in its try block or throws a new exception from one
4849of its catch clauses or its finally clause, the outer try conditional is
4850checked according to the rules above. If the inner try conditional is in the
4851try block of the outer try conditional, its catch clauses are checked, but
4852otherwise only the finally clause is executed. It does not matter for
4853nesting, whether the inner try conditional is directly contained in the outer
4854one, or whether the outer one sources a script or calls a function containing
4855the inner try conditional.
4856
4857When none of the active try conditionals catches an exception, just their
4858finally clauses are executed. Thereafter, the script processing terminates.
4859An error message is displayed in case of an uncaught exception explicitly
4860thrown by a ":throw" command. For uncaught error and interrupt exceptions
4861implicitly raised by Vim, the error message(s) or interrupt message are shown
4862as usual.
4863
4864For examples see |throw-catch|.
4865
4866
4867EXAMINING EXCEPTION HANDLING CODE *except-examine*
4868
4869Exception handling code can get tricky. If you are in doubt what happens, set
4870'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
4871script file. Then you see when an exception is thrown, discarded, caught, or
4872finished. When using a verbosity level of at least 14, things pending in
4873a finally clause are also shown. This information is also given in debug mode
4874(see |debug-scripts|).
4875
4876
4877THROWING AND CATCHING EXCEPTIONS *throw-catch*
4878
4879You can throw any number or string as an exception. Use the |:throw| command
4880and pass the value to be thrown as argument: >
4881 :throw 4711
4882 :throw "string"
4883< *throw-expression*
4884You can also specify an expression argument. The expression is then evaluated
4885first, and the result is thrown: >
4886 :throw 4705 + strlen("string")
4887 :throw strpart("strings", 0, 6)
4888
4889An exception might be thrown during evaluation of the argument of the ":throw"
4890command. Unless it is caught there, the expression evaluation is abandoned.
4891The ":throw" command then does not throw a new exception.
4892 Example: >
4893
4894 :function! Foo(arg)
4895 : try
4896 : throw a:arg
4897 : catch /foo/
4898 : endtry
4899 : return 1
4900 :endfunction
4901 :
4902 :function! Bar()
4903 : echo "in Bar"
4904 : return 4710
4905 :endfunction
4906 :
4907 :throw Foo("arrgh") + Bar()
4908
4909This throws "arrgh", and "in Bar" is not displayed since Bar() is not
4910executed. >
4911 :throw Foo("foo") + Bar()
4912however displays "in Bar" and throws 4711.
4913
4914Any other command that takes an expression as argument might also be
4915abandoned by an (uncaught) exception during the expression evaluation. The
4916exception is then propagated to the caller of the command.
4917 Example: >
4918
4919 :if Foo("arrgh")
4920 : echo "then"
4921 :else
4922 : echo "else"
4923 :endif
4924
4925Here neither of "then" or "else" is displayed.
4926
4927 *catch-order*
4928Exceptions can be caught by a try conditional with one or more |:catch|
4929commands, see |try-conditionals|. The values to be caught by each ":catch"
4930command can be specified as a pattern argument. The subsequent catch clause
4931gets executed when a matching exception is caught.
4932 Example: >
4933
4934 :function! Foo(value)
4935 : try
4936 : throw a:value
4937 : catch /^\d\+$/
4938 : echo "Number thrown"
4939 : catch /.*/
4940 : echo "String thrown"
4941 : endtry
4942 :endfunction
4943 :
4944 :call Foo(0x1267)
4945 :call Foo('string')
4946
4947The first call to Foo() displays "Number thrown", the second "String thrown".
4948An exception is matched against the ":catch" commands in the order they are
4949specified. Only the first match counts. So you should place the more
4950specific ":catch" first. The following order does not make sense: >
4951
4952 : catch /.*/
4953 : echo "String thrown"
4954 : catch /^\d\+$/
4955 : echo "Number thrown"
4956
4957The first ":catch" here matches always, so that the second catch clause is
4958never taken.
4959
4960 *throw-variables*
4961If you catch an exception by a general pattern, you may access the exact value
4962in the variable |v:exception|: >
4963
4964 : catch /^\d\+$/
4965 : echo "Number thrown. Value is" v:exception
4966
4967You may also be interested where an exception was thrown. This is stored in
4968|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
4969exception most recently caught as long it is not finished.
4970 Example: >
4971
4972 :function! Caught()
4973 : if v:exception != ""
4974 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
4975 : else
4976 : echo 'Nothing caught'
4977 : endif
4978 :endfunction
4979 :
4980 :function! Foo()
4981 : try
4982 : try
4983 : try
4984 : throw 4711
4985 : finally
4986 : call Caught()
4987 : endtry
4988 : catch /.*/
4989 : call Caught()
4990 : throw "oops"
4991 : endtry
4992 : catch /.*/
4993 : call Caught()
4994 : finally
4995 : call Caught()
4996 : endtry
4997 :endfunction
4998 :
4999 :call Foo()
5000
5001This displays >
5002
5003 Nothing caught
5004 Caught "4711" in function Foo, line 4
5005 Caught "oops" in function Foo, line 10
5006 Nothing caught
5007
5008A practical example: The following command ":LineNumber" displays the line
5009number in the script or function where it has been used: >
5010
5011 :function! LineNumber()
5012 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
5013 :endfunction
5014 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
5015<
5016 *try-nested*
5017An exception that is not caught by a try conditional can be caught by
5018a surrounding try conditional: >
5019
5020 :try
5021 : try
5022 : throw "foo"
5023 : catch /foobar/
5024 : echo "foobar"
5025 : finally
5026 : echo "inner finally"
5027 : endtry
5028 :catch /foo/
5029 : echo "foo"
5030 :endtry
5031
5032The inner try conditional does not catch the exception, just its finally
5033clause is executed. The exception is then caught by the outer try
5034conditional. The example displays "inner finally" and then "foo".
5035
5036 *throw-from-catch*
5037You can catch an exception and throw a new one to be caught elsewhere from the
5038catch clause: >
5039
5040 :function! Foo()
5041 : throw "foo"
5042 :endfunction
5043 :
5044 :function! Bar()
5045 : try
5046 : call Foo()
5047 : catch /foo/
5048 : echo "Caught foo, throw bar"
5049 : throw "bar"
5050 : endtry
5051 :endfunction
5052 :
5053 :try
5054 : call Bar()
5055 :catch /.*/
5056 : echo "Caught" v:exception
5057 :endtry
5058
5059This displays "Caught foo, throw bar" and then "Caught bar".
5060
5061 *rethrow*
5062There is no real rethrow in the Vim script language, but you may throw
5063"v:exception" instead: >
5064
5065 :function! Bar()
5066 : try
5067 : call Foo()
5068 : catch /.*/
5069 : echo "Rethrow" v:exception
5070 : throw v:exception
5071 : endtry
5072 :endfunction
5073< *try-echoerr*
5074Note that this method cannot be used to "rethrow" Vim error or interrupt
5075exceptions, because it is not possible to fake Vim internal exceptions.
5076Trying so causes an error exception. You should throw your own exception
5077denoting the situation. If you want to cause a Vim error exception containing
5078the original error exception value, you can use the |:echoerr| command: >
5079
5080 :try
5081 : try
5082 : asdf
5083 : catch /.*/
5084 : echoerr v:exception
5085 : endtry
5086 :catch /.*/
5087 : echo v:exception
5088 :endtry
5089
5090This code displays
5091
5092 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
5093
5094
5095CLEANUP CODE *try-finally*
5096
5097Scripts often change global settings and restore them at their end. If the
5098user however interrupts the script by pressing CTRL-C, the settings remain in
5099an inconsistent state. The same may happen to you in the development phase of
5100a script when an error occurs or you explicitly throw an exception without
5101catching it. You can solve these problems by using a try conditional with
5102a finally clause for restoring the settings. Its execution is guaranteed on
5103normal control flow, on error, on an explicit ":throw", and on interrupt.
5104(Note that errors and interrupts from inside the try conditional are converted
5105to exceptions. When not caught, they terminate the script after the finally
5106clause has been executed.)
5107Example: >
5108
5109 :try
5110 : let s:saved_ts = &ts
5111 : set ts=17
5112 :
5113 : " Do the hard work here.
5114 :
5115 :finally
5116 : let &ts = s:saved_ts
5117 : unlet s:saved_ts
5118 :endtry
5119
5120This method should be used locally whenever a function or part of a script
5121changes global settings which need to be restored on failure or normal exit of
5122that function or script part.
5123
5124 *break-finally*
5125Cleanup code works also when the try block or a catch clause is left by
5126a ":continue", ":break", ":return", or ":finish".
5127 Example: >
5128
5129 :let first = 1
5130 :while 1
5131 : try
5132 : if first
5133 : echo "first"
5134 : let first = 0
5135 : continue
5136 : else
5137 : throw "second"
5138 : endif
5139 : catch /.*/
5140 : echo v:exception
5141 : break
5142 : finally
5143 : echo "cleanup"
5144 : endtry
5145 : echo "still in while"
5146 :endwhile
5147 :echo "end"
5148
5149This displays "first", "cleanup", "second", "cleanup", and "end". >
5150
5151 :function! Foo()
5152 : try
5153 : return 4711
5154 : finally
5155 : echo "cleanup\n"
5156 : endtry
5157 : echo "Foo still active"
5158 :endfunction
5159 :
5160 :echo Foo() "returned by Foo"
5161
5162This displays "cleanup" and "4711 returned by Foo". You don't need to add an
5163extra ":return" in the finally clause. (Above all, this would override the
5164return value.)
5165
5166 *except-from-finally*
5167Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
5168a finally clause is possible, but not recommended since it abandons the
5169cleanup actions for the try conditional. But, of course, interrupt and error
5170exceptions might get raised from a finally clause.
5171 Example where an error in the finally clause stops an interrupt from
5172working correctly: >
5173
5174 :try
5175 : try
5176 : echo "Press CTRL-C for interrupt"
5177 : while 1
5178 : endwhile
5179 : finally
5180 : unlet novar
5181 : endtry
5182 :catch /novar/
5183 :endtry
5184 :echo "Script still running"
5185 :sleep 1
5186
5187If you need to put commands that could fail into a finally clause, you should
5188think about catching or ignoring the errors in these commands, see
5189|catch-errors| and |ignore-errors|.
5190
5191
5192CATCHING ERRORS *catch-errors*
5193
5194If you want to catch specific errors, you just have to put the code to be
5195watched in a try block and add a catch clause for the error message. The
5196presence of the try conditional causes all errors to be converted to an
5197exception. No message is displayed and |v:errmsg| is not set then. To find
5198the right pattern for the ":catch" command, you have to know how the format of
5199the error exception is.
5200 Error exceptions have the following format: >
5201
5202 Vim({cmdname}):{errmsg}
5203or >
5204 Vim:{errmsg}
5205
5206{cmdname} is the name of the command that failed; the second form is used when
5207the command name is not known. {errmsg} is the error message usually produced
5208when the error occurs outside try conditionals. It always begins with
5209a capital "E", followed by a two or three-digit error number, a colon, and
5210a space.
5211
5212Examples:
5213
5214The command >
5215 :unlet novar
5216normally produces the error message >
5217 E108: No such variable: "novar"
5218which is converted inside try conditionals to an exception >
5219 Vim(unlet):E108: No such variable: "novar"
5220
5221The command >
5222 :dwim
5223normally produces the error message >
5224 E492: Not an editor command: dwim
5225which is converted inside try conditionals to an exception >
5226 Vim:E492: Not an editor command: dwim
5227
5228You can catch all ":unlet" errors by a >
5229 :catch /^Vim(unlet):/
5230or all errors for misspelled command names by a >
5231 :catch /^Vim:E492:/
5232
5233Some error messages may be produced by different commands: >
5234 :function nofunc
5235and >
5236 :delfunction nofunc
5237both produce the error message >
5238 E128: Function name must start with a capital: nofunc
5239which is converted inside try conditionals to an exception >
5240 Vim(function):E128: Function name must start with a capital: nofunc
5241or >
5242 Vim(delfunction):E128: Function name must start with a capital: nofunc
5243respectively. You can catch the error by its number independently on the
5244command that caused it if you use the following pattern: >
5245 :catch /^Vim(\a\+):E128:/
5246
5247Some commands like >
5248 :let x = novar
5249produce multiple error messages, here: >
5250 E121: Undefined variable: novar
5251 E15: Invalid expression: novar
5252Only the first is used for the exception value, since it is the most specific
5253one (see |except-several-errors|). So you can catch it by >
5254 :catch /^Vim(\a\+):E121:/
5255
5256You can catch all errors related to the name "nofunc" by >
5257 :catch /\<nofunc\>/
5258
5259You can catch all Vim errors in the ":write" and ":read" commands by >
5260 :catch /^Vim(\(write\|read\)):E\d\+:/
5261
5262You can catch all Vim errors by the pattern >
5263 :catch /^Vim\((\a\+)\)\=:E\d\+:/
5264<
5265 *catch-text*
5266NOTE: You should never catch the error message text itself: >
5267 :catch /No such variable/
5268only works in the english locale, but not when the user has selected
5269a different language by the |:language| command. It is however helpful to
5270cite the message text in a comment: >
5271 :catch /^Vim(\a\+):E108:/ " No such variable
5272
5273
5274IGNORING ERRORS *ignore-errors*
5275
5276You can ignore errors in a specific Vim command by catching them locally: >
5277
5278 :try
5279 : write
5280 :catch
5281 :endtry
5282
5283But you are strongly recommended NOT to use this simple form, since it could
5284catch more than you want. With the ":write" command, some autocommands could
5285be executed and cause errors not related to writing, for instance: >
5286
5287 :au BufWritePre * unlet novar
5288
5289There could even be such errors you are not responsible for as a script
5290writer: a user of your script might have defined such autocommands. You would
5291then hide the error from the user.
5292 It is much better to use >
5293
5294 :try
5295 : write
5296 :catch /^Vim(write):/
5297 :endtry
5298
5299which only catches real write errors. So catch only what you'd like to ignore
5300intentionally.
5301
5302For a single command that does not cause execution of autocommands, you could
5303even suppress the conversion of errors to exceptions by the ":silent!"
5304command: >
5305 :silent! nunmap k
5306This works also when a try conditional is active.
5307
5308
5309CATCHING INTERRUPTS *catch-interrupt*
5310
5311When there are active try conditionals, an interrupt (CTRL-C) is converted to
5312the exception "Vim:Interrupt". You can catch it like every exception. The
5313script is not terminated, then.
5314 Example: >
5315
5316 :function! TASK1()
5317 : sleep 10
5318 :endfunction
5319
5320 :function! TASK2()
5321 : sleep 20
5322 :endfunction
5323
5324 :while 1
5325 : let command = input("Type a command: ")
5326 : try
5327 : if command == ""
5328 : continue
5329 : elseif command == "END"
5330 : break
5331 : elseif command == "TASK1"
5332 : call TASK1()
5333 : elseif command == "TASK2"
5334 : call TASK2()
5335 : else
5336 : echo "\nIllegal command:" command
5337 : continue
5338 : endif
5339 : catch /^Vim:Interrupt$/
5340 : echo "\nCommand interrupted"
5341 : " Caught the interrupt. Continue with next prompt.
5342 : endtry
5343 :endwhile
5344
5345You can interrupt a task here by pressing CTRL-C; the script then asks for
5346a new command. If you press CTRL-C at the prompt, the script is terminated.
5347
5348For testing what happens when CTRL-C would be pressed on a specific line in
5349your script, use the debug mode and execute the |>quit| or |>interrupt|
5350command on that line. See |debug-scripts|.
5351
5352
5353CATCHING ALL *catch-all*
5354
5355The commands >
5356
5357 :catch /.*/
5358 :catch //
5359 :catch
5360
5361catch everything, error exceptions, interrupt exceptions and exceptions
5362explicitly thrown by the |:throw| command. This is useful at the top level of
5363a script in order to catch unexpected things.
5364 Example: >
5365
5366 :try
5367 :
5368 : " do the hard work here
5369 :
5370 :catch /MyException/
5371 :
5372 : " handle known problem
5373 :
5374 :catch /^Vim:Interrupt$/
5375 : echo "Script interrupted"
5376 :catch /.*/
5377 : echo "Internal error (" . v:exception . ")"
5378 : echo " - occurred at " . v:throwpoint
5379 :endtry
5380 :" end of script
5381
5382Note: Catching all might catch more things than you want. Thus, you are
5383strongly encouraged to catch only for problems that you can really handle by
5384specifying a pattern argument to the ":catch".
5385 Example: Catching all could make it nearly impossible to interrupt a script
5386by pressing CTRL-C: >
5387
5388 :while 1
5389 : try
5390 : sleep 1
5391 : catch
5392 : endtry
5393 :endwhile
5394
5395
5396EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
5397
5398Exceptions may be used during execution of autocommands. Example: >
5399
5400 :autocmd User x try
5401 :autocmd User x throw "Oops!"
5402 :autocmd User x catch
5403 :autocmd User x echo v:exception
5404 :autocmd User x endtry
5405 :autocmd User x throw "Arrgh!"
5406 :autocmd User x echo "Should not be displayed"
5407 :
5408 :try
5409 : doautocmd User x
5410 :catch
5411 : echo v:exception
5412 :endtry
5413
5414This displays "Oops!" and "Arrgh!".
5415
5416 *except-autocmd-Pre*
5417For some commands, autocommands get executed before the main action of the
5418command takes place. If an exception is thrown and not caught in the sequence
5419of autocommands, the sequence and the command that caused its execution are
5420abandoned and the exception is propagated to the caller of the command.
5421 Example: >
5422
5423 :autocmd BufWritePre * throw "FAIL"
5424 :autocmd BufWritePre * echo "Should not be displayed"
5425 :
5426 :try
5427 : write
5428 :catch
5429 : echo "Caught:" v:exception "from" v:throwpoint
5430 :endtry
5431
5432Here, the ":write" command does not write the file currently being edited (as
5433you can see by checking 'modified'), since the exception from the BufWritePre
5434autocommand abandons the ":write". The exception is then caught and the
5435script displays: >
5436
5437 Caught: FAIL from BufWrite Auto commands for "*"
5438<
5439 *except-autocmd-Post*
5440For some commands, autocommands get executed after the main action of the
5441command has taken place. If this main action fails and the command is inside
5442an active try conditional, the autocommands are skipped and an error exception
5443is thrown that can be caught by the caller of the command.
5444 Example: >
5445
5446 :autocmd BufWritePost * echo "File successfully written!"
5447 :
5448 :try
5449 : write /i/m/p/o/s/s/i/b/l/e
5450 :catch
5451 : echo v:exception
5452 :endtry
5453
5454This just displays: >
5455
5456 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
5457
5458If you really need to execute the autocommands even when the main action
5459fails, trigger the event from the catch clause.
5460 Example: >
5461
5462 :autocmd BufWritePre * set noreadonly
5463 :autocmd BufWritePost * set readonly
5464 :
5465 :try
5466 : write /i/m/p/o/s/s/i/b/l/e
5467 :catch
5468 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
5469 :endtry
5470<
5471You can also use ":silent!": >
5472
5473 :let x = "ok"
5474 :let v:errmsg = ""
5475 :autocmd BufWritePost * if v:errmsg != ""
5476 :autocmd BufWritePost * let x = "after fail"
5477 :autocmd BufWritePost * endif
5478 :try
5479 : silent! write /i/m/p/o/s/s/i/b/l/e
5480 :catch
5481 :endtry
5482 :echo x
5483
5484This displays "after fail".
5485
5486If the main action of the command does not fail, exceptions from the
5487autocommands will be catchable by the caller of the command: >
5488
5489 :autocmd BufWritePost * throw ":-("
5490 :autocmd BufWritePost * echo "Should not be displayed"
5491 :
5492 :try
5493 : write
5494 :catch
5495 : echo v:exception
5496 :endtry
5497<
5498 *except-autocmd-Cmd*
5499For some commands, the normal action can be replaced by a sequence of
5500autocommands. Exceptions from that sequence will be catchable by the caller
5501of the command.
5502 Example: For the ":write" command, the caller cannot know whether the file
5503had actually been written when the exception occurred. You need to tell it in
5504some way. >
5505
5506 :if !exists("cnt")
5507 : let cnt = 0
5508 :
5509 : autocmd BufWriteCmd * if &modified
5510 : autocmd BufWriteCmd * let cnt = cnt + 1
5511 : autocmd BufWriteCmd * if cnt % 3 == 2
5512 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5513 : autocmd BufWriteCmd * endif
5514 : autocmd BufWriteCmd * write | set nomodified
5515 : autocmd BufWriteCmd * if cnt % 3 == 0
5516 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5517 : autocmd BufWriteCmd * endif
5518 : autocmd BufWriteCmd * echo "File successfully written!"
5519 : autocmd BufWriteCmd * endif
5520 :endif
5521 :
5522 :try
5523 : write
5524 :catch /^BufWriteCmdError$/
5525 : if &modified
5526 : echo "Error on writing (file contents not changed)"
5527 : else
5528 : echo "Error after writing"
5529 : endif
5530 :catch /^Vim(write):/
5531 : echo "Error on writing"
5532 :endtry
5533
5534When this script is sourced several times after making changes, it displays
5535first >
5536 File successfully written!
5537then >
5538 Error on writing (file contents not changed)
5539then >
5540 Error after writing
5541etc.
5542
5543 *except-autocmd-ill*
5544You cannot spread a try conditional over autocommands for different events.
5545The following code is ill-formed: >
5546
5547 :autocmd BufWritePre * try
5548 :
5549 :autocmd BufWritePost * catch
5550 :autocmd BufWritePost * echo v:exception
5551 :autocmd BufWritePost * endtry
5552 :
5553 :write
5554
5555
5556EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
5557
5558Some programming languages allow to use hierarchies of exception classes or to
5559pass additional information with the object of an exception class. You can do
5560similar things in Vim.
5561 In order to throw an exception from a hierarchy, just throw the complete
5562class name with the components separated by a colon, for instance throw the
5563string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
5564 When you want to pass additional information with your exception class, add
5565it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
5566for an error when writing "myfile".
5567 With the appropriate patterns in the ":catch" command, you can catch for
5568base classes or derived classes of your hierarchy. Additional information in
5569parentheses can be cut out from |v:exception| with the ":substitute" command.
5570 Example: >
5571
5572 :function! CheckRange(a, func)
5573 : if a:a < 0
5574 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
5575 : endif
5576 :endfunction
5577 :
5578 :function! Add(a, b)
5579 : call CheckRange(a:a, "Add")
5580 : call CheckRange(a:b, "Add")
5581 : let c = a:a + a:b
5582 : if c < 0
5583 : throw "EXCEPT:MATHERR:OVERFLOW"
5584 : endif
5585 : return c
5586 :endfunction
5587 :
5588 :function! Div(a, b)
5589 : call CheckRange(a:a, "Div")
5590 : call CheckRange(a:b, "Div")
5591 : if (a:b == 0)
5592 : throw "EXCEPT:MATHERR:ZERODIV"
5593 : endif
5594 : return a:a / a:b
5595 :endfunction
5596 :
5597 :function! Write(file)
5598 : try
5599 : execute "write" a:file
5600 : catch /^Vim(write):/
5601 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
5602 : endtry
5603 :endfunction
5604 :
5605 :try
5606 :
5607 : " something with arithmetics and I/O
5608 :
5609 :catch /^EXCEPT:MATHERR:RANGE/
5610 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
5611 : echo "Range error in" function
5612 :
5613 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
5614 : echo "Math error"
5615 :
5616 :catch /^EXCEPT:IO/
5617 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
5618 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
5619 : if file !~ '^/'
5620 : let file = dir . "/" . file
5621 : endif
5622 : echo 'I/O error for "' . file . '"'
5623 :
5624 :catch /^EXCEPT/
5625 : echo "Unspecified error"
5626 :
5627 :endtry
5628
5629The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
5630a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
5631exceptions with the "Vim" prefix; they are reserved for Vim.
5632 Vim error exceptions are parameterized with the name of the command that
5633failed, if known. See |catch-errors|.
5634
5635
5636PECULIARITIES
5637 *except-compat*
5638The exception handling concept requires that the command sequence causing the
5639exception is aborted immediately and control is transferred to finally clauses
5640and/or a catch clause.
5641
5642In the Vim script language there are cases where scripts and functions
5643continue after an error: in functions without the "abort" flag or in a command
5644after ":silent!", control flow goes to the following line, and outside
5645functions, control flow goes to the line following the outermost ":endwhile"
5646or ":endif". On the other hand, errors should be catchable as exceptions
5647(thus, requiring the immediate abortion).
5648
5649This problem has been solved by converting errors to exceptions and using
5650immediate abortion (if not suppressed by ":silent!") only when a try
5651conditional is active. This is no restriction since an (error) exception can
5652be caught only from an active try conditional. If you want an immediate
5653termination without catching the error, just use a try conditional without
5654catch clause. (You can cause cleanup code being executed before termination
5655by specifying a finally clause.)
5656
5657When no try conditional is active, the usual abortion and continuation
5658behavior is used instead of immediate abortion. This ensures compatibility of
5659scripts written for Vim 6.1 and earlier.
5660
5661However, when sourcing an existing script that does not use exception handling
5662commands (or when calling one of its functions) from inside an active try
5663conditional of a new script, you might change the control flow of the existing
5664script on error. You get the immediate abortion on error and can catch the
5665error in the new script. If however the sourced script suppresses error
5666messages by using the ":silent!" command (checking for errors by testing
5667|v:errmsg| if appropriate), its execution path is not changed. The error is
5668not converted to an exception. (See |:silent|.) So the only remaining cause
5669where this happens is for scripts that don't care about errors and produce
5670error messages. You probably won't want to use such code from your new
5671scripts.
5672
5673 *except-syntax-err*
5674Syntax errors in the exception handling commands are never caught by any of
5675the ":catch" commands of the try conditional they belong to. Its finally
5676clauses, however, is executed.
5677 Example: >
5678
5679 :try
5680 : try
5681 : throw 4711
5682 : catch /\(/
5683 : echo "in catch with syntax error"
5684 : catch
5685 : echo "inner catch-all"
5686 : finally
5687 : echo "inner finally"
5688 : endtry
5689 :catch
5690 : echo 'outer catch-all caught "' . v:exception . '"'
5691 : finally
5692 : echo "outer finally"
5693 :endtry
5694
5695This displays: >
5696 inner finally
5697 outer catch-all caught "Vim(catch):E54: Unmatched \("
5698 outer finally
5699The original exception is discarded and an error exception is raised, instead.
5700
5701 *except-single-line*
5702The ":try", ":catch", ":finally", and ":endtry" commands can be put on
5703a single line, but then syntax errors may make it difficult to recognize the
5704"catch" line, thus you better avoid this.
5705 Example: >
5706 :try | unlet! foo # | catch | endtry
5707raises an error exception for the trailing characters after the ":unlet!"
5708argument, but does not see the ":catch" and ":endtry" commands, so that the
5709error exception is discarded and the "E488: Trailing characters" message gets
5710displayed.
5711
5712 *except-several-errors*
5713When several errors appear in a single command, the first error message is
5714usually the most specific one and therefor converted to the error exception.
5715 Example: >
5716 echo novar
5717causes >
5718 E121: Undefined variable: novar
5719 E15: Invalid expression: novar
5720The value of the error exception inside try conditionals is: >
5721 Vim(echo):E121: Undefined variable: novar
5722< *except-syntax-error*
5723But when a syntax error is detected after a normal error in the same command,
5724the syntax error is used for the exception being thrown.
5725 Example: >
5726 unlet novar #
5727causes >
5728 E108: No such variable: "novar"
5729 E488: Trailing characters
5730The value of the error exception inside try conditionals is: >
5731 Vim(unlet):E488: Trailing characters
5732This is done because the syntax error might change the execution path in a way
5733not intended by the user. Example: >
5734 try
5735 try | unlet novar # | catch | echo v:exception | endtry
5736 catch /.*/
5737 echo "outer catch:" v:exception
5738 endtry
5739This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
5740a "E600: Missing :endtry" error message is given, see |except-single-line|.
5741
5742==============================================================================
57439. Examples *eval-examples*
5744
5745Printing in Hex ~
5746>
5747 :" The function Nr2Hex() returns the Hex string of a number.
5748 :func Nr2Hex(nr)
5749 : let n = a:nr
5750 : let r = ""
5751 : while n
5752 : let r = '0123456789ABCDEF'[n % 16] . r
5753 : let n = n / 16
5754 : endwhile
5755 : return r
5756 :endfunc
5757
5758 :" The function String2Hex() converts each character in a string to a two
5759 :" character Hex string.
5760 :func String2Hex(str)
5761 : let out = ''
5762 : let ix = 0
5763 : while ix < strlen(a:str)
5764 : let out = out . Nr2Hex(char2nr(a:str[ix]))
5765 : let ix = ix + 1
5766 : endwhile
5767 : return out
5768 :endfunc
5769
5770Example of its use: >
5771 :echo Nr2Hex(32)
5772result: "20" >
5773 :echo String2Hex("32")
5774result: "3332"
5775
5776
5777Sorting lines (by Robert Webb) ~
5778
5779Here is a Vim script to sort lines. Highlight the lines in Vim and type
5780":Sort". This doesn't call any external programs so it'll work on any
5781platform. The function Sort() actually takes the name of a comparison
5782function as its argument, like qsort() does in C. So you could supply it
5783with different comparison functions in order to sort according to date etc.
5784>
5785 :" Function for use with Sort(), to compare two strings.
5786 :func! Strcmp(str1, str2)
5787 : if (a:str1 < a:str2)
5788 : return -1
5789 : elseif (a:str1 > a:str2)
5790 : return 1
5791 : else
5792 : return 0
5793 : endif
5794 :endfunction
5795
5796 :" Sort lines. SortR() is called recursively.
5797 :func! SortR(start, end, cmp)
5798 : if (a:start >= a:end)
5799 : return
5800 : endif
5801 : let partition = a:start - 1
5802 : let middle = partition
5803 : let partStr = getline((a:start + a:end) / 2)
5804 : let i = a:start
5805 : while (i <= a:end)
5806 : let str = getline(i)
5807 : exec "let result = " . a:cmp . "(str, partStr)"
5808 : if (result <= 0)
5809 : " Need to put it before the partition. Swap lines i and partition.
5810 : let partition = partition + 1
5811 : if (result == 0)
5812 : let middle = partition
5813 : endif
5814 : if (i != partition)
5815 : let str2 = getline(partition)
5816 : call setline(i, str2)
5817 : call setline(partition, str)
5818 : endif
5819 : endif
5820 : let i = i + 1
5821 : endwhile
5822
5823 : " Now we have a pointer to the "middle" element, as far as partitioning
5824 : " goes, which could be anywhere before the partition. Make sure it is at
5825 : " the end of the partition.
5826 : if (middle != partition)
5827 : let str = getline(middle)
5828 : let str2 = getline(partition)
5829 : call setline(middle, str2)
5830 : call setline(partition, str)
5831 : endif
5832 : call SortR(a:start, partition - 1, a:cmp)
5833 : call SortR(partition + 1, a:end, a:cmp)
5834 :endfunc
5835
5836 :" To Sort a range of lines, pass the range to Sort() along with the name of a
5837 :" function that will compare two lines.
5838 :func! Sort(cmp) range
5839 : call SortR(a:firstline, a:lastline, a:cmp)
5840 :endfunc
5841
5842 :" :Sort takes a range of lines and sorts them.
5843 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
5844<
5845 *sscanf*
5846There is no sscanf() function in Vim. If you need to extract parts from a
5847line, you can use matchstr() and substitute() to do it. This example shows
5848how to get the file name, line number and column number out of a line like
5849"foobar.txt, 123, 45". >
5850 :" Set up the match bit
5851 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
5852 :"get the part matching the whole expression
5853 :let l = matchstr(line, mx)
5854 :"get each item out of the match
5855 :let file = substitute(l, mx, '\1', '')
5856 :let lnum = substitute(l, mx, '\2', '')
5857 :let col = substitute(l, mx, '\3', '')
5858
5859The input is in the variable "line", the results in the variables "file",
5860"lnum" and "col". (idea from Michael Geddes)
5861
5862==============================================================================
586310. No +eval feature *no-eval-feature*
5864
5865When the |+eval| feature was disabled at compile time, none of the expression
5866evaluation commands are available. To prevent this from causing Vim scripts
5867to generate all kinds of errors, the ":if" and ":endif" commands are still
5868recognized, though the argument of the ":if" and everything between the ":if"
5869and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
5870only if the commands are at the start of the line. The ":else" command is not
5871recognized.
5872
5873Example of how to avoid executing commands when the |+eval| feature is
5874missing: >
5875
5876 :if 1
5877 : echo "Expression evaluation is compiled in"
5878 :else
5879 : echo "You will _never_ see this message"
5880 :endif
5881
5882==============================================================================
588311. The sandbox *eval-sandbox* *sandbox* *E48*
5884
5885The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
5886options are evaluated in a sandbox. This means that you are protected from
5887these expressions having nasty side effects. This gives some safety for when
5888these options are set from a modeline. It is also used when the command from
5889a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005890The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891
5892These items are not allowed in the sandbox:
5893 - changing the buffer text
5894 - defining or changing mapping, autocommands, functions, user commands
5895 - setting certain options (see |option-summary|)
5896 - executing a shell command
5897 - reading or writing a file
5898 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00005899This is not guaranteed 100% secure, but it should block most attacks.
5900
5901 *:san* *:sandbox*
5902:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
5903 option that may have been set from a modeline, e.g.
5904 'foldexpr'.
5905
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906
5907 vim:tw=78:ts=8:ft=help:norl: